diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index fbf4badadde..9e576f2108a 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -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) diff --git a/src/Autocomplete/src/AutocompleteResultsExecutor.php b/src/Autocomplete/src/AutocompleteResultsExecutor.php index ea94ed07fbd..0061ca8a55b 100644 --- a/src/Autocomplete/src/AutocompleteResultsExecutor.php +++ b/src/Autocomplete/src/AutocompleteResultsExecutor.php @@ -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 = []; diff --git a/src/Autocomplete/src/Controller/EntityAutocompleteController.php b/src/Autocomplete/src/Controller/EntityAutocompleteController.php index 6188ca21f7d..f8d855120e3 100644 --- a/src/Autocomplete/src/Controller/EntityAutocompleteController.php +++ b/src/Autocomplete/src/Controller/EntityAutocompleteController.php @@ -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) { diff --git a/src/Autocomplete/src/DependencyInjection/AutocompleteFormTypePass.php b/src/Autocomplete/src/DependencyInjection/AutocompleteFormTypePass.php index 68f0b541648..7ef489a65dc 100644 --- a/src/Autocomplete/src/DependencyInjection/AutocompleteFormTypePass.php +++ b/src/Autocomplete/src/DependencyInjection/AutocompleteFormTypePass.php @@ -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); @@ -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); @@ -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); diff --git a/src/Autocomplete/src/Doctrine/EntityMetadata.php b/src/Autocomplete/src/Doctrine/EntityMetadata.php index 9a121385d90..6094d0b45e1 100644 --- a/src/Autocomplete/src/Doctrine/EntityMetadata.php +++ b/src/Autocomplete/src/Doctrine/EntityMetadata.php @@ -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())); } /** @@ -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 diff --git a/src/Autocomplete/src/Doctrine/EntityMetadataFactory.php b/src/Autocomplete/src/Doctrine/EntityMetadataFactory.php index 8526a05c086..d1cddb4a6bf 100644 --- a/src/Autocomplete/src/Doctrine/EntityMetadataFactory.php +++ b/src/Autocomplete/src/Doctrine/EntityMetadataFactory.php @@ -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; @@ -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; diff --git a/src/Autocomplete/src/Doctrine/EntitySearchUtil.php b/src/Autocomplete/src/Doctrine/EntitySearchUtil.php index 7cdf105764b..d7e09d12745 100644 --- a/src/Autocomplete/src/Doctrine/EntitySearchUtil.php +++ b/src/Autocomplete/src/Doctrine/EntitySearchUtil.php @@ -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]; @@ -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']); } } diff --git a/src/Autocomplete/src/Form/AutocompleteChoiceTypeExtension.php b/src/Autocomplete/src/Form/AutocompleteChoiceTypeExtension.php index 9c40fd39270..3942018d76e 100644 --- a/src/Autocomplete/src/Form/AutocompleteChoiceTypeExtension.php +++ b/src/Autocomplete/src/Form/AutocompleteChoiceTypeExtension.php @@ -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) ? '&' : '?', @@ -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)) { diff --git a/src/Autocomplete/src/Form/AutocompleteEntityTypeSubscriber.php b/src/Autocomplete/src/Form/AutocompleteEntityTypeSubscriber.php index e528953a228..d81e2d5f77d 100644 --- a/src/Autocomplete/src/Form/AutocompleteEntityTypeSubscriber.php +++ b/src/Autocomplete/src/Form/AutocompleteEntityTypeSubscriber.php @@ -23,7 +23,7 @@ * * @internal * - * @deprecated since 2.13 + * @deprecated since UX 2.13 */ final class AutocompleteEntityTypeSubscriber implements EventSubscriberInterface { @@ -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]); diff --git a/src/Autocomplete/src/Form/BaseEntityAutocompleteType.php b/src/Autocomplete/src/Form/BaseEntityAutocompleteType.php index 0a8784d583c..f4e002d0fe4 100644 --- a/src/Autocomplete/src/Form/BaseEntityAutocompleteType.php +++ b/src/Autocomplete/src/Form/BaseEntityAutocompleteType.php @@ -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(), [ diff --git a/src/Autocomplete/src/Form/ParentEntityAutocompleteType.php b/src/Autocomplete/src/Form/ParentEntityAutocompleteType.php index 417af9e693d..b1d41900af1 100644 --- a/src/Autocomplete/src/Form/ParentEntityAutocompleteType.php +++ b/src/Autocomplete/src/Form/ParentEntityAutocompleteType.php @@ -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 { @@ -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 diff --git a/src/Autocomplete/src/Maker/MakeAutocompleteField.php b/src/Autocomplete/src/Maker/MakeAutocompleteField.php index 8076a1b5852..41ef37a4f80 100644 --- a/src/Autocomplete/src/Maker/MakeAutocompleteField.php +++ b/src/Autocomplete/src/Maker/MakeAutocompleteField.php @@ -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. %s)', $defaultClass), + \sprintf('Choose a name for your entity field class (e.g. %s)', $defaultClass), $defaultClass ); } @@ -146,7 +146,7 @@ public function generate(InputInterface $input, ConsoleStyle $io, Generator $gen '', ' $builder', ' // ...', - sprintf(' ->add(\'%s\', %s::class)', Str::asLowerCamelCase($entityClassDetails->getShortName()), $classDetails->getShortName()), + \sprintf(' ->add(\'%s\', %s::class)', Str::asLowerCamelCase($entityClassDetails->getShortName()), $classDetails->getShortName()), ' ;', ]); } diff --git a/src/Autocomplete/tests/Functional/AutocompleteFormRenderingTest.php b/src/Autocomplete/tests/Functional/AutocompleteFormRenderingTest.php index 72d801b6f82..92c7695c98c 100644 --- a/src/Autocomplete/tests/Functional/AutocompleteFormRenderingTest.php +++ b/src/Autocomplete/tests/Functional/AutocompleteFormRenderingTest.php @@ -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) ; } diff --git a/src/Chartjs/src/Twig/ChartExtension.php b/src/Chartjs/src/Twig/ChartExtension.php index 78fa73dcb61..e893d31728d 100644 --- a/src/Chartjs/src/Twig/ChartExtension.php +++ b/src/Chartjs/src/Twig/ChartExtension.php @@ -73,6 +73,6 @@ public function renderChart(Chart $chart, array $attributes = []): string } } - return sprintf('', $stimulusAttributes); + return \sprintf('', $stimulusAttributes); } } diff --git a/src/Icons/src/Command/ImportIconCommand.php b/src/Icons/src/Command/ImportIconCommand.php index d5320e109de..b287231d203 100644 --- a/src/Icons/src/Command/ImportIconCommand.php +++ b/src/Icons/src/Command/ImportIconCommand.php @@ -57,7 +57,7 @@ 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; @@ -65,7 +65,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int [$fullName, $prefix, $name] = $matches; - $io->comment(sprintf('Importing %s...', $fullName)); + $io->comment(\sprintf('Importing %s...', $fullName)); try { $svg = $this->iconify->fetchSvg($prefix, $name); @@ -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( " ✓ Imported %s:%s (License: %s). Render with: {{ ux_icon('%s') }}", $prefix, $name, diff --git a/src/Icons/src/Command/LockIconsCommand.php b/src/Icons/src/Command/LockIconsCommand.php index 6f092348529..c58a258f9e3 100644 --- a/src/Icons/src/Command/LockIconsCommand.php +++ b/src/Icons/src/Command/LockIconsCommand.php @@ -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( " ✓ Imported %s:%s (License: %s). Render with: {{ ux_icon('%s') }}", $prefix, $name, @@ -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; } diff --git a/src/Icons/src/Command/SearchIconCommand.php b/src/Icons/src/Command/SearchIconCommand.php index 6d1bc79afe3..f3ded32fd14 100644 --- a/src/Icons/src/Command/SearchIconCommand.php +++ b/src/Icons/src/Command/SearchIconCommand.php @@ -89,9 +89,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (1 === \count($iconSets)) { $iconSet = reset($iconSets); $searchTerm = 'arrow'; - $io->writeln(sprintf('Search "%s" in %s icons:', $searchTerm, $iconSet['name'])); + $io->writeln(\sprintf('Search "%s" in %s icons:', $searchTerm, $iconSet['name'])); $io->newLine(); - $io->writeln(' '.sprintf('php bin/console ux:icons:search %s %s', $iconSet['prefix'], $searchTerm)); + $io->writeln(' '.\sprintf('php bin/console ux:icons:search %s %s', $iconSet['prefix'], $searchTerm)); $io->newLine(); } @@ -99,7 +99,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } if (false === $iconSet = reset($iconSets)) { - $io->error(sprintf('No icon sets found for prefix "%s".', $prefix)); + $io->error(\sprintf('No icon sets found for prefix "%s".', $prefix)); return Command::INVALID; } @@ -115,7 +115,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $iconSet = $iconSets[$prefix]; } - $io->write(sprintf('Searching %s icons "%s"...', $iconSet['name'], $name)); + $io->write(\sprintf('Searching %s icons "%s"...', $iconSet['name'], $name)); try { $results = $this->iconify->searchIcons($prefix, $name); } catch (\Throwable $e) { @@ -138,19 +138,19 @@ protected function execute(InputInterface $input, OutputInterface $output): int $nbPages = \count($iconPages); $cursor = new Cursor($output); - $io->writeln(sprintf('Found %d icons.', \count($icons))); + $io->writeln(\sprintf('Found %d icons.', \count($icons))); foreach ($iconPages as $page => $iconPage) { $this->renderIconTable($io, $prefix, $name, $iconPage); if ($page + 1 === $nbPages) { break; } - if (!$io->confirm(sprintf('Page %d/%d. Continue?', $page + 1, $nbPages))) { + if (!$io->confirm(\sprintf('Page %d/%d. Continue?', $page + 1, $nbPages))) { break; } $cursor->moveUp(5)->clearLineAfter(); } $io->newLine(); - $io->writeln(sprintf('See all the %s icons on: https://ux.symfony.com/icons?set=%s', $prefix, $prefix)); + $io->writeln(\sprintf('See all the %s icons on: https://ux.symfony.com/icons?set=%s', $prefix, $prefix)); $io->newLine(); return Command::SUCCESS; @@ -225,6 +225,6 @@ private function formatIcon(OutputInterface $output, string $icon, bool $padding [$prefix, $name] = explode(':', $icon.':'); $padding = $padding ? ' ' : ''; - return sprintf('%s%s:%s%s', $padding, $prefix, $name, $padding); + return \sprintf('%s%s:%s%s', $padding, $prefix, $name, $padding); } } diff --git a/src/Icons/src/Command/WarmCacheCommand.php b/src/Icons/src/Command/WarmCacheCommand.php index 548c6f3c5fb..1451a7cfc89 100644 --- a/src/Icons/src/Command/WarmCacheCommand.php +++ b/src/Icons/src/Command/WarmCacheCommand.php @@ -42,7 +42,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->warmer->warm( onSuccess: function (string $name) use ($io) { if ($io->isVerbose()) { - $io->writeln(sprintf(' Warmed icon %s.', $name)); + $io->writeln(\sprintf(' Warmed icon %s.', $name)); } }, ); diff --git a/src/Icons/src/Icon.php b/src/Icons/src/Icon.php index 0aedfd52c9f..41883a98254 100644 --- a/src/Icons/src/Icon.php +++ b/src/Icons/src/Icon.php @@ -28,7 +28,7 @@ final class Icon implements \Stringable public static function idToName(string $id): string { if (!self::isValidId($id)) { - throw new \InvalidArgumentException(sprintf('The id "%s" is not a valid id.', $id)); + throw new \InvalidArgumentException(\sprintf('The id "%s" is not a valid id.', $id)); } return str_replace('--', ':', $id); @@ -44,7 +44,7 @@ public static function idToName(string $id): string public static function nameToId(string $name): string { if (!self::isValidName($name)) { - throw new \InvalidArgumentException(sprintf('The name "%s" is not a valid name.', $name)); + throw new \InvalidArgumentException(\sprintf('The name "%s" is not a valid name.', $name)); } return str_replace(':', '--', $name); @@ -82,7 +82,7 @@ public static function fromFile(string $filename): self throw new \LogicException('The "DOM" PHP extension is required to create icons from files.'); } - $svg = file_get_contents($filename) ?: throw new \RuntimeException(sprintf('The icon file "%s" could not be read.', $filename)); + $svg = file_get_contents($filename) ?: throw new \RuntimeException(\sprintf('The icon file "%s" could not be read.', $filename)); $svgDoc = new \DOMDocument(); $svgDoc->preserveWhiteSpace = false; @@ -90,20 +90,20 @@ public static function fromFile(string $filename): self try { $svgDoc->loadXML($svg); } catch (\Throwable $e) { - throw new \RuntimeException(sprintf('The icon file "%s" does not contain a valid SVG.', $filename), previous: $e); + throw new \RuntimeException(\sprintf('The icon file "%s" does not contain a valid SVG.', $filename), previous: $e); } $svgElements = $svgDoc->getElementsByTagName('svg'); if (0 === $svgElements->length) { - throw new \RuntimeException(sprintf('The icon file "%s" does not contain a valid SVG.', $filename)); + throw new \RuntimeException(\sprintf('The icon file "%s" does not contain a valid SVG.', $filename)); } if (1 !== $svgElements->length) { - throw new \RuntimeException(sprintf('The icon file "%s" contains more than one SVG.', $filename)); + throw new \RuntimeException(\sprintf('The icon file "%s" contains more than one SVG.', $filename)); } - $svgElement = $svgElements->item(0) ?? throw new \RuntimeException(sprintf('The icon file "%s" does not contain a valid SVG.', $filename)); + $svgElement = $svgElements->item(0) ?? throw new \RuntimeException(\sprintf('The icon file "%s" does not contain a valid SVG.', $filename)); $innerSvg = ''; @@ -122,7 +122,7 @@ public static function fromFile(string $filename): self } if (!$innerSvg) { - throw new \RuntimeException(sprintf('The icon file "%s" contains an empty SVG.', $filename)); + throw new \RuntimeException(\sprintf('The icon file "%s" contains an empty SVG.', $filename)); } $attributes = array_map(static fn (\DOMAttr $a) => $a->value, [...$svgElement->attributes]); @@ -182,15 +182,15 @@ public function withAttributes(array $attributes): self { foreach ($attributes as $name => $value) { if (!\is_string($name)) { - throw new \InvalidArgumentException(sprintf('Attribute names must be string, "%s" given.', get_debug_type($name))); + throw new \InvalidArgumentException(\sprintf('Attribute names must be string, "%s" given.', get_debug_type($name))); } if (!ctype_alnum($name) && !str_contains($name, '-')) { - throw new \InvalidArgumentException(sprintf('Invalid attribute name "%s".', $name)); + throw new \InvalidArgumentException(\sprintf('Invalid attribute name "%s".', $name)); } if (!\is_string($value) && !\is_bool($value)) { - throw new \InvalidArgumentException(sprintf('Invalid value type for attribute "%s". Boolean or string allowed, "%s" provided. ', $name, get_debug_type($value))); + throw new \InvalidArgumentException(\sprintf('Invalid value type for attribute "%s". Boolean or string allowed, "%s" provided. ', $name, get_debug_type($value))); } } diff --git a/src/Icons/src/Iconify.php b/src/Icons/src/Iconify.php index 9318221766a..d9d3fa15b02 100644 --- a/src/Icons/src/Iconify.php +++ b/src/Icons/src/Iconify.php @@ -44,21 +44,21 @@ public function __construct( public function metadataFor(string $prefix): array { - return $this->sets()[$prefix] ?? throw new \RuntimeException(sprintf('The icon prefix "%s" does not exist on iconify.design.', $prefix)); + return $this->sets()[$prefix] ?? throw new \RuntimeException(\sprintf('The icon prefix "%s" does not exist on iconify.design.', $prefix)); } public function fetchIcon(string $prefix, string $name): Icon { if (!isset($this->sets()[$prefix])) { - throw new IconNotFoundException(sprintf('The icon "%s:%s" does not exist on iconify.design.', $prefix, $name)); + throw new IconNotFoundException(\sprintf('The icon "%s:%s" does not exist on iconify.design.', $prefix, $name)); } - $response = $this->http->request('GET', sprintf('/%s.json?icons=%s', $prefix, $name)); + $response = $this->http->request('GET', \sprintf('/%s.json?icons=%s', $prefix, $name)); try { $data = $response->toArray(); } catch (JsonException) { - throw new IconNotFoundException(sprintf('The icon "%s:%s" does not exist on iconify.design.', $prefix, $name)); + throw new IconNotFoundException(\sprintf('The icon "%s:%s" does not exist on iconify.design.', $prefix, $name)); } $nameArg = $name; @@ -67,33 +67,33 @@ public function fetchIcon(string $prefix, string $name): Icon } if (!isset($data['icons'][$name]['body'])) { - throw new IconNotFoundException(sprintf('The icon "%s:%s" does not exist on iconify.design.', $prefix, $nameArg)); + throw new IconNotFoundException(\sprintf('The icon "%s:%s" does not exist on iconify.design.', $prefix, $nameArg)); } $height = $data['icons'][$name]['height'] ?? $data['height'] ?? $this->sets()[$prefix]['height'] ?? null; $width = $data['icons'][$name]['width'] ?? $data['width'] ?? $this->sets()[$prefix]['width'] ?? null; if (null === $width && null === $height) { - throw new \RuntimeException(sprintf('The icon "%s:%s" does not have a width or height.', $prefix, $nameArg)); + throw new \RuntimeException(\sprintf('The icon "%s:%s" does not have a width or height.', $prefix, $nameArg)); } return new Icon($data['icons'][$name]['body'], [ - 'viewBox' => sprintf('0 0 %s %s', $width ?? $height, $height ?? $width), + 'viewBox' => \sprintf('0 0 %s %s', $width ?? $height, $height ?? $width), ]); } public function fetchSvg(string $prefix, string $name): string { if (!isset($this->sets()[$prefix])) { - throw new IconNotFoundException(sprintf('The icon "%s:%s" does not exist on iconify.design.', $prefix, $name)); + throw new IconNotFoundException(\sprintf('The icon "%s:%s" does not exist on iconify.design.', $prefix, $name)); } $content = $this->http - ->request('GET', sprintf('/%s/%s.svg', $prefix, $name)) + ->request('GET', \sprintf('/%s/%s.svg', $prefix, $name)) ->getContent() ; if (!str_starts_with($content, 'cache->get( - sprintf('ux-icon-%s', Icon::nameToId($name)), + \sprintf('ux-icon-%s', Icon::nameToId($name)), fn () => $this->inner->get($name), beta: $refresh ? \INF : null, ); diff --git a/src/Icons/src/Registry/ChainIconRegistry.php b/src/Icons/src/Registry/ChainIconRegistry.php index e9c4c31201d..c6e882cff59 100644 --- a/src/Icons/src/Registry/ChainIconRegistry.php +++ b/src/Icons/src/Registry/ChainIconRegistry.php @@ -38,6 +38,6 @@ public function get(string $name): Icon } } - throw new IconNotFoundException(sprintf('Icon "%s" not found.', $name)); + throw new IconNotFoundException(\sprintf('Icon "%s" not found.', $name)); } } diff --git a/src/Icons/src/Registry/IconifyOnDemandRegistry.php b/src/Icons/src/Registry/IconifyOnDemandRegistry.php index 4c314ca79d1..7e9325adbd3 100644 --- a/src/Icons/src/Registry/IconifyOnDemandRegistry.php +++ b/src/Icons/src/Registry/IconifyOnDemandRegistry.php @@ -30,7 +30,7 @@ public function __construct(private Iconify $iconify) public function get(string $name): Icon { if (2 !== \count($parts = explode(':', $name))) { - throw new IconNotFoundException(sprintf('The icon name "%s" is not valid.', $name)); + throw new IconNotFoundException(\sprintf('The icon name "%s" is not valid.', $name)); } return $this->iconify->fetchIcon(...$parts); diff --git a/src/Icons/src/Registry/LocalSvgIconRegistry.php b/src/Icons/src/Registry/LocalSvgIconRegistry.php index 5f9e65782bf..c12ef39475c 100644 --- a/src/Icons/src/Registry/LocalSvgIconRegistry.php +++ b/src/Icons/src/Registry/LocalSvgIconRegistry.php @@ -29,8 +29,8 @@ public function __construct(private string $iconDir) public function get(string $name): Icon { - if (!file_exists($filename = sprintf('%s/%s.svg', $this->iconDir, str_replace(':', '/', $name)))) { - throw new IconNotFoundException(sprintf('The icon "%s" (%s) does not exist.', $name, $filename)); + if (!file_exists($filename = \sprintf('%s/%s.svg', $this->iconDir, str_replace(':', '/', $name)))) { + throw new IconNotFoundException(\sprintf('The icon "%s" (%s) does not exist.', $name, $filename)); } return Icon::fromFile($filename); @@ -49,7 +49,7 @@ public function has(string $name): bool public function add(string $name, string $svg): void { - $filename = sprintf('%s/%s.svg', $this->iconDir, $name); + $filename = \sprintf('%s/%s.svg', $this->iconDir, $name); (new Filesystem())->dumpFile($filename, $svg); } diff --git a/src/Icons/tests/Util/InMemoryIconRegistry.php b/src/Icons/tests/Util/InMemoryIconRegistry.php index d472a9cfef1..2e20eac5f9b 100644 --- a/src/Icons/tests/Util/InMemoryIconRegistry.php +++ b/src/Icons/tests/Util/InMemoryIconRegistry.php @@ -35,6 +35,6 @@ public function set(string $name, Icon $icon): void public function get(string $name): Icon { - return $this->icons[$name] ?? throw new IconNotFoundException(sprintf('Icon "%s" not found.', $name)); + return $this->icons[$name] ?? throw new IconNotFoundException(\sprintf('Icon "%s" not found.', $name)); } } diff --git a/src/LiveComponent/src/ComponentWithFormTrait.php b/src/LiveComponent/src/ComponentWithFormTrait.php index 806cfaa24bb..00d981decdc 100644 --- a/src/LiveComponent/src/ComponentWithFormTrait.php +++ b/src/LiveComponent/src/ComponentWithFormTrait.php @@ -176,7 +176,7 @@ private function submitForm(bool $validateAll = true): void ); if (!$form->isValid()) { - throw new UnprocessableEntityHttpException('Form validation failed in component'); + throw new UnprocessableEntityHttpException('Form validation failed in component.'); } } @@ -273,7 +273,7 @@ private function clearErrorsForNonValidatedFields(FormInterface $form, string $c } foreach ($form as $name => $child) { - $this->clearErrorsForNonValidatedFields($child, sprintf('%s.%s', $currentPath, $name)); + $this->clearErrorsForNonValidatedFields($child, \sprintf('%s.%s', $currentPath, $name)); } } } diff --git a/src/LiveComponent/src/DependencyInjection/Compiler/ComponentDefaultActionPass.php b/src/LiveComponent/src/DependencyInjection/Compiler/ComponentDefaultActionPass.php index 6168fd290e2..5ebd61546f2 100644 --- a/src/LiveComponent/src/DependencyInjection/Compiler/ComponentDefaultActionPass.php +++ b/src/LiveComponent/src/DependencyInjection/Compiler/ComponentDefaultActionPass.php @@ -29,13 +29,13 @@ public function process(ContainerBuilder $container): void } if (!$class = $container->getDefinition($id)->getClass()) { - throw new \LogicException(sprintf('Live component service "%s" must have a class.', $id)); + throw new \LogicException(\sprintf('Live component service "%s" must have a class.', $id)); } $defaultAction = trim($component[0]['default_action'] ?? '__invoke', '()'); if (!method_exists($class, $defaultAction)) { - throw new \LogicException(sprintf('Live component "%s" requires the default action method "%s".%s', $class, $defaultAction, '__invoke' === $defaultAction ? ' Either add this method or use the DefaultActionTrait' : '')); + throw new \LogicException(\sprintf('Live component "%s" requires the default action method "%s".%s', $class, $defaultAction, '__invoke' === $defaultAction ? ' Either add this method or use the DefaultActionTrait' : '')); } } } diff --git a/src/LiveComponent/src/EventListener/DeferLiveComponentSubscriber.php b/src/LiveComponent/src/EventListener/DeferLiveComponentSubscriber.php index c585caa6f25..3d15890a6cc 100644 --- a/src/LiveComponent/src/EventListener/DeferLiveComponentSubscriber.php +++ b/src/LiveComponent/src/EventListener/DeferLiveComponentSubscriber.php @@ -44,10 +44,10 @@ public function onPostMount(PostMountEvent $event): void // Ignored values: false / null / '' if ($loading = $data['loading']) { if (!\is_scalar($loading)) { - throw new \InvalidArgumentException(sprintf('The "loading" attribute value must be scalar, "%s" passed.', get_debug_type($loading))); + throw new \InvalidArgumentException(\sprintf('The "loading" attribute value must be scalar, "%s" passed.', get_debug_type($loading))); } if (!\in_array($loading, ['defer', 'lazy'], true)) { - throw new \InvalidArgumentException(sprintf('Invalid "loading" attribute value "%s". Accepted values: "defer" and "lazy".', $loading)); + throw new \InvalidArgumentException(\sprintf('Invalid "loading" attribute value "%s". Accepted values: "defer" and "lazy".', $loading)); } $event->addExtraMetadata('loading', $loading); } diff --git a/src/LiveComponent/src/EventListener/LiveComponentSubscriber.php b/src/LiveComponent/src/EventListener/LiveComponentSubscriber.php index 97775c1d120..5d2480f4fd9 100644 --- a/src/LiveComponent/src/EventListener/LiveComponentSubscriber.php +++ b/src/LiveComponent/src/EventListener/LiveComponentSubscriber.php @@ -86,18 +86,18 @@ public function onKernelRequest(RequestEvent $event): void /** @var ComponentMetadata $metadata */ $metadata = $this->container->get(ComponentFactory::class)->metadataFor($componentName); } catch (\InvalidArgumentException $e) { - throw new NotFoundHttpException(sprintf('Component "%s" not found.', $componentName), $e); + throw new NotFoundHttpException(\sprintf('Component "%s" not found.', $componentName), $e); } if (!$metadata->get('live', false)) { - throw new NotFoundHttpException(sprintf('"%s" (%s) is not a Live Component.', $metadata->getClass(), $componentName)); + throw new NotFoundHttpException(\sprintf('"%s" (%s) is not a Live Component.', $metadata->getClass(), $componentName)); } if ('get' === $action) { $defaultAction = trim($metadata->get('default_action', '__invoke'), '()'); // set default controller for "default" action - $request->attributes->set('_controller', sprintf('%s::%s', $metadata->getServiceId(), $defaultAction)); + $request->attributes->set('_controller', \sprintf('%s::%s', $metadata->getServiceId(), $defaultAction)); $request->attributes->set('_component_default_action', true); return; @@ -131,7 +131,7 @@ public function onKernelRequest(RequestEvent $event): void return; } - $request->attributes->set('_controller', sprintf('%s::%s', $metadata->getServiceId(), $action)); + $request->attributes->set('_controller', \sprintf('%s::%s', $metadata->getServiceId(), $action)); } public function onKernelController(ControllerEvent $event): void @@ -159,7 +159,7 @@ public function onKernelController(ControllerEvent $event): void } if (!$request->attributes->get('_component_default_action', false) && !AsLiveComponent::isActionAllowed($component, $action)) { - throw new NotFoundHttpException(sprintf('The action "%s" either doesn\'t exist or is not allowed in "%s". Make sure it exist and has the LiveAction attribute above it.', $action, $component::class)); + throw new NotFoundHttpException(\sprintf('The action "%s" either doesn\'t exist or is not allowed in "%s". Make sure it exist and has the LiveAction attribute above it.', $action, $component::class)); } $componentName = $request->attributes->get('_component_name') ?? $request->attributes->get('_mounted_component')->getName(); @@ -381,7 +381,7 @@ private static function parseJsonFromQuery(Request $request, string $key): array try { return json_decode($request->query->get($key), true, 512, \JSON_THROW_ON_ERROR); } catch (\JsonException $exception) { - throw new JsonException(sprintf('Invalid JSON on query string "%s".', $key), 0, $exception); + throw new JsonException(\sprintf('Invalid JSON on query string "%s".', $key), 0, $exception); } } } diff --git a/src/LiveComponent/src/Hydration/DoctrineEntityHydrationExtension.php b/src/LiveComponent/src/Hydration/DoctrineEntityHydrationExtension.php index 118a6152ae8..43b6400d97c 100644 --- a/src/LiveComponent/src/Hydration/DoctrineEntityHydrationExtension.php +++ b/src/LiveComponent/src/Hydration/DoctrineEntityHydrationExtension.php @@ -53,7 +53,7 @@ public function hydrate(mixed $value, string $className): ?object return $this->objectManagerFor($className)->find($className, $value); } - throw new \InvalidArgumentException(sprintf('Cannot hydrate Doctrine entity "%s". Value of type "%s" is not supported.', $className, get_debug_type($value))); + throw new \InvalidArgumentException(\sprintf('Cannot hydrate Doctrine entity "%s". Value of type "%s" is not supported.', $className, get_debug_type($value))); } public function dehydrate(object $object): mixed diff --git a/src/LiveComponent/src/LiveComponentHydrator.php b/src/LiveComponent/src/LiveComponentHydrator.php index bd79380b0fb..c5ec39b9554 100644 --- a/src/LiveComponent/src/LiveComponentHydrator.php +++ b/src/LiveComponent/src/LiveComponentHydrator.php @@ -68,10 +68,10 @@ public function dehydrate(object $component, ComponentAttributes $attributes, Li $frontendName = $propMetadata->calculateFieldName($component, $propertyName); if (isset($takenFrontendPropertyNames[$frontendName])) { - $message = sprintf('The field name "%s" cannot be used by multiple LiveProp properties in a component. Currently, both "%s" and "%s" are trying to use it in "%s".', $frontendName, $takenFrontendPropertyNames[$frontendName], $propertyName, $component::class); + $message = \sprintf('The field name "%s" cannot be used by multiple LiveProp properties in a component. Currently, both "%s" and "%s" are trying to use it in "%s".', $frontendName, $takenFrontendPropertyNames[$frontendName], $propertyName, $component::class); if ($frontendName === $takenFrontendPropertyNames[$frontendName] || $frontendName === $propertyName) { - $message .= sprintf(' Try adding LiveProp(fieldName="somethingElse") for the "%s" property to avoid this.', $frontendName); + $message .= \sprintf(' Try adding LiveProp(fieldName="somethingElse") for the "%s" property to avoid this.', $frontendName); } throw new \LogicException($message); @@ -83,7 +83,7 @@ public function dehydrate(object $component, ComponentAttributes $attributes, Li try { $rawPropertyValue = $this->propertyAccessor->getValue($component, $propertyName); } catch (UninitializedPropertyException $exception) { - throw new \LogicException(sprintf('The "%s" property on the "%s" component is uninitialized. Did you forget to pass this into the component?', $propertyName, $component::class), 0, $exception); + throw new \LogicException(\sprintf('The "%s" property on the "%s" component is uninitialized. Did you forget to pass this into the component?', $propertyName, $component::class), 0, $exception); } $dehydratedValue = $this->dehydrateValue($rawPropertyValue, $propMetadata, $component); @@ -99,14 +99,14 @@ public function dehydrate(object $component, ComponentAttributes $attributes, Li $this->adjustPropertyPathForData($rawPropertyValue, $path) ); } catch (NoSuchPropertyException $e) { - throw new \LogicException(sprintf('The writable path "%s" does not exist on the "%s" property of the "%s" component.', $path, $propertyName, $component::class), 0, $e); + throw new \LogicException(\sprintf('The writable path "%s" does not exist on the "%s" property of the "%s" component.', $path, $propertyName, $component::class), 0, $e); } catch (PropertyAccessExceptionInterface $e) { - throw new \LogicException(sprintf('The writable path "%s" on the "%s" property of the "%s" component could not be read: %s', $path, $propertyName, $component::class, $e->getMessage()), 0, $e); + throw new \LogicException(\sprintf('The writable path "%s" on the "%s" property of the "%s" component could not be read: %s', $path, $propertyName, $component::class, $e->getMessage()), 0, $e); } // TODO: maybe we allow support the same types as LiveProps later if (!$this->isValueValidDehydratedValue($pathValue)) { - throw new \LogicException(sprintf('The writable path "%s" on the "%s" property of the "%s" component must be a scalar or array of scalars.', $path, $propertyName, $component::class)); + throw new \LogicException(\sprintf('The writable path "%s" on the "%s" property of the "%s" component must be a scalar or array of scalars.', $path, $propertyName, $component::class)); } $dehydratedProps->addNestedProp($frontendName, $path, $pathValue); @@ -182,7 +182,7 @@ public function hydrate(object $component, array $props, array $updatedProps, Li */ if ($dehydratedUpdatedProps->hasPropValue($frontendName)) { if (!$propMetadata->isIdentityWritable()) { - throw new HydrationException(sprintf('The model "%s" was sent for update, but it is not writable. Try adding "writable: true" to the $%s property in %s.', $frontendName, $propMetadata->getName(), $component::class)); + throw new HydrationException(\sprintf('The model "%s" was sent for update, but it is not writable. Try adding "writable: true" to the $%s property in %s.', $frontendName, $propMetadata->getName(), $component::class)); } try { $propertyValue = $this->hydrateValue( @@ -239,7 +239,7 @@ public function hydrateValue(mixed $value, LivePropMetadata $propMetadata, objec { if ($propMetadata->hydrateMethod()) { if (!method_exists($parentObject, $propMetadata->hydrateMethod())) { - throw new \LogicException(sprintf('The "%s" object has a hydrateMethod of "%s" but the method does not exist.', $parentObject::class, $propMetadata->hydrateMethod())); + throw new \LogicException(\sprintf('The "%s" object has a hydrateMethod of "%s" but the method does not exist.', $parentObject::class, $propMetadata->hydrateMethod())); } return $parentObject->{$propMetadata->hydrateMethod()}($value); @@ -247,13 +247,13 @@ public function hydrateValue(mixed $value, LivePropMetadata $propMetadata, objec if ($propMetadata->useSerializerForHydration()) { if (!interface_exists(DenormalizerInterface::class)) { - throw new \LogicException(sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but the Serializer component is not installed. Try running "composer require symfony/serializer".', $propMetadata->getName(), $parentObject::class)); + throw new \LogicException(\sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but the Serializer component is not installed. Try running "composer require symfony/serializer".', $propMetadata->getName(), $parentObject::class)); } if (null === $this->serializer) { - throw new \LogicException(sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but no serializer has been set.', $propMetadata->getName(), $parentObject::class)); + throw new \LogicException(\sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but no serializer has been set.', $propMetadata->getName(), $parentObject::class)); } if (!$this->serializer instanceof DenormalizerInterface) { - throw new \LogicException(sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but the given serializer does not implement DenormalizerInterface.', $propMetadata->getName(), $parentObject::class)); + throw new \LogicException(\sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but the given serializer does not implement DenormalizerInterface.', $propMetadata->getName(), $parentObject::class)); } if ($propMetadata->collectionValueType()) { @@ -268,7 +268,7 @@ public function hydrateValue(mixed $value, LivePropMetadata $propMetadata, objec } if (null === $type) { - throw new \LogicException(sprintf('The "%s::%s" object should be hydrated with the Serializer, but no type could be guessed.', $parentObject::class, $propMetadata->getName())); + throw new \LogicException(\sprintf('The "%s::%s" object should be hydrated with the Serializer, but no type could be guessed.', $parentObject::class, $propMetadata->getName())); } return $this->serializer->denormalize($value, $type, 'json', $propMetadata->serializationContext()); @@ -277,7 +277,7 @@ public function hydrateValue(mixed $value, LivePropMetadata $propMetadata, objec if ($propMetadata->collectionValueType() && Type::BUILTIN_TYPE_OBJECT === $propMetadata->collectionValueType()->getBuiltinType()) { $collectionClass = $propMetadata->collectionValueType()->getClassName(); foreach ($value as $key => $objectItem) { - $value[$key] = $this->hydrateObjectValue($objectItem, $collectionClass, true, $propMetadata->getFormat(), $parentObject::class, sprintf('%s.%s', $propMetadata->getName(), $key), $parentObject); + $value[$key] = $this->hydrateObjectValue($objectItem, $collectionClass, true, $propMetadata->getFormat(), $parentObject::class, \sprintf('%s.%s', $propMetadata->getName(), $key), $parentObject); } } @@ -321,7 +321,7 @@ private static function coerceStringValue(string $value, string $type, bool $all 'int' => (int) $value, 'float' => (float) $value, 'bool' => self::coerceStringToBoolean($value), - default => throw new \LogicException(sprintf('Cannot coerce value "%s" to type "%s"', $value, $type)), + default => throw new \LogicException(\sprintf('Cannot coerce value "%s" to type "%s"', $value, $type)), }; } @@ -348,7 +348,7 @@ private function calculateChecksum(array $dehydratedPropsData): ?string private function verifyChecksum(array $identifierPops, string $error = 'Invalid checksum sent when updating the live component.'): void { if (!\array_key_exists(self::CHECKSUM_KEY, $identifierPops)) { - throw new HydrationException(sprintf('Missing %s. key', self::CHECKSUM_KEY)); + throw new HydrationException(\sprintf('Missing %s. key', self::CHECKSUM_KEY)); } $sentChecksum = $identifierPops[self::CHECKSUM_KEY]; unset($identifierPops[self::CHECKSUM_KEY]); @@ -369,7 +369,7 @@ private function adjustPropertyPathForData(mixed $rawPropertyValue, string $prop $finalPropertyPath = ''; foreach ($parts as $part) { if (\is_array($currentValue)) { - $finalPropertyPath .= sprintf('[%s]', $part); + $finalPropertyPath .= \sprintf('[%s]', $part); continue; } @@ -423,7 +423,7 @@ private function dehydrateValue(mixed $value, LivePropMetadata $propMetadata, ob { if ($method = $propMetadata->dehydrateMethod()) { if (!method_exists($parentObject, $method)) { - throw new \LogicException(sprintf('The dehydration failed for class "%s" because the "%s" method does not exist.', $parentObject::class, $method)); + throw new \LogicException(\sprintf('The dehydration failed for class "%s" because the "%s" method does not exist.', $parentObject::class, $method)); } return $parentObject->$method($value); @@ -431,13 +431,13 @@ private function dehydrateValue(mixed $value, LivePropMetadata $propMetadata, ob if ($propMetadata->useSerializerForHydration()) { if (!interface_exists(NormalizerInterface::class)) { - throw new \LogicException(sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but the Serializer component is not installed. Try running "composer require symfony/serializer".', $propMetadata->getName(), $parentObject::class)); + throw new \LogicException(\sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but the Serializer component is not installed. Try running "composer require symfony/serializer".', $propMetadata->getName(), $parentObject::class)); } if (null === $this->serializer) { - throw new \LogicException(sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but no serializer has been set.', $propMetadata->getName(), $parentObject::class)); + throw new \LogicException(\sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but no serializer has been set.', $propMetadata->getName(), $parentObject::class)); } if (!$this->serializer instanceof NormalizerInterface) { - throw new \LogicException(sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but the given serializer does not implement NormalizerInterface.', $propMetadata->getName(), $parentObject::class)); + throw new \LogicException(\sprintf('The LiveProp "%s" on component "%s" has "useSerializerForHydration: true", but the given serializer does not implement NormalizerInterface.', $propMetadata->getName(), $parentObject::class)); } return $this->serializer->normalize($value, 'json', $propMetadata->serializationContext()); @@ -452,7 +452,7 @@ private function dehydrateValue(mixed $value, LivePropMetadata $propMetadata, ob $collectionClass = $propMetadata->collectionValueType()->getClassName(); foreach ($value as $key => $objectItem) { if (!$objectItem instanceof $collectionClass) { - throw new \LogicException(sprintf('The LiveProp "%s" on component "%s" is an array. We determined the array is full of %s objects, but at least on key had a different value of %s', $propMetadata->getName(), $parentObject::class, $collectionClass, get_debug_type($objectItem))); + throw new \LogicException(\sprintf('The LiveProp "%s" on component "%s" is an array. We determined the array is full of %s objects, but at least on key had a different value of %s', $propMetadata->getName(), $parentObject::class, $collectionClass, get_debug_type($objectItem))); } $value[$key] = $this->dehydrateObjectValue($objectItem, $collectionClass, $propMetadata->getFormat(), $parentObject); @@ -460,18 +460,18 @@ private function dehydrateValue(mixed $value, LivePropMetadata $propMetadata, ob } if (!$this->isValueValidDehydratedValue($value)) { - throw new \LogicException(throw new \LogicException(sprintf('Unable to dehydrate value of type "%s" for property "%s" on component "%s". Change this to a simpler type of an object that can be dehydrated. Or set the hydrateWith/dehydrateWith options in LiveProp or set "useSerializerForHydration: true" on the LiveProp to use the serializer.', get_debug_type($value), $propMetadata->getName(), $parentObject::class))); + throw new \LogicException(throw new \LogicException(\sprintf('Unable to dehydrate value of type "%s" for property "%s" on component "%s". Change this to a simpler type of an object that can be dehydrated. Or set the hydrateWith/dehydrateWith options in LiveProp or set "useSerializerForHydration: true" on the LiveProp to use the serializer.', get_debug_type($value), $propMetadata->getName(), $parentObject::class))); } return $value; } if (!\is_object($value)) { - throw new \LogicException(sprintf('Unable to dehydrate value of type "%s" for property "%s" on component "%s". Change this to a simpler type of an object that can be dehydrated. Or set the hydrateWith/dehydrateWith options in LiveProp or set "useSerializerForHydration: true" on the LiveProp to use the serializer.', get_debug_type($value), $propMetadata->getName(), $parentObject::class)); + throw new \LogicException(\sprintf('Unable to dehydrate value of type "%s" for property "%s" on component "%s". Change this to a simpler type of an object that can be dehydrated. Or set the hydrateWith/dehydrateWith options in LiveProp or set "useSerializerForHydration: true" on the LiveProp to use the serializer.', get_debug_type($value), $propMetadata->getName(), $parentObject::class)); } if (!$propMetadata->getType() || $propMetadata->isBuiltIn()) { - throw new \LogicException(sprintf('The "%s" property on component "%s" is missing its property-type. Add the "%s" type so the object can be hydrated later.', $propMetadata->getName(), $parentObject::class, $value::class)); + throw new \LogicException(\sprintf('The "%s" property on component "%s" is missing its property-type. Add the "%s" type so the object can be hydrated later.', $propMetadata->getName(), $parentObject::class, $value::class)); } // at this point, we have an object and can assume $propMetadata->getType() @@ -497,7 +497,7 @@ private function dehydrateObjectValue(object $value, string $classType, ?string } if (interface_exists($classType)) { - throw new \LogicException(sprintf('Cannot dehydrate value typed as interface "%s" on component "%s". Change this to a concrete type that can be dehydrated. Or set the hydrateWith/dehydrateWith options in LiveProp or set "useSerializerForHydration: true" on the LiveProp to use the serializer.', get_debug_type($value), $parentObject::class)); + throw new \LogicException(\sprintf('Cannot dehydrate value typed as interface "%s" on component "%s". Change this to a concrete type that can be dehydrated. Or set the hydrateWith/dehydrateWith options in LiveProp or set "useSerializerForHydration: true" on the LiveProp to use the serializer.', get_debug_type($value), $parentObject::class)); } $dehydratedObjectValues = []; @@ -528,11 +528,11 @@ private function hydrateObjectValue(mixed $value, string $className, bool $allow } if (!\is_string($value)) { - throw new BadRequestHttpException(sprintf('The model path "%s" was sent an invalid data type "%s" for a date.', $propertyPathForError, get_debug_type($value))); + throw new BadRequestHttpException(\sprintf('The model path "%s" was sent an invalid data type "%s" for a date.', $propertyPathForError, get_debug_type($value))); } if (null !== $dateFormat) { - return $className::createFromFormat($dateFormat, $value) ?: throw new BadRequestHttpException(sprintf('The model path "%s" was sent invalid date data "%s" or in an invalid format. Make sure it\'s a valid date and it matches the expected format "%s".', $propertyPathForError, $value, $dateFormat)); + return $className::createFromFormat($dateFormat, $value) ?: throw new BadRequestHttpException(\sprintf('The model path "%s" was sent invalid date data "%s" or in an invalid format. Make sure it\'s a valid date and it matches the expected format "%s".', $propertyPathForError, $value, $dateFormat)); } return new $className($value); @@ -545,7 +545,7 @@ private function hydrateObjectValue(mixed $value, string $className, bool $allow } if (interface_exists($className)) { - throw new \LogicException(sprintf('Cannot hydrate value typed as interface "%s" on component "%s". Change this to a concrete type that can be hydrated. Or set the hydrateWith/dehydrateWith options in LiveProp or set "useSerializerForHydration: true" on the LiveProp to use the serializer.', $className, $component::class)); + throw new \LogicException(\sprintf('Cannot hydrate value typed as interface "%s" on component "%s". Change this to a concrete type that can be hydrated. Or set the hydrateWith/dehydrateWith options in LiveProp or set "useSerializerForHydration: true" on the LiveProp to use the serializer.', $className, $component::class)); } if (\is_array($value)) { @@ -560,7 +560,7 @@ private function hydrateObjectValue(mixed $value, string $className, bool $allow return $object; } - throw new HydrationException(sprintf('Unable to hydrate value of type "%s" for property "%s" on component "%s". it looks like something went wrong by trying to guess your property types.', $className, $propertyPathForError, $componentClassForError)); + throw new HydrationException(\sprintf('Unable to hydrate value of type "%s" for property "%s" on component "%s". it looks like something went wrong by trying to guess your property types.', $className, $propertyPathForError, $componentClassForError)); } private function isValueValidDehydratedValue(mixed $value): bool @@ -601,7 +601,7 @@ private function calculateWritablePaths(LivePropMetadata $propMetadata, mixed $p if (\count($extraSentWritablePaths) > 0) { // we could show multiple fields here in the message - throw new HydrationException(sprintf('The model "%s.%s" was sent for update, but it is not writable. Try adding "writable: [\'%s\']" to the $%s property in %s.', $frontendPropName, $extraSentWritablePaths[0], $extraSentWritablePaths[0], $propMetadata->getName(), $componentClass)); + throw new HydrationException(\sprintf('The model "%s.%s" was sent for update, but it is not writable. Try adding "writable: [\'%s\']" to the $%s property in %s.', $frontendPropName, $extraSentWritablePaths[0], $extraSentWritablePaths[0], $propMetadata->getName(), $componentClass)); } return $writablePaths; @@ -642,7 +642,7 @@ private function ensureOnUpdatedMethodExists(object $component, string $methodNa return; } - throw new \Exception(sprintf('Method "%s:%s()" specified as LiveProp "onUpdated" hook does not exist.', $component::class, $methodName)); + throw new \Exception(\sprintf('Method "%s:%s()" specified as LiveProp "onUpdated" hook does not exist.', $component::class, $methodName)); } /** @@ -673,7 +673,7 @@ private function processOnUpdatedHook(object $component, string $frontendName, L continue; } - $key = sprintf('%s.%s', $frontendName, $propName); + $key = \sprintf('%s.%s', $frontendName, $propName); if (!$dehydratedUpdatedProps->hasPropValue($key)) { continue; } diff --git a/src/LiveComponent/src/Metadata/LiveComponentMetadataFactory.php b/src/LiveComponent/src/Metadata/LiveComponentMetadataFactory.php index 37c68f1a2dd..78fd36ab836 100644 --- a/src/LiveComponent/src/Metadata/LiveComponentMetadataFactory.php +++ b/src/LiveComponent/src/Metadata/LiveComponentMetadataFactory.php @@ -76,7 +76,7 @@ public function createLivePropMetadata(string $className, string $propertyName, { $type = $property->getType(); if ($type instanceof \ReflectionUnionType || $type instanceof \ReflectionIntersectionType) { - throw new \LogicException(sprintf('Union or intersection types are not supported for LiveProps. You may want to change the type of property %s in %s.', $property->getName(), $property->getDeclaringClass()->getName())); + throw new \LogicException(\sprintf('Union or intersection types are not supported for LiveProps. You may want to change the type of property %s in %s.', $property->getName(), $property->getDeclaringClass()->getName())); } $infoTypes = $this->propertyTypeExtractor->getTypes($className, $propertyName) ?? []; diff --git a/src/LiveComponent/src/Metadata/LivePropMetadata.php b/src/LiveComponent/src/Metadata/LivePropMetadata.php index 1878a159b03..b6a94b7f163 100644 --- a/src/LiveComponent/src/Metadata/LivePropMetadata.php +++ b/src/LiveComponent/src/Metadata/LivePropMetadata.php @@ -132,12 +132,12 @@ public function withModifier(object $component): self } if (!method_exists($component, $modifier)) { - throw new \LogicException(sprintf('Method "%s::%s()" given in LiveProp "modifier" does not exist.', $component::class, $modifier)); + throw new \LogicException(\sprintf('Method "%s::%s()" given in LiveProp "modifier" does not exist.', $component::class, $modifier)); } $modifiedLiveProp = $component->{$modifier}($this->liveProp); if (!$modifiedLiveProp instanceof LiveProp) { - throw new \LogicException(sprintf('Method "%s::%s()" should return an instance of "%s" (given: "%s").', $component::class, $modifier, LiveProp::class, get_debug_type($modifiedLiveProp))); + throw new \LogicException(\sprintf('Method "%s::%s()" should return an instance of "%s" (given: "%s").', $component::class, $modifier, LiveProp::class, get_debug_type($modifiedLiveProp))); } $clone = clone $this; diff --git a/src/LiveComponent/src/Test/InteractsWithLiveComponents.php b/src/LiveComponent/src/Test/InteractsWithLiveComponents.php index 6d2df7ef005..377fbad1f34 100644 --- a/src/LiveComponent/src/Test/InteractsWithLiveComponents.php +++ b/src/LiveComponent/src/Test/InteractsWithLiveComponents.php @@ -23,7 +23,7 @@ trait InteractsWithLiveComponents protected function createLiveComponent(string $name, array $data = [], ?KernelBrowser $client = null): TestLiveComponent { if (!$this instanceof KernelTestCase) { - throw new \LogicException(sprintf('The "%s" trait can only be used on "%s" classes.', __TRAIT__, KernelTestCase::class)); + throw new \LogicException(\sprintf('The "%s" trait can only be used on "%s" classes.', __TRAIT__, KernelTestCase::class)); } /** @var ComponentFactory $factory */ @@ -31,7 +31,7 @@ protected function createLiveComponent(string $name, array $data = [], ?KernelBr $metadata = $factory->metadataFor($name); if (!$metadata->get('live')) { - throw new \LogicException(sprintf('The "%s" component is not a live component.', $name)); + throw new \LogicException(\sprintf('The "%s" component is not a live component.', $name)); } return new TestLiveComponent( diff --git a/src/LiveComponent/src/Test/TestLiveComponent.php b/src/LiveComponent/src/Test/TestLiveComponent.php index 98d9126ad15..cd2ef088d1f 100644 --- a/src/LiveComponent/src/Test/TestLiveComponent.php +++ b/src/LiveComponent/src/Test/TestLiveComponent.php @@ -100,7 +100,7 @@ public function emit(string $event, array $arguments = []): self } if (!$actions) { - throw new \InvalidArgumentException(sprintf('Event "%s" does not exist on component "%s".', $event, $this->metadata->getName())); + throw new \InvalidArgumentException(\sprintf('Event "%s" does not exist on component "%s".', $event, $this->metadata->getName())); } if (1 === \count($listeners)) { diff --git a/src/LiveComponent/src/Twig/DeterministicTwigIdCalculator.php b/src/LiveComponent/src/Twig/DeterministicTwigIdCalculator.php index a228e9867a8..e3130fa7ecf 100644 --- a/src/LiveComponent/src/Twig/DeterministicTwigIdCalculator.php +++ b/src/LiveComponent/src/Twig/DeterministicTwigIdCalculator.php @@ -43,12 +43,12 @@ public function calculateDeterministicId(bool $increment = true, ?string $key = { $lineData = $this->guessTemplateInfo(); - $fileAndLine = sprintf('%s-%d', $lineData['name'], $lineData['line']); + $fileAndLine = \sprintf('%s-%d', $lineData['name'], $lineData['line']); if (!isset($this->lineAndFileCounts[$fileAndLine])) { $this->lineAndFileCounts[$fileAndLine] = 0; } - $id = sprintf( + $id = \sprintf( 'live-%s-%s', crc32($fileAndLine), null !== $key ? $key : $this->lineAndFileCounts[$fileAndLine] @@ -172,6 +172,6 @@ private function guessTemplateInfo(): array } } - throw new \LogicException(sprintf('Could not find line number in template "%s" while generating deterministic id.', $name)); + throw new \LogicException(\sprintf('Could not find line number in template "%s" while generating deterministic id.', $name)); } } diff --git a/src/LiveComponent/src/Twig/TemplateCacheWarmer.php b/src/LiveComponent/src/Twig/TemplateCacheWarmer.php index 3e6f4e9a850..39bf2a95ce1 100644 --- a/src/LiveComponent/src/Twig/TemplateCacheWarmer.php +++ b/src/LiveComponent/src/Twig/TemplateCacheWarmer.php @@ -36,7 +36,7 @@ public function warmUp(string $cacheDir, ?string $buildDir = null): array $map[hash('xxh128', $item.$this->secret)] = $item; } - $cacheFile = sprintf('%s%s%s', $buildDir ?? $cacheDir, \DIRECTORY_SEPARATOR, $this->cacheFilename); + $cacheFile = \sprintf('%s%s%s', $buildDir ?? $cacheDir, \DIRECTORY_SEPARATOR, $this->cacheFilename); PhpArrayAdapter::create($cacheFile, new NullAdapter())->warmUp(['map' => $map]); return []; diff --git a/src/LiveComponent/src/Twig/TemplateMap.php b/src/LiveComponent/src/Twig/TemplateMap.php index 142e58cd3b1..0fee92941f1 100644 --- a/src/LiveComponent/src/Twig/TemplateMap.php +++ b/src/LiveComponent/src/Twig/TemplateMap.php @@ -33,13 +33,13 @@ public function __construct(string $cacheFile) public function resolve(string $obscuredName): string { - return $this->map[$obscuredName] ?? throw new \RuntimeException(sprintf('Cannot find a template matching "%s". Cache may be corrupt.', $obscuredName)); + return $this->map[$obscuredName] ?? throw new \RuntimeException(\sprintf('Cannot find a template matching "%s". Cache may be corrupt.', $obscuredName)); } public function obscuredName(string $templateName): string { if (false === $obscuredName = array_search($templateName, $this->map, true)) { - throw new \RuntimeException(sprintf('Cannot find a match for template "%s". Cache may be corrupt.', $templateName)); + throw new \RuntimeException(\sprintf('Cannot find a match for template "%s". Cache may be corrupt.', $templateName)); } return $obscuredName; diff --git a/src/LiveComponent/src/Util/ChildComponentPartialRenderer.php b/src/LiveComponent/src/Util/ChildComponentPartialRenderer.php index c05c5a32844..7920747be50 100644 --- a/src/LiveComponent/src/Util/ChildComponentPartialRenderer.php +++ b/src/LiveComponent/src/Util/ChildComponentPartialRenderer.php @@ -85,11 +85,11 @@ private function createHtml(array $attributes, string $childTag): string { // transform attributes into an array of key="value" strings $attributes = array_map(function ($key, $value) { - return sprintf('%s="%s"', $key, $value); + return \sprintf('%s="%s"', $key, $value); }, array_keys($attributes), $attributes); $attributes[] = 'data-live-preserve="true"'; - return sprintf('<%s %s>', $childTag, implode(' ', $attributes), $childTag); + return \sprintf('<%s %s>', $childTag, implode(' ', $attributes), $childTag); } public static function getSubscribedServices(): array diff --git a/src/LiveComponent/src/Util/DehydratedProps.php b/src/LiveComponent/src/Util/DehydratedProps.php index 3a2372d4d36..64d50cea770 100644 --- a/src/LiveComponent/src/Util/DehydratedProps.php +++ b/src/LiveComponent/src/Util/DehydratedProps.php @@ -93,7 +93,7 @@ public function hasNestedPathValue(string $propName, string $nestedPath): bool public function getNestedPathValue(string $propName, string $nestedPath): mixed { if (!$this->hasNestedPathValue($propName, $nestedPath)) { - throw new \InvalidArgumentException(sprintf('The nested path "%s.%s" does not exist.', $propName, $nestedPath)); + throw new \InvalidArgumentException(\sprintf('The nested path "%s.%s" does not exist.', $propName, $nestedPath)); } $fullPath = $propName.'.'.$nestedPath; diff --git a/src/LiveComponent/src/Util/ModelBindingParser.php b/src/LiveComponent/src/Util/ModelBindingParser.php index 9d4c02b2d4b..bac916ee94b 100644 --- a/src/LiveComponent/src/Util/ModelBindingParser.php +++ b/src/LiveComponent/src/Util/ModelBindingParser.php @@ -48,7 +48,7 @@ private function parseBinding(string $bindingString): array return match (\count($parts)) { 1 => ['child' => 'value', 'parent' => $parts[0]], 2 => ['child' => $parts[1], 'parent' => $parts[0]], - default => throw new \InvalidArgumentException(sprintf('Invalid value "%s" given for "data-model". Format should be "childValue:parentValue" or just "parentValue" to use "value" for the child.', $bindingString)), + default => throw new \InvalidArgumentException(\sprintf('Invalid value "%s" given for "data-model". Format should be "childValue:parentValue" or just "parentValue" to use "value" for the child.', $bindingString)), }; } } diff --git a/src/LiveComponent/src/ValidatableComponentTrait.php b/src/LiveComponent/src/ValidatableComponentTrait.php index dc568722e72..16435be24b2 100644 --- a/src/LiveComponent/src/ValidatableComponentTrait.php +++ b/src/LiveComponent/src/ValidatableComponentTrait.php @@ -79,7 +79,7 @@ public function validateField(string $propertyName, bool $throw = true): void $this->getValidationErrors()->set($propertyName, $errors); if ($throw && \count($errors) > 0) { - throw new UnprocessableEntityHttpException(sprintf('The "%s" field of the component failed validation.', $propertyName)); + throw new UnprocessableEntityHttpException(\sprintf('The "%s" field of the component failed validation.', $propertyName)); } } @@ -160,7 +160,7 @@ private function resetValidation(): void private function getValidator(): ComponentValidatorInterface { if (!$this->componentValidator) { - throw new \InvalidArgumentException(sprintf('The ComponentValidator service was not injected into %s. Did you forget to autowire this service or configure the setComponentValidator() call?', static::class)); + throw new \InvalidArgumentException(\sprintf('The ComponentValidator service was not injected into %s. Did you forget to autowire this service or configure the setComponentValidator() call?', static::class)); } return $this->componentValidator; diff --git a/src/LiveComponent/tests/Functional/EventListener/InterceptChildComponentRenderSubscriberTest.php b/src/LiveComponent/tests/Functional/EventListener/InterceptChildComponentRenderSubscriberTest.php index 19cd1740b79..7eab6dc5a05 100644 --- a/src/LiveComponent/tests/Functional/EventListener/InterceptChildComponentRenderSubscriberTest.php +++ b/src/LiveComponent/tests/Functional/EventListener/InterceptChildComponentRenderSubscriberTest.php @@ -88,16 +88,16 @@ public function testItRendersNewPropWhenFingerprintDoesNotMatch(): void // 1st renders empty // fingerprint changed in 2nd & 3rd, so it renders new fingerprint + props - $this->assertStringContainsString(sprintf( + $this->assertStringContainsString(\sprintf( '
  • ', AddLiveAttributesSubscriberTest::TODO_ITEM_DETERMINISTIC_PREFIX ), $content); // new props are JUST the "textLength" + a checksum for it specifically - $this->assertStringContainsString(sprintf( + $this->assertStringContainsString(\sprintf( '
  • ', AddLiveAttributesSubscriberTest::TODO_ITEM_DETERMINISTIC_PREFIX_EMBEDDED ), $content); - $this->assertStringContainsString(sprintf( + $this->assertStringContainsString(\sprintf( '
  • ', AddLiveAttributesSubscriberTest::TODO_ITEM_DETERMINISTIC_PREFIX ), $content); @@ -172,6 +172,6 @@ private function doBuildUrlForComponent(string $componentName, array $childrenFi $queryData['children'] = json_encode($children); } - return sprintf('/_components/%s?%s', $componentName, http_build_query($queryData)); + return \sprintf('/_components/%s?%s', $componentName, http_build_query($queryData)); } } diff --git a/src/LiveComponent/tests/Integration/LiveComponentHydratorTest.php b/src/LiveComponent/tests/Integration/LiveComponentHydratorTest.php index 3ef22386e4c..fd01de4c385 100644 --- a/src/LiveComponent/tests/Integration/LiveComponentHydratorTest.php +++ b/src/LiveComponent/tests/Integration/LiveComponentHydratorTest.php @@ -57,7 +57,7 @@ final class LiveComponentHydratorTest extends KernelTestCase private function executeHydrationTestCase(callable $testFactory, ?int $minPhpVersion = null): void { if (null !== $minPhpVersion && $minPhpVersion > \PHP_VERSION_ID) { - $this->markTestSkipped(sprintf('Test requires PHP version %s or higher.', $minPhpVersion)); + $this->markTestSkipped(\sprintf('Test requires PHP version %s or higher.', $minPhpVersion)); } // lazily create the test case so each case can prep its data with an isolated container @@ -1157,7 +1157,7 @@ public function hydrateDate($data) { return \DateTime::createFromFormat( 'Y-m-d', - sprintf('%s-%s-%s', $data['year'], $data['month'], $data['day']) + \sprintf('%s-%s-%s', $data['year'], $data['month'], $data['day']) ); } }) diff --git a/src/LiveComponent/tests/Unit/Metadata/LivePropMetadataTest.php b/src/LiveComponent/tests/Unit/Metadata/LivePropMetadataTest.php index 2e59833580b..bca2d262f74 100644 --- a/src/LiveComponent/tests/Unit/Metadata/LivePropMetadataTest.php +++ b/src/LiveComponent/tests/Unit/Metadata/LivePropMetadataTest.php @@ -63,7 +63,7 @@ public function testWithModifierThrowsAnErrorIfModifierMethodDoesNotReturnLivePr ->willReturn(false); $this->expectException(\LogicException::class); - $this->expectExceptionMessageMatches(sprintf('/Method ".*::modifyProp\(\)" should return an instance of "%s" \(given: "bool"\)\./', preg_quote(LiveProp::class))); + $this->expectExceptionMessageMatches(\sprintf('/Method ".*::modifyProp\(\)" should return an instance of "%s" \(given: "bool"\)\./', preg_quote(LiveProp::class))); $livePropMetadata->withModifier($component); } } diff --git a/src/Notify/src/Twig/NotifyRuntime.php b/src/Notify/src/Twig/NotifyRuntime.php index 24e91d2245e..374c0b529da 100644 --- a/src/Notify/src/Twig/NotifyRuntime.php +++ b/src/Notify/src/Twig/NotifyRuntime.php @@ -53,6 +53,6 @@ public function renderStreamNotifications(array|string $topics = [], array $opti $stimulusAttributes->addController($name, $controllerValues); } - return trim(sprintf('
    ', $stimulusAttributes)); + return trim(\sprintf('
    ', $stimulusAttributes)); } } diff --git a/src/React/src/AssetMapper/ReactControllerLoaderAssetCompiler.php b/src/React/src/AssetMapper/ReactControllerLoaderAssetCompiler.php index 5f40016c8ab..d998471d5b4 100644 --- a/src/React/src/AssetMapper/ReactControllerLoaderAssetCompiler.php +++ b/src/React/src/AssetMapper/ReactControllerLoaderAssetCompiler.php @@ -50,18 +50,18 @@ public function compile(string $content, MappedAsset $asset, AssetMapperInterfac $relativeImportPath = Path::makeRelative($mappedAsset->sourcePath, \dirname($asset->sourcePath)); } - $controllerNameForVariable = sprintf('component_%s', \count($componentParts)); + $controllerNameForVariable = \sprintf('component_%s', \count($componentParts)); - $importLines[] = sprintf( + $importLines[] = \sprintf( "import %s from '%s';", $controllerNameForVariable, $relativeImportPath ); - $componentParts[] = sprintf('"%s": %s', $name, $controllerNameForVariable); + $componentParts[] = \sprintf('"%s": %s', $name, $controllerNameForVariable); } $importCode = implode("\n", $importLines); - $componentsJson = sprintf('{%s}', implode(', ', $componentParts)); + $componentsJson = \sprintf('{%s}', implode(', ', $componentParts)); return <<getAssetFromSourcePath($file->getRealPath()); if (null === $asset) { - throw new \LogicException(sprintf('Could not find an asset mapper path for the React controller file "%s".', $file->getRealPath())); + throw new \LogicException(\sprintf('Could not find an asset mapper path for the React controller file "%s".', $file->getRealPath())); } $name = $file->getRelativePathname(); diff --git a/src/StimulusBundle/src/AssetMapper/AutoImportLocator.php b/src/StimulusBundle/src/AssetMapper/AutoImportLocator.php index 06dc7842ea8..35ea5515519 100644 --- a/src/StimulusBundle/src/AssetMapper/AutoImportLocator.php +++ b/src/StimulusBundle/src/AssetMapper/AutoImportLocator.php @@ -37,12 +37,12 @@ public function locateAutoImport(string $path, UxPackageMetadata $packageMetadat $slashPosition = strpos($path, '/'); if (false === $slashPosition) { - throw new \LogicException(sprintf('The autoimport "%s" is not valid.', $path)); + throw new \LogicException(\sprintf('The autoimport "%s" is not valid.', $path)); } $parts = explode('/', ltrim($path, '@')); if (2 > \count($parts)) { - throw new \LogicException(sprintf('The autoimport "%s" is not valid.', $path)); + throw new \LogicException(\sprintf('The autoimport "%s" is not valid.', $path)); } $package = implode('/', \array_slice($parts, 0, 2)); $file = implode('/', \array_slice($parts, 2)); @@ -51,12 +51,12 @@ public function locateAutoImport(string $path, UxPackageMetadata $packageMetadat // this is a file local to the ux package $filePath = $packageMetadata->packageDirectory.'/'.$file; if (!is_file($filePath)) { - throw new \LogicException(sprintf('An "autoimport" in "controllers.json" refers to "%s". This path could not be found in the asset mapper and the file "%s" does not exist in the package path "%s". And so, the file cannot be loaded.', $path, $filePath, $packageMetadata->packageDirectory)); + throw new \LogicException(\sprintf('An "autoimport" in "controllers.json" refers to "%s". This path could not be found in the asset mapper and the file "%s" does not exist in the package path "%s". And so, the file cannot be loaded.', $path, $filePath, $packageMetadata->packageDirectory)); } $asset = $this->assetMapper->getAssetFromSourcePath($filePath); if (!$asset) { - throw new \LogicException(sprintf('An "autoimport" in "controllers.json" refers to "%s". This file was found, but the path is not in the asset mapper. And so, the file cannot be loaded. This is a misconfiguration with the bundle providing this.', $path)); + throw new \LogicException(\sprintf('An "autoimport" in "controllers.json" refers to "%s". This file was found, but the path is not in the asset mapper. And so, the file cannot be loaded. This is a misconfiguration with the bundle providing this.', $path)); } return new MappedControllerAutoImport($asset->sourcePath, false); @@ -64,7 +64,7 @@ public function locateAutoImport(string $path, UxPackageMetadata $packageMetadat $entry = $this->importMapConfigReader->findRootImportMapEntry($path); if (!$entry) { - throw new \LogicException(sprintf('The autoimport "%s" could not be found in importmap.php. Try running "php bin/console importmap:require %s".', $path, $path)); + throw new \LogicException(\sprintf('The autoimport "%s" could not be found in importmap.php. Try running "php bin/console importmap:require %s".', $path, $path)); } return new MappedControllerAutoImport($path, true); diff --git a/src/StimulusBundle/src/AssetMapper/ControllersMapGenerator.php b/src/StimulusBundle/src/AssetMapper/ControllersMapGenerator.php index be94775f193..4eb66984b02 100644 --- a/src/StimulusBundle/src/AssetMapper/ControllersMapGenerator.php +++ b/src/StimulusBundle/src/AssetMapper/ControllersMapGenerator.php @@ -108,7 +108,7 @@ private function loadUxControllers(): array $packageControllerConfig = $packageMetadata->symfonyConfig['controllers'][$controllerName] ?? null; if (null === $packageControllerConfig) { - throw new \RuntimeException(sprintf('Controller "%s" does not exist in the "%s" package.', $controllerReference, $packageMetadata->packageName)); + throw new \RuntimeException(\sprintf('Controller "%s" does not exist in the "%s" package.', $controllerReference, $packageMetadata->packageName)); } if (!$localControllerConfig['enabled']) { @@ -132,7 +132,7 @@ private function loadUxControllers(): array $asset = $this->assetMapper->getAssetFromSourcePath($controllerMainPath); if (!$asset) { - throw new \RuntimeException(sprintf('Could not find an asset mapper path that points to the "%s" controller in package "%s", defined in controllers.json.', $controllerName, $packageMetadata->packageName)); + throw new \RuntimeException(\sprintf('Could not find an asset mapper path that points to the "%s" controller in package "%s", defined in controllers.json.', $controllerName, $packageMetadata->packageName)); } $autoImports = $this->collectAutoImports($localControllerConfig['autoimport'] ?? [], $packageMetadata); @@ -154,7 +154,7 @@ private function collectAutoImports(array $autoImports, UxPackageMetadata $curre return []; } if (null === $this->autoImportLocator) { - throw new \InvalidArgumentException(sprintf('The "autoImportLocator" argument to "%s" is required when using AssetMapper 6.4', self::class)); + throw new \InvalidArgumentException(\sprintf('The "autoImportLocator" argument to "%s" is required when using AssetMapper 6.4', self::class)); } $autoImportItems = []; diff --git a/src/StimulusBundle/src/AssetMapper/StimulusLoaderJavaScriptCompiler.php b/src/StimulusBundle/src/AssetMapper/StimulusLoaderJavaScriptCompiler.php index 72f7c1e090f..d6603771be5 100644 --- a/src/StimulusBundle/src/AssetMapper/StimulusLoaderJavaScriptCompiler.php +++ b/src/StimulusBundle/src/AssetMapper/StimulusLoaderJavaScriptCompiler.php @@ -91,35 +91,35 @@ public function compile(string $content, MappedAsset $asset, AssetMapperInterfac if ($mappedControllerAsset->isLazy) { if (!$mappedControllerAsset->autoImports) { - $lazyControllers[] = sprintf('%s: () => import(%s)', json_encode($name), $relativeImportPath); + $lazyControllers[] = \sprintf('%s: () => import(%s)', json_encode($name), $relativeImportPath); } else { // import $relativeImportPath and also the auto-imports // and use a Promise.all() to wait for all of them - $lazyControllers[] = sprintf('%s: () => Promise.all([import(%s), %s]).then((ret) => ret[0])', json_encode($name), $relativeImportPath, implode(', ', array_map(fn ($path) => "import($path)", $autoImportPaths))); + $lazyControllers[] = \sprintf('%s: () => Promise.all([import(%s), %s]).then((ret) => ret[0])', json_encode($name), $relativeImportPath, implode(', ', array_map(fn ($path) => "import($path)", $autoImportPaths))); } continue; } - $controllerNameForVariable = sprintf('controller_%s', \count($eagerControllerParts)); + $controllerNameForVariable = \sprintf('controller_%s', \count($eagerControllerParts)); - $importLines[] = sprintf( + $importLines[] = \sprintf( 'import %s from %s;', $controllerNameForVariable, $relativeImportPath ); foreach ($autoImportPaths as $autoImportRelativePath) { - $importLines[] = sprintf( + $importLines[] = \sprintf( 'import %s;', $autoImportRelativePath ); } - $eagerControllerParts[] = sprintf('"%s": %s', $name, $controllerNameForVariable); + $eagerControllerParts[] = \sprintf('"%s": %s', $name, $controllerNameForVariable); } $importCode = implode("\n", $importLines); - $eagerControllersJson = sprintf('{%s}', implode(', ', $eagerControllerParts)); - $lazyControllersExpression = sprintf('{%s}', implode(', ', $lazyControllers)); + $eagerControllersJson = \sprintf('{%s}', implode(', ', $eagerControllerParts)); + $lazyControllersExpression = \sprintf('{%s}', implode(', ', $lazyControllers)); $isDebugString = $this->isDebug ? 'true' : 'false'; diff --git a/src/StimulusBundle/src/Dto/StimulusAttributes.php b/src/StimulusBundle/src/Dto/StimulusAttributes.php index f3cc035c7d5..c1038922cf4 100644 --- a/src/StimulusBundle/src/Dto/StimulusAttributes.php +++ b/src/StimulusBundle/src/Dto/StimulusAttributes.php @@ -138,16 +138,16 @@ public function __toString(): string $attributes = []; if ($controllers) { - $attributes[] = sprintf('data-controller="%s"', implode(' ', $controllers)); + $attributes[] = \sprintf('data-controller="%s"', implode(' ', $controllers)); } if ($actions) { - $attributes[] = sprintf('data-action="%s"', implode(' ', $actions)); + $attributes[] = \sprintf('data-action="%s"', implode(' ', $actions)); } if ($targets) { $attributes[] = implode(' ', array_map(function (string $key, string $value): string { - return sprintf('%s="%s"', $key, $value); + return \sprintf('%s="%s"', $key, $value); }, array_keys($targets), $targets)); } diff --git a/src/StimulusBundle/src/Twig/UxControllersTwigRuntime.php b/src/StimulusBundle/src/Twig/UxControllersTwigRuntime.php index 77a2217adfb..16994eae2ba 100644 --- a/src/StimulusBundle/src/Twig/UxControllersTwigRuntime.php +++ b/src/StimulusBundle/src/Twig/UxControllersTwigRuntime.php @@ -64,7 +64,7 @@ public function renderLinkTags(): string foreach ($controllerData['autoimport'] ?? [] as $autoImport => $enabled) { if ($enabled) { - $links[] = sprintf('', $this->getLinkHref($autoImport, $uxPackageName)); + $links[] = \sprintf('', $this->getLinkHref($autoImport, $uxPackageName)); } } } @@ -84,7 +84,7 @@ private function getLinkHref(string $autoImport, string $uxPackageName): string $slashPosition = strpos($autoImport, '/'); if (false === $slashPosition) { - throw new \LogicException(sprintf('The autoimport "%s" is not valid.', $autoImport)); + throw new \LogicException(\sprintf('The autoimport "%s" is not valid.', $autoImport)); } // if the first character is @, then the package name is @symfony/ux-cropperjs @@ -102,12 +102,12 @@ private function getLinkHref(string $autoImport, string $uxPackageName): string $uxPackageMetadata = $this->uxPackageReader->readPackageMetadata($uxPackageName); $filePath = $uxPackageMetadata->packageDirectory.'/'.$file; if (!is_file($filePath)) { - throw new \LogicException(sprintf('An "autoimport" in "%s" refers to "%s". This path could not be found in the asset mapper and the file "%s" does not exist in the package path "%s". And so, the file cannot be loaded.', $this->shortControllersPath(), $autoImport, $file, $uxPackageMetadata->packageDirectory)); + throw new \LogicException(\sprintf('An "autoimport" in "%s" refers to "%s". This path could not be found in the asset mapper and the file "%s" does not exist in the package path "%s". And so, the file cannot be loaded.', $this->shortControllersPath(), $autoImport, $file, $uxPackageMetadata->packageDirectory)); } $asset = $this->assetMapper->getAssetFromSourcePath($filePath); if (!$asset) { - throw new \LogicException(sprintf('An "autoimport" in "%s" refers to "%s". This file was found, but the path is not in the asset mapper. And so, the file cannot be loaded.', $this->shortControllersPath(), $autoImport)); + throw new \LogicException(\sprintf('An "autoimport" in "%s" refers to "%s". This file was found, but the path is not in the asset mapper. And so, the file cannot be loaded.', $this->shortControllersPath(), $autoImport)); } return $asset->publicPath; @@ -115,12 +115,12 @@ private function getLinkHref(string $autoImport, string $uxPackageName): string $importMap = $this->readImportMap(); if (!isset($importMap[$package])) { - throw new \LogicException(sprintf('An "autoimport" in "%s" refers to "%s". This path could not be found in the asset mapper and no "%s" entry was found in importmap.php. And so, the file cannot be loaded.', $this->shortControllersPath(), $autoImport, $package)); + throw new \LogicException(\sprintf('An "autoimport" in "%s" refers to "%s". This path could not be found in the asset mapper and no "%s" entry was found in importmap.php. And so, the file cannot be loaded.', $this->shortControllersPath(), $autoImport, $package)); } $importMapEntry = $importMap[$package]; if (!isset($importMapEntry['url'])) { - throw new \LogicException(sprintf('An "autoimport" in "%s" refers to "%s". This path could not be found in the asset mapper and no "url" key was found in importmap.php for the package "%s". And so, the file cannot be loaded.', $this->shortControllersPath(), $autoImport, $package)); + throw new \LogicException(\sprintf('An "autoimport" in "%s" refers to "%s". This path could not be found in the asset mapper and no "url" key was found in importmap.php for the package "%s". And so, the file cannot be loaded.', $this->shortControllersPath(), $autoImport, $package)); } $version = $this->parseVersionFromUrl($importMapEntry['url']); @@ -154,7 +154,7 @@ private function getJsDelivrUrl(string $package, ?string $version, string $file) $version = $version ?? 'latest'; $package = str_replace('@', '', $package); - return sprintf('https://cdn.jsdelivr.net/npm/%s@%s/%s', $package, $version, $file); + return \sprintf('https://cdn.jsdelivr.net/npm/%s@%s/%s', $package, $version, $file); } private function shortControllersPath(): string diff --git a/src/StimulusBundle/src/Ux/UxPackageReader.php b/src/StimulusBundle/src/Ux/UxPackageReader.php index a291eae4522..dd1fb9efbf5 100644 --- a/src/StimulusBundle/src/Ux/UxPackageReader.php +++ b/src/StimulusBundle/src/Ux/UxPackageReader.php @@ -35,14 +35,14 @@ public function readPackageMetadata(string $packageName): UxPackageMetadata } if (!is_dir($phpPackagePath)) { - throw new \RuntimeException(sprintf('Could not find package "%s" referred to from controllers.json.', $phpPackageName)); + throw new \RuntimeException(\sprintf('Could not find package "%s" referred to from controllers.json.', $phpPackageName)); } $packageConfigJsonPath = $phpPackagePath.'/assets/package.json'; if (!file_exists($packageConfigJsonPath)) { $packageConfigJsonPath = $phpPackagePath.'/Resources/assets/package.json'; } if (!file_exists($packageConfigJsonPath)) { - throw new \RuntimeException(sprintf('Could not find package.json in the "%s" package.', $phpPackagePath)); + throw new \RuntimeException(\sprintf('Could not find package.json in the "%s" package.', $phpPackagePath)); } $packageConfigJson = file_get_contents($packageConfigJsonPath); diff --git a/src/Svelte/src/AssetMapper/SvelteControllerLoaderAssetCompiler.php b/src/Svelte/src/AssetMapper/SvelteControllerLoaderAssetCompiler.php index 2e36fb6d003..20ac80947c2 100644 --- a/src/Svelte/src/AssetMapper/SvelteControllerLoaderAssetCompiler.php +++ b/src/Svelte/src/AssetMapper/SvelteControllerLoaderAssetCompiler.php @@ -50,18 +50,18 @@ public function compile(string $content, MappedAsset $asset, AssetMapperInterfac $relativeImportPath = Path::makeRelative($mappedAsset->sourcePath, \dirname($asset->sourcePath)); } - $controllerNameForVariable = sprintf('component_%s', \count($componentParts)); + $controllerNameForVariable = \sprintf('component_%s', \count($componentParts)); - $importLines[] = sprintf( + $importLines[] = \sprintf( "import %s from '%s';", $controllerNameForVariable, $relativeImportPath ); - $componentParts[] = sprintf('"%s": %s', $name, $controllerNameForVariable); + $componentParts[] = \sprintf('"%s": %s', $name, $controllerNameForVariable); } $importCode = implode("\n", $importLines); - $componentsJson = sprintf('{%s}', implode(', ', $componentParts)); + $componentsJson = \sprintf('{%s}', implode(', ', $componentParts)); return <<getAssetFromSourcePath($file->getRealPath()); if (null === $asset) { - throw new \LogicException(sprintf('Could not find an asset mapper path for the Svelte controller file "%s".', $file->getRealPath())); + throw new \LogicException(\sprintf('Could not find an asset mapper path for the Svelte controller file "%s".', $file->getRealPath())); } $name = $file->getRelativePathname(); diff --git a/src/TogglePassword/src/Form/TogglePasswordTypeExtension.php b/src/TogglePassword/src/Form/TogglePasswordTypeExtension.php index 016eb3c0152..b639399a9be 100644 --- a/src/TogglePassword/src/Form/TogglePasswordTypeExtension.php +++ b/src/TogglePassword/src/Form/TogglePasswordTypeExtension.php @@ -79,7 +79,7 @@ public function buildView(FormView $view, FormInterface $form, array $options): } $controllerName = 'symfony--ux-toggle-password--toggle-password'; - $view->vars['attr']['data-controller'] = trim(sprintf('%s %s', $view->vars['attr']['data-controller'] ?? '', $controllerName)); + $view->vars['attr']['data-controller'] = trim(\sprintf('%s %s', $view->vars['attr']['data-controller'] ?? '', $controllerName)); if (false !== $options['toggle_translation_domain']) { $controllerValues['hidden-label'] = $this->translateLabel($options['hidden_label'], $options['toggle_translation_domain']); @@ -94,7 +94,7 @@ public function buildView(FormView $view, FormInterface $form, array $options): $controllerValues['button-classes'] = json_encode($options['button_classes'], \JSON_THROW_ON_ERROR); foreach ($controllerValues as $name => $value) { - $view->vars['attr'][sprintf('data-%s-%s-value', $controllerName, $name)] = $value; + $view->vars['attr'][\sprintf('data-%s-%s-value', $controllerName, $name)] = $value; } $view->vars['toggle_container_classes'] = $options['toggle_container_classes']; diff --git a/src/Translator/src/Intl/IntlMessageParser.php b/src/Translator/src/Intl/IntlMessageParser.php index 614127b406a..839de42fbf4 100644 --- a/src/Translator/src/Intl/IntlMessageParser.php +++ b/src/Translator/src/Intl/IntlMessageParser.php @@ -980,7 +980,7 @@ private function bumpUntil(string $pattern): bool private function bumpTo(int $targetOffset) { if ($this->offset() > $targetOffset) { - throw new \Exception(sprintf('targetOffset %s must be greater than or equal to the current offset %d', $targetOffset, $this->offset())); + throw new \Exception(\sprintf('targetOffset %s must be greater than or equal to the current offset %d', $targetOffset, $this->offset())); } $targetOffset = min($targetOffset, s($this->message)->length()); diff --git a/src/Translator/src/MessageParameters/Extractor/IntlMessageParametersExtractor.php b/src/Translator/src/MessageParameters/Extractor/IntlMessageParametersExtractor.php index f90e61e3186..6722f882836 100644 --- a/src/Translator/src/MessageParameters/Extractor/IntlMessageParametersExtractor.php +++ b/src/Translator/src/MessageParameters/Extractor/IntlMessageParametersExtractor.php @@ -28,7 +28,7 @@ public function extract(string $message): array $intlMessageParser = new IntlMessageParser($message); $ast = $intlMessageParser->parse(); if ($ast['err']) { - throw new \InvalidArgumentException(sprintf('The message "%s" is not a valid Intl message.', $message)); + throw new \InvalidArgumentException(\sprintf('The message "%s" is not a valid Intl message.', $message)); } $nodes = $ast['val']; diff --git a/src/Translator/src/MessageParameters/Printer/TypeScriptMessageParametersPrinter.php b/src/Translator/src/MessageParameters/Printer/TypeScriptMessageParametersPrinter.php index 523c08f647b..4eaf9c89b91 100644 --- a/src/Translator/src/MessageParameters/Printer/TypeScriptMessageParametersPrinter.php +++ b/src/Translator/src/MessageParameters/Printer/TypeScriptMessageParametersPrinter.php @@ -50,10 +50,10 @@ public function print(array $parameters): string $value = 'Date'; break; default: - throw new \InvalidArgumentException(sprintf('Unknown type "%s" for parameter "%s"', $parameter['type'], $parameterName)); + throw new \InvalidArgumentException(\sprintf('Unknown type "%s" for parameter "%s"', $parameter['type'], $parameterName)); } - $type .= sprintf("'%s': %s, ", $parameterName, $value); + $type .= \sprintf("'%s': %s, ", $parameterName, $value); } $type = rtrim($type, ', '); diff --git a/src/Translator/src/TranslationsDumper.php b/src/Translator/src/TranslationsDumper.php index 6359892f764..751f4203da0 100644 --- a/src/Translator/src/TranslationsDumper.php +++ b/src/Translator/src/TranslationsDumper.php @@ -55,7 +55,7 @@ public function dump(MessageCatalogueInterface ...$catalogues): void foreach ($this->getTranslations(...$catalogues) as $translationId => $translationsByDomainAndLocale) { $constantName = $this->generateConstantName($translationId); - $translationsJs .= sprintf( + $translationsJs .= \sprintf( "export const %s = %s;\n", $constantName, json_encode([ @@ -63,7 +63,7 @@ public function dump(MessageCatalogueInterface ...$catalogues): void 'translations' => $translationsByDomainAndLocale, ], \JSON_THROW_ON_ERROR), ); - $translationsTs .= sprintf( + $translationsTs .= \sprintf( "export declare const %s: %s;\n", $constantName, $this->getTranslationsTypeScriptTypeDefinition($translationsByDomainAndLocale) @@ -72,7 +72,7 @@ public function dump(MessageCatalogueInterface ...$catalogues): void $this->filesystem->dumpFile($this->dumpDir.'/index.js', $translationsJs); $this->filesystem->dumpFile($this->dumpDir.'/index.d.ts', $translationsTs); - $this->filesystem->dumpFile($this->dumpDir.'/configuration.js', sprintf( + $this->filesystem->dumpFile($this->dumpDir.'/configuration.js', \sprintf( "export const localeFallbacks = %s;\n", json_encode($this->getLocaleFallbacks(...$catalogues), \JSON_THROW_ON_ERROR) )); @@ -126,7 +126,7 @@ private function getTranslationsTypeScriptTypeDefinition(array $translationsByDo ? $this->intlMessageParametersExtractor->extract($translation) : $this->messageParametersExtractor->extract($translation); } catch (\Throwable $e) { - throw new \Exception(sprintf('Error while extracting parameters from message "%s" in domain "%s" and locale "%s".', $translation, $domain, $locale), previous: $e); + throw new \Exception(\sprintf('Error while extracting parameters from message "%s" in domain "%s" and locale "%s".', $translation, $domain, $locale), previous: $e); } $parametersTypes[$domain] = $this->typeScriptMessageParametersPrinter->print($parameters); @@ -135,13 +135,13 @@ private function getTranslationsTypeScriptTypeDefinition(array $translationsByDo } } - return sprintf( + return \sprintf( 'Message<{ %s }, %s>', implode(', ', array_reduce( array_keys($parametersTypes), fn (array $carry, string $domain) => [ ...$carry, - sprintf("'%s': { parameters: %s }", $domain, $parametersTypes[$domain]), + \sprintf("'%s': { parameters: %s }", $domain, $parametersTypes[$domain]), ], [], )), diff --git a/src/Turbo/src/Bridge/Mercure/Broadcaster.php b/src/Turbo/src/Bridge/Mercure/Broadcaster.php index e727a1276db..a31e79a9086 100644 --- a/src/Turbo/src/Bridge/Mercure/Broadcaster.php +++ b/src/Turbo/src/Bridge/Mercure/Broadcaster.php @@ -65,11 +65,11 @@ public function broadcast(object $entity, string $action, array $options): void $entityClass = ClassUtil::getEntityClass($entity); if (!isset($options['rendered_action'])) { - throw new \InvalidArgumentException(sprintf('Cannot broadcast entity of class "%s" as option "rendered_action" is missing.', $entityClass)); + throw new \InvalidArgumentException(\sprintf('Cannot broadcast entity of class "%s" as option "rendered_action" is missing.', $entityClass)); } if (!isset($options['topics']) && !isset($options['id'])) { - throw new \InvalidArgumentException(sprintf('Cannot broadcast entity of class "%s": either option "topics" or "id" is missing, or the PropertyAccess component is not installed. Try running "composer require property-access".', $entityClass)); + throw new \InvalidArgumentException(\sprintf('Cannot broadcast entity of class "%s": either option "topics" or "id" is missing, or the PropertyAccess component is not installed. Try running "composer require property-access".', $entityClass)); } $topics = []; @@ -96,10 +96,10 @@ public function broadcast(object $entity, string $action, array $options): void if (0 === \count($options['topics'])) { if (!isset($options['id'])) { - throw new \InvalidArgumentException(sprintf('Cannot broadcast entity of class "%s": the option "topics" is empty and "id" is missing.', $entityClass)); + throw new \InvalidArgumentException(\sprintf('Cannot broadcast entity of class "%s": the option "topics" is empty and "id" is missing.', $entityClass)); } - $options['topics'] = (array) sprintf(self::TOPIC_PATTERN, rawurlencode($entityClass), rawurlencode(implode('-', (array) $options['id']))); + $options['topics'] = (array) \sprintf(self::TOPIC_PATTERN, rawurlencode($entityClass), rawurlencode(implode('-', (array) $options['id']))); } $update = new Update( diff --git a/src/Turbo/src/Bridge/Mercure/TurboStreamListenRenderer.php b/src/Turbo/src/Bridge/Mercure/TurboStreamListenRenderer.php index 97dd22b76e7..58451551e3e 100644 --- a/src/Turbo/src/Bridge/Mercure/TurboStreamListenRenderer.php +++ b/src/Turbo/src/Bridge/Mercure/TurboStreamListenRenderer.php @@ -52,13 +52,13 @@ public function renderTurboStreamListen(Environment $env, $topic): string $class = $topic::class; if (!$id = $this->idAccessor->getEntityId($topic)) { - throw new \LogicException(sprintf('Cannot listen to entity of class "%s" as the PropertyAccess component is not installed. Try running "composer require symfony/property-access".', $class)); + throw new \LogicException(\sprintf('Cannot listen to entity of class "%s" as the PropertyAccess component is not installed. Try running "composer require symfony/property-access".', $class)); } - $topic = sprintf(Broadcaster::TOPIC_PATTERN, rawurlencode($class), rawurlencode(implode('-', $id))); + $topic = \sprintf(Broadcaster::TOPIC_PATTERN, rawurlencode($class), rawurlencode(implode('-', $id))); } elseif (!preg_match('/[^a-zA-Z0-9_\x7f-\xff\\\\]/', $topic) && class_exists($topic)) { // Generate a URI template to subscribe to updates for all objects of this class - $topic = sprintf(Broadcaster::TOPIC_PATTERN, rawurlencode($topic), '{id}'); + $topic = \sprintf(Broadcaster::TOPIC_PATTERN, rawurlencode($topic), '{id}'); } $stimulusAttributes = $this->stimulusHelper->createStimulusAttributes(); diff --git a/src/Turbo/src/Twig/TwigExtension.php b/src/Turbo/src/Twig/TwigExtension.php index e23024edd17..965abb71e36 100644 --- a/src/Turbo/src/Twig/TwigExtension.php +++ b/src/Turbo/src/Twig/TwigExtension.php @@ -43,7 +43,7 @@ public function turboStreamListen(Environment $env, $topic, ?string $transport = $transport = $transport ?? $this->default; if (!$this->turboStreamListenRenderers->has($transport)) { - throw new \InvalidArgumentException(sprintf('The Turbo stream transport "%s" doesn\'t exist.', $transport)); + throw new \InvalidArgumentException(\sprintf('The Turbo stream transport "%s" doesn\'t exist.', $transport)); } return $this->turboStreamListenRenderers->get($transport)->renderTurboStreamListen($env, $topic); diff --git a/src/Turbo/tests/BroadcastTest.php b/src/Turbo/tests/BroadcastTest.php index ea57faf7628..87c06d9f8d2 100644 --- a/src/Turbo/tests/BroadcastTest.php +++ b/src/Turbo/tests/BroadcastTest.php @@ -27,7 +27,7 @@ class BroadcastTest extends PantherTestCase protected function setUp(): void { if (!file_exists(__DIR__.'/app/public/build')) { - throw new \Exception(sprintf('Move into %s and execute Encore before running this test.', realpath(__DIR__.'/app'))); + throw new \Exception(\sprintf('Move into %s and execute Encore before running this test.', realpath(__DIR__.'/app'))); } parent::setUp(); diff --git a/src/TwigComponent/src/Command/TwigComponentDebugCommand.php b/src/TwigComponent/src/Command/TwigComponentDebugCommand.php index ec47a28b47b..f727a223fcf 100644 --- a/src/TwigComponent/src/Command/TwigComponentDebugCommand.php +++ b/src/TwigComponent/src/Command/TwigComponentDebugCommand.php @@ -73,7 +73,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (\is_string($name)) { $component = $this->findComponentName($io, $name, $input->isInteractive()); if (null === $component) { - $io->error(sprintf('Unknown component "%s".', $name)); + $io->error(\sprintf('Unknown component "%s".', $name)); return Command::FAILURE; } @@ -200,7 +200,7 @@ private function displayComponentDetails(SymfonyStyle $io, string $name): void $m->getParameters(), ); - return sprintf('%s(%s)', $m->getName(), implode(', ', $params)); + return \sprintf('%s(%s)', $m->getName(), implode(', ', $params)); }; $hooks = []; if ($method = AsTwigComponent::mountMethod($metadata->getClass())) { diff --git a/src/TwigComponent/src/ComponentAttributes.php b/src/TwigComponent/src/ComponentAttributes.php index a54846e9df3..57c5e4676d6 100644 --- a/src/TwigComponent/src/ComponentAttributes.php +++ b/src/TwigComponent/src/ComponentAttributes.php @@ -52,7 +52,7 @@ function (string $carry, string $key) { } if (!\is_scalar($value) && null !== $value) { - throw new \LogicException(sprintf('A "%s" prop was passed when creating the component. No matching "%s" property or mount() argument was found, so we attempted to use this as an HTML attribute. But, the value is not a scalar (it\'s a "%s"). Did you mean to pass this to your component or is there a typo on its name?', $key, $key, get_debug_type($value))); + throw new \LogicException(\sprintf('A "%s" prop was passed when creating the component. No matching "%s" property or mount() argument was found, so we attempted to use this as an HTML attribute. But, the value is not a scalar (it\'s a "%s"). Did you mean to pass this to your component or is there a typo on its name?', $key, $key, get_debug_type($value))); } if (null === $value) { @@ -67,7 +67,7 @@ function (string $carry, string $key) { return match ($value) { true => "{$carry} {$key}", false => $carry, - default => sprintf('%s %s="%s"', $carry, $key, $value), + default => \sprintf('%s %s="%s"', $carry, $key, $value), }; }, '' @@ -94,7 +94,7 @@ public function render(string $attribute): ?string } if (!\is_string($value)) { - throw new \LogicException(sprintf('Can only get string attributes (%s is a "%s").', $attribute, get_debug_type($value))); + throw new \LogicException(\sprintf('Can only get string attributes (%s is a "%s").', $attribute, get_debug_type($value))); } $this->rendered[$attribute] = true; @@ -183,7 +183,7 @@ public function add($stimulusDto): self return $this->defaults($stimulusDto); } else { - throw new \InvalidArgumentException(sprintf('Argument 1 passed to "%s()" must be an instance of "%s" or "%s", "%s" given.', __METHOD__, AbstractStimulusDto::class, StimulusAttributes::class, get_debug_type($stimulusDto))); + throw new \InvalidArgumentException(\sprintf('Argument 1 passed to "%s()" must be an instance of "%s" or "%s", "%s" given.', __METHOD__, AbstractStimulusDto::class, StimulusAttributes::class, get_debug_type($stimulusDto))); } $controllersAttributes = $stimulusDto->toArray(); diff --git a/src/TwigComponent/src/ComponentFactory.php b/src/TwigComponent/src/ComponentFactory.php index 4f9767d42a3..2a677d38803 100644 --- a/src/TwigComponent/src/ComponentFactory.php +++ b/src/TwigComponent/src/ComponentFactory.php @@ -152,7 +152,7 @@ private function mount(object $component, array &$data): void } elseif ($refParameter->isDefaultValueAvailable()) { $parameters[] = $refParameter->getDefaultValue(); } else { - throw new \LogicException(sprintf('%s::mount() has a required $%s parameter. Make sure this is passed or make give a default value.', $component::class, $refParameter->getName())); + throw new \LogicException(\sprintf('%s::mount() has a required $%s parameter. Make sure this is passed or make give a default value.', $component::class, $refParameter->getName())); } } @@ -225,7 +225,7 @@ private function isAnonymousComponent(string $name): bool */ private function throwUnknownComponentException(string $name): void { - $message = sprintf('Unknown component "%s".', $name); + $message = \sprintf('Unknown component "%s".', $name); $lowerName = strtolower($name); $nameLength = \strlen($lowerName); $alternatives = []; diff --git a/src/TwigComponent/src/ComponentRenderer.php b/src/TwigComponent/src/ComponentRenderer.php index fd81f1a187e..cfe9f208541 100644 --- a/src/TwigComponent/src/ComponentRenderer.php +++ b/src/TwigComponent/src/ComponentRenderer.php @@ -177,7 +177,7 @@ private function exposedVariables(object $component, bool $exposePublicProps): \ $name = $attribute->name ?? (str_starts_with($method->name, 'get') ? lcfirst(substr($method->name, 3)) : $method->name); if ($method->getNumberOfRequiredParameters()) { - throw new \LogicException(sprintf('Cannot use "%s" on methods with required parameters (%s::%s).', ExposeInTemplate::class, $component::class, $method->name)); + throw new \LogicException(\sprintf('Cannot use "%s" on methods with required parameters (%s::%s).', ExposeInTemplate::class, $component::class, $method->name)); } if ($attribute->destruct) { diff --git a/src/TwigComponent/src/ComputedPropertiesProxy.php b/src/TwigComponent/src/ComputedPropertiesProxy.php index 0fb97dbde02..57df84b29ee 100644 --- a/src/TwigComponent/src/ComputedPropertiesProxy.php +++ b/src/TwigComponent/src/ComputedPropertiesProxy.php @@ -60,11 +60,11 @@ private function normalizeMethod(string $name): string } foreach (['get', 'is', 'has'] as $prefix) { - if (method_exists($this->component, $method = sprintf('%s%s', $prefix, ucfirst($name)))) { + if (method_exists($this->component, $method = \sprintf('%s%s', $prefix, ucfirst($name)))) { return $method; } } - throw new \InvalidArgumentException(sprintf('Component "%s" does not have a "%s" method.', $this->component::class, $name)); + throw new \InvalidArgumentException(\sprintf('Component "%s" does not have a "%s" method.', $this->component::class, $name)); } } diff --git a/src/TwigComponent/src/DependencyInjection/Compiler/TwigComponentPass.php b/src/TwigComponent/src/DependencyInjection/Compiler/TwigComponentPass.php index 10440aded2f..2a4ec1b0ba4 100644 --- a/src/TwigComponent/src/DependencyInjection/Compiler/TwigComponentPass.php +++ b/src/TwigComponent/src/DependencyInjection/Compiler/TwigComponentPass.php @@ -50,16 +50,16 @@ public function process(ContainerBuilder $container): void $name = substr($fqcn, strrpos($fqcn, '\\') + 1); } else { if (null === $defaults) { - throw new LogicException(sprintf('Could not generate a component name for class "%s": no matching namespace found under the "twig_component.defaults" to use as a root. Check the config or give your component an explicit name.', $fqcn)); + throw new LogicException(\sprintf('Could not generate a component name for class "%s": no matching namespace found under the "twig_component.defaults" to use as a root. Check the config or give your component an explicit name.', $fqcn)); } $name = str_replace('\\', ':', substr($fqcn, \strlen($defaults['namespace']))); if ($defaults['name_prefix']) { - $name = sprintf('%s:%s', $defaults['name_prefix'], $name); + $name = \sprintf('%s:%s', $defaults['name_prefix'], $name); } } if (\in_array($name, $componentNames, true)) { - throw new LogicException(sprintf('Failed creating the "%s" component with the automatic name "%s": another component already has this name. To fix this, give the component an explicit name (hint: using "%s" will override the existing component).', $fqcn, $name, $name)); + throw new LogicException(\sprintf('Failed creating the "%s" component with the automatic name "%s": another component already has this name. To fix this, give the component an explicit name (hint: using "%s" will override the existing component).', $fqcn, $name, $name)); } $tag['key'] = $name; @@ -104,6 +104,6 @@ private function calculateTemplate(string $componentName, ?array $defaults): str $componentName = substr($componentName, \strlen($defaults['name_prefix']) + 1); } - return sprintf('%s/%s.html.twig', rtrim($directory, '/'), str_replace(':', '/', $componentName)); + return \sprintf('%s/%s.html.twig', rtrim($directory, '/'), str_replace(':', '/', $componentName)); } } diff --git a/src/TwigComponent/src/DependencyInjection/TwigComponentExtension.php b/src/TwigComponent/src/DependencyInjection/TwigComponentExtension.php index 0027e319ed0..e69bfb62ce7 100644 --- a/src/TwigComponent/src/DependencyInjection/TwigComponentExtension.php +++ b/src/TwigComponent/src/DependencyInjection/TwigComponentExtension.php @@ -81,10 +81,10 @@ static function (ChildDefinition $definition, AsTwigComponent $attribute) { $container->register('ux.twig_component.component_factory', ComponentFactory::class) ->setArguments([ new Reference('ux.twig_component.component_template_finder'), - class_exists(AbstractArgument::class) ? new AbstractArgument(sprintf('Added in %s.', TwigComponentPass::class)) : null, + class_exists(AbstractArgument::class) ? new AbstractArgument(\sprintf('Added in %s.', TwigComponentPass::class)) : null, new Reference('property_accessor'), new Reference('event_dispatcher'), - class_exists(AbstractArgument::class) ? new AbstractArgument(sprintf('Added in %s.', TwigComponentPass::class)) : [], + class_exists(AbstractArgument::class) ? new AbstractArgument(\sprintf('Added in %s.', TwigComponentPass::class)) : [], ]) ; @@ -116,7 +116,7 @@ class_exists(AbstractArgument::class) ? new AbstractArgument(sprintf('Added in % new Parameter('twig.default_path'), new Reference('ux.twig_component.component_factory'), new Reference('twig'), - class_exists(AbstractArgument::class) ? new AbstractArgument(sprintf('Added in %s.', TwigComponentPass::class)) : [], + class_exists(AbstractArgument::class) ? new AbstractArgument(\sprintf('Added in %s.', TwigComponentPass::class)) : [], $config['anonymous_template_directory'], ]) ->addTag('console.command') @@ -155,7 +155,7 @@ public function getConfigTreeBuilder(): TreeBuilder ->always(function ($v) { foreach ($v as $namespace => $defaults) { if (!str_ends_with($namespace, '\\')) { - throw new InvalidConfigurationException(sprintf('The twig_component.defaults namespace "%s" is invalid: it must end in a "\".', $namespace)); + throw new InvalidConfigurationException(\sprintf('The twig_component.defaults namespace "%s" is invalid: it must end in a "\".', $namespace)); } } diff --git a/src/TwigComponent/src/Event/PostMountEvent.php b/src/TwigComponent/src/Event/PostMountEvent.php index e8783fcb9de..45dfed3bf65 100644 --- a/src/TwigComponent/src/Event/PostMountEvent.php +++ b/src/TwigComponent/src/Event/PostMountEvent.php @@ -35,10 +35,10 @@ public function __construct( $this->extraMetadata = $metadata; } else { if (null !== $metadata && !$metadata instanceof ComponentMetadata) { - throw new \InvalidArgumentException(sprintf('Expecting "$metadata" to be null or an instance of "%s", given: "%s."', ComponentMetadata::class, get_debug_type($metadata))); + throw new \InvalidArgumentException(\sprintf('Expecting "$metadata" to be null or an instance of "%s", given: "%s."', ComponentMetadata::class, get_debug_type($metadata))); } if (!\is_array($extraMetadata)) { - throw new \InvalidArgumentException(sprintf('Expecting "$extraMetadata" to be array, given: "%s".', get_debug_type($extraMetadata))); + throw new \InvalidArgumentException(\sprintf('Expecting "$extraMetadata" to be array, given: "%s".', get_debug_type($extraMetadata))); } $this->metadata = $metadata; diff --git a/src/TwigComponent/src/MountedComponent.php b/src/TwigComponent/src/MountedComponent.php index 4406f9c41bf..45e9b501d60 100644 --- a/src/TwigComponent/src/MountedComponent.php +++ b/src/TwigComponent/src/MountedComponent.php @@ -69,7 +69,7 @@ public function hasExtraMetadata(string $key): bool public function getExtraMetadata(string $key): mixed { if (!$this->hasExtraMetadata($key)) { - throw new \InvalidArgumentException(sprintf('No extra metadata for key "%s" found.', $key)); + throw new \InvalidArgumentException(\sprintf('No extra metadata for key "%s" found.', $key)); } return $this->extraMetadata[$key]; diff --git a/src/TwigComponent/src/Test/InteractsWithTwigComponents.php b/src/TwigComponent/src/Test/InteractsWithTwigComponents.php index 45db16a3d66..6de97629cc0 100644 --- a/src/TwigComponent/src/Test/InteractsWithTwigComponents.php +++ b/src/TwigComponent/src/Test/InteractsWithTwigComponents.php @@ -21,7 +21,7 @@ trait InteractsWithTwigComponents protected function mountTwigComponent(string $name, array $data = []): object { if (!$this instanceof KernelTestCase) { - throw new \LogicException(sprintf('The "%s" trait can only be used on "%s" classes.', __TRAIT__, KernelTestCase::class)); + throw new \LogicException(\sprintf('The "%s" trait can only be used on "%s" classes.', __TRAIT__, KernelTestCase::class)); } return static::getContainer()->get('ux.twig_component.component_factory')->create($name, $data)->getComponent(); @@ -33,7 +33,7 @@ protected function mountTwigComponent(string $name, array $data = []): object protected function renderTwigComponent(string $name, array $data = [], ?string $content = null, array $blocks = []): RenderedComponent { if (!$this instanceof KernelTestCase) { - throw new \LogicException(sprintf('The "%s" trait can only be used on "%s" classes.', __TRAIT__, KernelTestCase::class)); + throw new \LogicException(\sprintf('The "%s" trait can only be used on "%s" classes.', __TRAIT__, KernelTestCase::class)); } $blocks = array_filter(array_merge($blocks, ['content' => $content])); @@ -49,10 +49,10 @@ protected function renderTwigComponent(string $name, array $data = [], ?string $ ); } - $template = sprintf('{%% component "%s" with data %%}', addslashes($name)); + $template = \sprintf('{%% component "%s" with data %%}', addslashes($name)); foreach (array_keys($blocks) as $blockName) { - $template .= sprintf('{%% block %1$s %%}{{ blocks.%1$s|raw }}{%% endblock %%}', $blockName); + $template .= \sprintf('{%% block %1$s %%}{{ blocks.%1$s|raw }}{%% endblock %%}', $blockName); } $template .= '{% endcomponent %}'; diff --git a/src/TwigComponent/src/Test/RenderedComponent.php b/src/TwigComponent/src/Test/RenderedComponent.php index ac3469cb17d..f35a843347b 100644 --- a/src/TwigComponent/src/Test/RenderedComponent.php +++ b/src/TwigComponent/src/Test/RenderedComponent.php @@ -28,7 +28,7 @@ public function __construct(private string $html) public function crawler(): Crawler { if (!class_exists(Crawler::class)) { - throw new \LogicException(sprintf('"symfony/dom-crawler" is required to use "%s()" (install with "composer require symfony/dom-crawler").', __METHOD__)); + throw new \LogicException(\sprintf('"symfony/dom-crawler" is required to use "%s()" (install with "composer require symfony/dom-crawler").', __METHOD__)); } return new Crawler($this->html); diff --git a/src/TwigComponent/src/Twig/ComponentExtension.php b/src/TwigComponent/src/Twig/ComponentExtension.php index af859bc813a..82fa37a972a 100644 --- a/src/TwigComponent/src/Twig/ComponentExtension.php +++ b/src/TwigComponent/src/Twig/ComponentExtension.php @@ -124,6 +124,6 @@ private function throwRuntimeError(string $name, \Throwable $e): void $e = new \Exception($e->getMessage(), $e->getCode(), $e->getPrevious()); } - throw new RuntimeError(sprintf('Error rendering "%s" component: %s', $name, $e->getMessage()), previous: $e); + throw new RuntimeError(\sprintf('Error rendering "%s" component: %s', $name, $e->getMessage()), previous: $e); } } diff --git a/src/TwigComponent/src/Twig/ComponentNode.php b/src/TwigComponent/src/Twig/ComponentNode.php index 3c46f0e6bde..5fd9b2f5f82 100644 --- a/src/TwigComponent/src/Twig/ComponentNode.php +++ b/src/TwigComponent/src/Twig/ComponentNode.php @@ -135,7 +135,7 @@ public function compile(Compiler $compiler): void $compiler->write('if (!isset($embeddedContext["outerBlocks"])) {') ->raw("\n") ->indent() - ->write(sprintf('$embeddedContext["outerBlocks"] = new \%s();', BlockStack::class)) + ->write(\sprintf('$embeddedContext["outerBlocks"] = new \%s();', BlockStack::class)) ->raw("\n") ->outdent() ->write('}') diff --git a/src/TwigComponent/src/Twig/ComponentTokenParser.php b/src/TwigComponent/src/Twig/ComponentTokenParser.php index 8c5151bbb0c..dbb1cf74250 100644 --- a/src/TwigComponent/src/Twig/ComponentTokenParser.php +++ b/src/TwigComponent/src/Twig/ComponentTokenParser.php @@ -113,7 +113,7 @@ private function parseArguments(): array private function generateEmbeddedTemplateIndex(string $file, int $line): int { - $fileAndLine = sprintf('%s-%d', $file, $line); + $fileAndLine = \sprintf('%s-%d', $file, $line); if (!isset($this->lineAndFileCounts[$fileAndLine])) { $this->lineAndFileCounts[$fileAndLine] = 0; } diff --git a/src/TwigComponent/src/Twig/TemplateNameParser.php b/src/TwigComponent/src/Twig/TemplateNameParser.php index 6d90e1fe7d4..2c9d5918f79 100644 --- a/src/TwigComponent/src/Twig/TemplateNameParser.php +++ b/src/TwigComponent/src/Twig/TemplateNameParser.php @@ -25,7 +25,7 @@ public static function parse(string $name): string { if (str_starts_with($name, '@')) { if (!str_contains($name, '/')) { - throw new \LogicException(sprintf('Malformed namespaced template name "%s" (expecting "@namespace/template_name").', $name)); + throw new \LogicException(\sprintf('Malformed namespaced template name "%s" (expecting "@namespace/template_name").', $name)); } return $name; diff --git a/src/TwigComponent/src/Twig/TwigPreLexer.php b/src/TwigComponent/src/Twig/TwigPreLexer.php index 16d1f897a13..3fa5f36af11 100644 --- a/src/TwigComponent/src/Twig/TwigPreLexer.php +++ b/src/TwigComponent/src/Twig/TwigPreLexer.php @@ -191,7 +191,7 @@ public function preLexComponents(string $input): string if (!empty($this->currentComponents)) { $lastComponent = array_pop($this->currentComponents)['name']; - throw new SyntaxError(sprintf('Expected closing tag "" not found.', $lastComponent), $this->line); + throw new SyntaxError(\sprintf('Expected closing tag "" not found.', $lastComponent), $this->line); } return $output; @@ -219,7 +219,7 @@ private function consumeComponentName(?string $customExceptionMessage = null): s private function consumeAttributeName(string $componentName): string { - $message = sprintf('Expected attribute name when parsing the "consumeComponentName($message); } @@ -257,10 +257,10 @@ private function consumeAttributes(string $componentName): string if (!$this->check('=')) { // don't allow "" if ($isAttributeDynamic) { - throw new SyntaxError(sprintf('Expected "=" after ":%s" when parsing the "line); + throw new SyntaxError(\sprintf('Expected "=" after ":%s" when parsing the "line); } - $attributes[] = sprintf('%s: true', preg_match('/[-:]/', $key) ? "'$key'" : $key); + $attributes[] = \sprintf('%s: true', preg_match('/[-:]/', $key) ? "'$key'" : $key); $this->consumeWhitespace(); continue; } @@ -275,7 +275,7 @@ private function consumeAttributes(string $componentName): string $attributeValue = $this->consumeAttributeValue($quote); } - $attributes[] = sprintf('%s: %s', preg_match('/[-:]/', $key) ? "'$key'" : $key, '' === $attributeValue ? "''" : $attributeValue); + $attributes[] = \sprintf('%s: %s', preg_match('/[-:]/', $key) ? "'$key'" : $key, '' === $attributeValue ? "''" : $attributeValue); $this->expectAndConsumeChar($quote); $this->consumeWhitespace(); @@ -488,14 +488,14 @@ private function consumeAttributeValue(string $quote): string if ($this->check('{{')) { // mark any previous static text as complete: push into parts if ('' !== $currentPart) { - $parts[] = sprintf("'%s'", str_replace("'", "\'", $currentPart)); + $parts[] = \sprintf("'%s'", str_replace("'", "\'", $currentPart)); $currentPart = ''; } // consume the entire {{ }} block $this->consume('{{'); $this->consumeWhitespace(); - $parts[] = sprintf('(%s)', rtrim($this->consumeUntil('}}'))); + $parts[] = \sprintf('(%s)', rtrim($this->consumeUntil('}}'))); $this->expectAndConsumeChar('}'); $this->expectAndConsumeChar('}'); @@ -507,7 +507,7 @@ private function consumeAttributeValue(string $quote): string } if ('' !== $currentPart) { - $parts[] = sprintf("'%s'", str_replace("'", "\'", $currentPart)); + $parts[] = \sprintf("'%s'", str_replace("'", "\'", $currentPart)); } return implode('~', $parts); diff --git a/src/TwigComponent/tests/Integration/Twig/ComponentParserTest.php b/src/TwigComponent/tests/Integration/Twig/ComponentParserTest.php index 34ee68f4824..476ee4f24df 100644 --- a/src/TwigComponent/tests/Integration/Twig/ComponentParserTest.php +++ b/src/TwigComponent/tests/Integration/Twig/ComponentParserTest.php @@ -42,7 +42,7 @@ public function testAcceptTwigComponentTagWithValidComponentName(string $name): public function testAcceptHtmlComponentTagWithValidComponentName(string $name): void { $environment = self::createEnvironment(); - $source = sprintf('', $name, $name); + $source = \sprintf('', $name, $name); $template = $environment->createTemplate($source); @@ -55,7 +55,7 @@ public function testAcceptHtmlComponentTagWithValidComponentName(string $name): public function testAcceptHtmlSelfClosingComponentTagWithValidComponentName(string $name): void { $environment = self::createEnvironment(); - $source = sprintf('', $name); + $source = \sprintf('', $name); $template = $environment->createTemplate($source); diff --git a/src/Vue/src/AssetMapper/VueControllerLoaderAssetCompiler.php b/src/Vue/src/AssetMapper/VueControllerLoaderAssetCompiler.php index b0f4db157a3..ded6a2510d8 100644 --- a/src/Vue/src/AssetMapper/VueControllerLoaderAssetCompiler.php +++ b/src/Vue/src/AssetMapper/VueControllerLoaderAssetCompiler.php @@ -50,18 +50,18 @@ public function compile(string $content, MappedAsset $asset, AssetMapperInterfac $relativeImportPath = Path::makeRelative($mappedAsset->sourcePath, \dirname($asset->sourcePath)); } - $controllerNameForVariable = sprintf('component_%s', \count($componentParts)); + $controllerNameForVariable = \sprintf('component_%s', \count($componentParts)); - $importLines[] = sprintf( + $importLines[] = \sprintf( "import %s from '%s';", $controllerNameForVariable, $relativeImportPath ); - $componentParts[] = sprintf('"%s": %s', $name, $controllerNameForVariable); + $componentParts[] = \sprintf('"%s": %s', $name, $controllerNameForVariable); } $importCode = implode("\n", $importLines); - $componentsJson = sprintf('{%s}', implode(', ', $componentParts)); + $componentsJson = \sprintf('{%s}', implode(', ', $componentParts)); return <<getAssetFromSourcePath($file->getRealPath()); if (null === $asset) { - throw new \LogicException(sprintf('Could not find an asset mapper path for the Vue controller file "%s".', $file->getRealPath())); + throw new \LogicException(\sprintf('Could not find an asset mapper path for the Vue controller file "%s".', $file->getRealPath())); } $name = $file->getRelativePathname(); diff --git a/ux.symfony.com/.php-cs-fixer.dist.php b/ux.symfony.com/.php-cs-fixer.dist.php index 06c7f89bdc3..c5a5e79056a 100644 --- a/ux.symfony.com/.php-cs-fixer.dist.php +++ b/ux.symfony.com/.php-cs-fixer.dist.php @@ -29,6 +29,8 @@ '@Symfony:risky' => true, 'header_comment' => ['header' => $fileHeaderComment], 'nullable_type_declaration' => true, + // 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) diff --git a/ux.symfony.com/src/Command/LoadDataCommand.php b/ux.symfony.com/src/Command/LoadDataCommand.php index 9e1c42e8f19..b27a8e7139d 100644 --- a/ux.symfony.com/src/Command/LoadDataCommand.php +++ b/ux.symfony.com/src/Command/LoadDataCommand.php @@ -124,7 +124,7 @@ private function manufactureProducts(SymfonyStyle $io): void private function clearEntity(string $className, SymfonyStyle $io): void { - $io->writeln(sprintf('Clearing %s', $className)); + $io->writeln(\sprintf('Clearing %s', $className)); $this->entityManager ->createQuery('DELETE FROM '.$className) ->execute(); diff --git a/ux.symfony.com/src/Controller/UxPackage/AutocompleteController.php b/ux.symfony.com/src/Controller/UxPackage/AutocompleteController.php index da5cedd4f30..ceca6ba9aff 100644 --- a/ux.symfony.com/src/Controller/UxPackage/AutocompleteController.php +++ b/ux.symfony.com/src/Controller/UxPackage/AutocompleteController.php @@ -71,7 +71,7 @@ private function generateEatingMessage(Collection $foods, string $name): string return $str; }); - return sprintf( + return \sprintf( 'Time for %s! Enjoy %s %s %s!', $name, \count($foodStrings) > 1 ? 'some' : 'a', diff --git a/ux.symfony.com/src/Controller/UxPackage/CropperjsController.php b/ux.symfony.com/src/Controller/UxPackage/CropperjsController.php index a060eb2be22..2edd3ad22c9 100644 --- a/ux.symfony.com/src/Controller/UxPackage/CropperjsController.php +++ b/ux.symfony.com/src/Controller/UxPackage/CropperjsController.php @@ -55,8 +55,8 @@ public function __invoke(UxPackageRepository $packageRepository, CropperInterfac if ($form->isSubmitted()) { // faking an error to let the page re-render with the cropped images $form->addError(new FormError('🤩')); - $croppedImage = sprintf('data:image/jpeg;base64,%s', base64_encode($crop->getCroppedImage())); - $croppedThumbnail = sprintf('data:image/jpeg;base64,%s', base64_encode($crop->getCroppedThumbnail(200, 150))); + $croppedImage = \sprintf('data:image/jpeg;base64,%s', base64_encode($crop->getCroppedImage())); + $croppedThumbnail = \sprintf('data:image/jpeg;base64,%s', base64_encode($crop->getCroppedThumbnail(200, 150))); } return $this->render('ux_packages/cropperjs.html.twig', [ diff --git a/ux.symfony.com/src/Controller/UxPackage/LiveComponentController.php b/ux.symfony.com/src/Controller/UxPackage/LiveComponentController.php index b65134b996f..24e2a25232e 100644 --- a/ux.symfony.com/src/Controller/UxPackage/LiveComponentController.php +++ b/ux.symfony.com/src/Controller/UxPackage/LiveComponentController.php @@ -42,6 +42,6 @@ public function redirectDemo(LiveDemoRepository $liveDemoRepository, ?string $de return $this->redirectToRoute($liveDemo->getRoute(), [], 301); } - throw $this->createNotFoundException(sprintf('Live Component demo "%s" not found.', $demo)); + throw $this->createNotFoundException(\sprintf('Live Component demo "%s" not found.', $demo)); } } diff --git a/ux.symfony.com/src/Form/MealPlannerForm.php b/ux.symfony.com/src/Form/MealPlannerForm.php index 3c07ed8b0d3..bcf1abe06cc 100644 --- a/ux.symfony.com/src/Form/MealPlannerForm.php +++ b/ux.symfony.com/src/Form/MealPlannerForm.php @@ -44,7 +44,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void ->addDependent('mainFood', 'meal', function (DependentField $field, ?Meal $meal) { $field->add(EnumType::class, [ 'class' => Food::class, - 'placeholder' => null === $meal ? 'Select a meal first' : sprintf('What\'s for %s?', $meal->getReadable()), + 'placeholder' => null === $meal ? 'Select a meal first' : \sprintf('What\'s for %s?', $meal->getReadable()), 'choices' => $meal?->getFoodChoices(), 'choice_label' => fn (Food $food): string => $food->getReadable(), 'disabled' => null === $meal, diff --git a/ux.symfony.com/src/LiveMemory/Asset/CssCompiler.php b/ux.symfony.com/src/LiveMemory/Asset/CssCompiler.php index eb8ef3ecf6d..bb6096dec71 100644 --- a/ux.symfony.com/src/LiveMemory/Asset/CssCompiler.php +++ b/ux.symfony.com/src/LiveMemory/Asset/CssCompiler.php @@ -40,7 +40,7 @@ public function compile(string $content, MappedAsset $asset, AssetMapperInterfac $filePath = Path::makeAbsolute($file, \dirname($asset->sourcePath)); if (!file_exists($filePath)) { - throw new \RuntimeException(sprintf('The file "%s" does not exist.', $filePath)); + throw new \RuntimeException(\sprintf('The file "%s" does not exist.', $filePath)); } $content = file_get_contents($filePath); diff --git a/ux.symfony.com/src/LiveMemory/Component/Board.php b/ux.symfony.com/src/LiveMemory/Component/Board.php index 8d9e45d272c..c1a2051b1fb 100644 --- a/ux.symfony.com/src/LiveMemory/Component/Board.php +++ b/ux.symfony.com/src/LiveMemory/Component/Board.php @@ -129,7 +129,7 @@ public function flip(#[LiveArg('key')] int $key): void // An old game should have stopped, so this should never happen // Even if the player clicked "too late" on a card, the game would not // be completed... meaning the card would still exist in the new game. - throw new \RuntimeException(sprintf('Game "%s" has no card "%s".', $this->game->getId(), $key)); + throw new \RuntimeException(\sprintf('Game "%s" has no card "%s".', $this->game->getId(), $key)); } // As we show "unsaved games" as initial content in the template view, diff --git a/ux.symfony.com/src/LiveMemory/Component/Timer.php b/ux.symfony.com/src/LiveMemory/Component/Timer.php index 1ce8c90bbfe..f2ea8017879 100644 --- a/ux.symfony.com/src/LiveMemory/Component/Timer.php +++ b/ux.symfony.com/src/LiveMemory/Component/Timer.php @@ -85,7 +85,7 @@ public function tick(): void */ public function getRemainingTime(): int { - $expiresAt = $this->startedAt->modify(sprintf('+%d seconds', $this->duration)); + $expiresAt = $this->startedAt->modify(\sprintf('+%d seconds', $this->duration)); $difference = max(0, $expiresAt->getTimestamp() - microtime(true)); // Number of milliseconds until the timer expires diff --git a/ux.symfony.com/src/LiveMemory/Game.php b/ux.symfony.com/src/LiveMemory/Game.php index 8582860ac5d..066dbbcda63 100644 --- a/ux.symfony.com/src/LiveMemory/Game.php +++ b/ux.symfony.com/src/LiveMemory/Game.php @@ -124,7 +124,7 @@ public function getFlipCount(): int public function addFlip(int $key): void { if (!isset($this->cards[$key])) { - throw new \InvalidArgumentException(sprintf('Invalid card key "%s".', $key)); + throw new \InvalidArgumentException(\sprintf('Invalid card key "%s".', $key)); } $this->flips[] = $key; } @@ -142,10 +142,10 @@ public function getMatchCount(): int public function addMatch(int $key): void { if (!isset($this->cards[$key])) { - throw new \InvalidArgumentException(sprintf('Invalid card key "%s".', $key)); + throw new \InvalidArgumentException(\sprintf('Invalid card key "%s".', $key)); } if (\in_array($key, $this->matches)) { - throw new \InvalidArgumentException(sprintf('Card "%s" is already matched.', $key)); + throw new \InvalidArgumentException(\sprintf('Card "%s" is already matched.', $key)); } $this->matches[] = $key; } @@ -165,7 +165,7 @@ public function getSelectedPairs(): array public function getCard(int $key): string { if (!isset($this->cards[$key])) { - throw new \InvalidArgumentException(sprintf('Invalid card key "%s".', $key)); + throw new \InvalidArgumentException(\sprintf('Invalid card key "%s".', $key)); } return $this->cards[$key]; @@ -254,7 +254,7 @@ public function setStartedAt(\DateTimeImmutable $startedAt): void public function getExpiredAt(): ?\DateTimeImmutable { - return $this->startedAt?->modify(sprintf('+%d seconds', $this->timeLimit)); + return $this->startedAt?->modify(\sprintf('+%d seconds', $this->timeLimit)); } public function getEndedAt(): ?\DateTimeImmutable diff --git a/ux.symfony.com/src/LiveMemory/GameCards.php b/ux.symfony.com/src/LiveMemory/GameCards.php index 672f22e5143..a2f0636eba3 100644 --- a/ux.symfony.com/src/LiveMemory/GameCards.php +++ b/ux.symfony.com/src/LiveMemory/GameCards.php @@ -23,7 +23,7 @@ final class GameCards */ public static function getCards(): array { - return array_map(fn ($i) => sprintf('%02d', $i), range(1, 16)); + return array_map(fn ($i) => \sprintf('%02d', $i), range(1, 16)); } /** diff --git a/ux.symfony.com/src/LiveMemory/GameFactory.php b/ux.symfony.com/src/LiveMemory/GameFactory.php index ca89e2e7474..83fa570f26f 100644 --- a/ux.symfony.com/src/LiveMemory/GameFactory.php +++ b/ux.symfony.com/src/LiveMemory/GameFactory.php @@ -21,7 +21,7 @@ final class GameFactory public static function createGame(int $level = 1): Game { if (!\in_array($level, GameLevels::getLevels())) { - throw new \InvalidArgumentException(sprintf('Level "%s" does not exist.', $level)); + throw new \InvalidArgumentException(\sprintf('Level "%s" does not exist.', $level)); } [$nbCards, $theme, $timeLimit] = array_values(GameLevels::getLevelMetadata($level)); diff --git a/ux.symfony.com/src/LiveMemory/GameLevels.php b/ux.symfony.com/src/LiveMemory/GameLevels.php index 90770e65cc2..6e6b995b051 100644 --- a/ux.symfony.com/src/LiveMemory/GameLevels.php +++ b/ux.symfony.com/src/LiveMemory/GameLevels.php @@ -46,7 +46,7 @@ public static function getLevels(): array public static function getLevelMetadata(int $level = 1): array { if (!isset(self::LEVEL_METADATA[$level])) { - throw new \InvalidArgumentException(sprintf('Level "%s" does not exist.', $level)); + throw new \InvalidArgumentException(\sprintf('Level "%s" does not exist.', $level)); } return array_combine(['nbCards', 'theme', 'timeLimit', 'grid'], self::LEVEL_METADATA[$level]); diff --git a/ux.symfony.com/src/Model/Icon/Icon.php b/ux.symfony.com/src/Model/Icon/Icon.php index 520eada0961..db1657cc4f0 100644 --- a/ux.symfony.com/src/Model/Icon/Icon.php +++ b/ux.symfony.com/src/Model/Icon/Icon.php @@ -25,10 +25,10 @@ public function __construct( private readonly string $name, ) { if (!preg_match('/[a-z-]+/', $this->prefix)) { - throw new \InvalidArgumentException(sprintf('Invalid icon prefix "%s".', $this->prefix)); + throw new \InvalidArgumentException(\sprintf('Invalid icon prefix "%s".', $this->prefix)); } if (!preg_match('/[a-z-0-9]+/', $this->name)) { - throw new \InvalidArgumentException(sprintf('Invalid icon name "%s".', $this->name)); + throw new \InvalidArgumentException(\sprintf('Invalid icon name "%s".', $this->name)); } } @@ -61,7 +61,7 @@ public function getName(): string public function getImageUrl(): string { - return sprintf('https://api.iconify.design/%s/%s.svg', $this->prefix, $this->name); + return \sprintf('https://api.iconify.design/%s/%s.svg', $this->prefix, $this->name); } public function __toString(): string diff --git a/ux.symfony.com/src/Model/Icon/IconSet.php b/ux.symfony.com/src/Model/Icon/IconSet.php index 345f31cdd41..858185e4303 100644 --- a/ux.symfony.com/src/Model/Icon/IconSet.php +++ b/ux.symfony.com/src/Model/Icon/IconSet.php @@ -144,7 +144,7 @@ public function getGithub(): ?array return [ 'owner' => $owner = $matches['owner'], 'repo' => $repo = $matches['repo'], - 'name' => $name = sprintf('%s/%s', $owner, $repo), + 'name' => $name = \sprintf('%s/%s', $owner, $repo), 'url' => 'https://github.com/'.$name, ]; } diff --git a/ux.symfony.com/src/Model/UxPackage.php b/ux.symfony.com/src/Model/UxPackage.php index 94d12af42b6..824983b45bd 100644 --- a/ux.symfony.com/src/Model/UxPackage.php +++ b/ux.symfony.com/src/Model/UxPackage.php @@ -119,7 +119,7 @@ public function getScreencastLinkText(): ?string public function getOfficialDocsUrl(): string { - return sprintf('https://symfony.com/bundles/ux-%s/current/index.html', $this->name); + return \sprintf('https://symfony.com/bundles/ux-%s/current/index.html', $this->name); } public function getCreateString(): string diff --git a/ux.symfony.com/src/Service/Changelog/ChangelogProvider.php b/ux.symfony.com/src/Service/Changelog/ChangelogProvider.php index 5174a9887ab..e609cde335c 100644 --- a/ux.symfony.com/src/Service/Changelog/ChangelogProvider.php +++ b/ux.symfony.com/src/Service/Changelog/ChangelogProvider.php @@ -53,7 +53,7 @@ private function getReleases(int $page = 1): array */ private function fetchReleases(string $owner, string $repo, int $page = 1, int $perPage = 20): array { - $response = $this->httpClient->request('GET', sprintf('https://api.github.com/repos/%s/%s/releases', $owner, $repo), [ + $response = $this->httpClient->request('GET', \sprintf('https://api.github.com/repos/%s/%s/releases', $owner, $repo), [ 'query' => [ 'page' => $page, 'per_page' => $perPage, diff --git a/ux.symfony.com/src/Service/Icon/IconSetRepository.php b/ux.symfony.com/src/Service/Icon/IconSetRepository.php index f0e85fa8b75..6629740e5c2 100644 --- a/ux.symfony.com/src/Service/Icon/IconSetRepository.php +++ b/ux.symfony.com/src/Service/Icon/IconSetRepository.php @@ -62,7 +62,7 @@ public function load(string $identifier): IconSet public function get(string $identifier): IconSet { - return $this->find($identifier) ?? throw new \InvalidArgumentException(sprintf('Unknown icon set "%s"', $identifier)); + return $this->find($identifier) ?? throw new \InvalidArgumentException(\sprintf('Unknown icon set "%s"', $identifier)); } public function find(string $identifier): ?IconSet diff --git a/ux.symfony.com/src/Service/LiveDemoRepository.php b/ux.symfony.com/src/Service/LiveDemoRepository.php index cddb4d52beb..df459b2d2c5 100644 --- a/ux.symfony.com/src/Service/LiveDemoRepository.php +++ b/ux.symfony.com/src/Service/LiveDemoRepository.php @@ -206,6 +206,6 @@ public function find(string $identifier): LiveDemo } } - throw new \InvalidArgumentException(sprintf('Unknown demo "%s"', $identifier)); + throw new \InvalidArgumentException(\sprintf('Unknown demo "%s"', $identifier)); } } diff --git a/ux.symfony.com/src/Service/UxPackageRepository.php b/ux.symfony.com/src/Service/UxPackageRepository.php index 6f703c8b189..9fefded98c4 100644 --- a/ux.symfony.com/src/Service/UxPackageRepository.php +++ b/ux.symfony.com/src/Service/UxPackageRepository.php @@ -239,7 +239,7 @@ public function find(string $name): UxPackage } } - throw new \InvalidArgumentException(sprintf('Unknown package "%s".', $name)); + throw new \InvalidArgumentException(\sprintf('Unknown package "%s".', $name)); } public function count(): int @@ -256,6 +256,6 @@ public function findByRoute(string $route): UxPackage } } - throw new \InvalidArgumentException(sprintf('Could not find a package for the current route "%s".', $route)); + throw new \InvalidArgumentException(\sprintf('Could not find a package for the current route "%s".', $route)); } } diff --git a/ux.symfony.com/src/Twig/Components/Code/CodeBlock.php b/ux.symfony.com/src/Twig/Components/Code/CodeBlock.php index e45909da2d4..3ecc2a48e63 100644 --- a/ux.symfony.com/src/Twig/Components/Code/CodeBlock.php +++ b/ux.symfony.com/src/Twig/Components/Code/CodeBlock.php @@ -53,17 +53,17 @@ public function mount(string $filename): void if (str_contains($filename, '#')) { [$filename, $lines] = explode('#', $filename, 2); if (str_contains($lines, '#')) { - throw new \InvalidArgumentException(sprintf('Invalid filename "%s": only one "#" is allowed.', $filename)); + throw new \InvalidArgumentException(\sprintf('Invalid filename "%s": only one "#" is allowed.', $filename)); } if (!preg_match('/^L(\d+)(?:-L(\d+))?$/', $lines, $matches)) { - throw new \InvalidArgumentException(sprintf('Invalid filename "%s": the line range is not valid.', $filename)); + throw new \InvalidArgumentException(\sprintf('Invalid filename "%s": the line range is not valid.', $filename)); } $lineStart = (int) $matches[1]; $lineEnd = (int) ($matches[2] ?? $matches[1]); if ($lineStart > $lineEnd) { - throw new \InvalidArgumentException(sprintf('Invalid filename "%s": the line range is not valid.', $filename)); + throw new \InvalidArgumentException(\sprintf('Invalid filename "%s": the line range is not valid.', $filename)); } $this->lineStart = $lineStart; @@ -97,7 +97,7 @@ public function getRawSource(): string { $path = $this->rootDir.'/'.$this->filename; if (!file_exists($path)) { - throw new \InvalidArgumentException(sprintf('File "%s" does not exist.', $path)); + throw new \InvalidArgumentException(\sprintf('File "%s" does not exist.', $path)); } $content = file_get_contents($path); @@ -129,13 +129,13 @@ public function getLineAnchor(): ?string return null; } - $anchor = sprintf('L%d', $this->lineStart); + $anchor = \sprintf('L%d', $this->lineStart); if (null === $this->lineEnd) { return $anchor; } if ($this->lineStart !== $this->lineEnd) { - $anchor .= sprintf('-L%d', $this->lineEnd); + $anchor .= \sprintf('-L%d', $this->lineEnd); } return $anchor; @@ -148,7 +148,7 @@ public function getClassString(): string public function getGithubLink(): string { - return sprintf('https://github.com/symfony/ux/blob/2.x/ux.symfony.com/%s', $this->filename); + return \sprintf('https://github.com/symfony/ux/blob/2.x/ux.symfony.com/%s', $this->filename); } public function getLanguage(): string diff --git a/ux.symfony.com/src/Twig/DinoChart.php b/ux.symfony.com/src/Twig/DinoChart.php index 8d7fd5d44ae..1c49e80c08b 100644 --- a/ux.symfony.com/src/Twig/DinoChart.php +++ b/ux.symfony.com/src/Twig/DinoChart.php @@ -54,7 +54,7 @@ public function getChart(): Chart 'plugins' => [ 'title' => [ 'display' => true, - 'text' => sprintf( + 'text' => \sprintf( 'Dinos species count from %dmya to %dmya', abs($this->fromYear), abs($this->toYear) diff --git a/ux.symfony.com/src/Twig/Icon.php b/ux.symfony.com/src/Twig/Icon.php index 2fd520fb36c..3fcf26f53ae 100644 --- a/ux.symfony.com/src/Twig/Icon.php +++ b/ux.symfony.com/src/Twig/Icon.php @@ -51,7 +51,7 @@ public function __construct( public function mount(string $name): void { if (!preg_match('/[A-Za-z0-9-]+/', $name)) { - throw new \InvalidArgumentException(sprintf('Icon name can only contain letters, digits or dashes, "%s" provided.', $this->name)); + throw new \InvalidArgumentException(\sprintf('Icon name can only contain letters, digits or dashes, "%s" provided.', $this->name)); } $this->name = $name; @@ -62,7 +62,7 @@ public function getRawSvg(): string { $path = $this->iconDirectory.'/'.$this->name.'.svg'; if (!file_exists($path)) { - throw new \InvalidArgumentException(sprintf('File "%s" does not exist.', $path)); + throw new \InvalidArgumentException(\sprintf('File "%s" does not exist.', $path)); } $svg = file_get_contents($path); diff --git a/ux.symfony.com/src/Util/SourceCleaner.php b/ux.symfony.com/src/Util/SourceCleaner.php index b44f95b5fb5..0b70cc794d0 100644 --- a/ux.symfony.com/src/Util/SourceCleaner.php +++ b/ux.symfony.com/src/Util/SourceCleaner.php @@ -59,7 +59,7 @@ public static function processTerminalLines(string $content): string // comment lines if (str_starts_with($line, '//')) { - return sprintf('%s', $line); + return \sprintf('%s', $line); } return '$ '.$line; @@ -71,7 +71,7 @@ public static function processTerminalLines(string $content): string public static function extractTwigBlock(string $content, string $targetTwigBlock, bool $showTwigExtends = true): string { $lines = explode("\n", $content); - $startBlock = sprintf('{%% block %s %%}', $targetTwigBlock); + $startBlock = \sprintf('{%% block %s %%}', $targetTwigBlock); $insideTargetBlock = false; $nestedBlockCount = 0; $blockLines = []; diff --git a/ux.symfony.com/tests/Functional/UxPackagesTest.php b/ux.symfony.com/tests/Functional/UxPackagesTest.php index 439cc914eda..f38af38a984 100644 --- a/ux.symfony.com/tests/Functional/UxPackagesTest.php +++ b/ux.symfony.com/tests/Functional/UxPackagesTest.php @@ -58,7 +58,7 @@ public static function getSmokeTests(): \Generator continue; } - yield $package->getName() => [$package, sprintf('%s Docs', $package->getHumanName())]; + yield $package->getName() => [$package, \sprintf('%s Docs', $package->getHumanName())]; } } }