From 6f4798de59470a8d5642b646f7aa6bef9bb7e836 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 19 May 2021 15:18:37 +0200 Subject: [PATCH 001/208] Bump Symfony 6 to PHP 8 --- composer.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/composer.json b/composer.json index b99e08620a..8a9d75ed93 100644 --- a/composer.json +++ b/composer.json @@ -16,14 +16,13 @@ } ], "require": { - "php": ">=7.2.5", + "php": ">=8.0.2", "symfony/deprecation-contracts": "^2.1", "symfony/event-dispatcher": "^4.4|^5.0", "symfony/options-resolver": "^5.1", "symfony/polyfill-ctype": "~1.8", "symfony/polyfill-intl-icu": "^1.21", "symfony/polyfill-mbstring": "~1.0", - "symfony/polyfill-php80": "^1.15", "symfony/property-access": "^5.0.8", "symfony/service-contracts": "^1.1|^2" }, From eb493be1a567e24d080d2d8baff46e75baa496d2 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 20 May 2021 14:59:02 +0200 Subject: [PATCH 002/208] Bump symfony/* deps to ^5.4|^6.0 --- composer.json | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/composer.json b/composer.json index e8d7517292..97fc8f0e7b 100644 --- a/composer.json +++ b/composer.json @@ -18,40 +18,40 @@ "require": { "php": ">=8.0.2", "symfony/deprecation-contracts": "^2.1", - "symfony/event-dispatcher": "^4.4|^5.0|^6.0", - "symfony/options-resolver": "^5.1|^6.0", + "symfony/event-dispatcher": "^5.4|^6.0", + "symfony/options-resolver": "^5.4|^6.0", "symfony/polyfill-ctype": "~1.8", "symfony/polyfill-intl-icu": "^1.21", "symfony/polyfill-mbstring": "~1.0", - "symfony/property-access": "^5.0.8|^6.0", + "symfony/property-access": "^5.4|^6.0", "symfony/service-contracts": "^1.1|^2" }, "require-dev": { "doctrine/collections": "~1.0", - "symfony/validator": "^4.4.17|^5.1.9|^6.0", - "symfony/dependency-injection": "^4.4|^5.0|^6.0", - "symfony/expression-language": "^4.4|^5.0|^6.0", - "symfony/config": "^4.4|^5.0|^6.0", - "symfony/console": "^4.4|^5.0|^6.0", - "symfony/http-foundation": "^4.4|^5.0|^6.0", - "symfony/http-kernel": "^4.4|^5.0|^6.0", - "symfony/intl": "^4.4|^5.0|^6.0", - "symfony/security-csrf": "^4.4|^5.0|^6.0", - "symfony/translation": "^4.4|^5.0|^6.0", - "symfony/var-dumper": "^4.4|^5.0|^6.0", - "symfony/uid": "^5.1|^6.0" + "symfony/validator": "^5.4|^6.0", + "symfony/dependency-injection": "^5.4|^6.0", + "symfony/expression-language": "^5.4|^6.0", + "symfony/config": "^5.4|^6.0", + "symfony/console": "^5.4|^6.0", + "symfony/http-foundation": "^5.4|^6.0", + "symfony/http-kernel": "^5.4|^6.0", + "symfony/intl": "^5.4|^6.0", + "symfony/security-csrf": "^5.4|^6.0", + "symfony/translation": "^5.4|^6.0", + "symfony/var-dumper": "^5.4|^6.0", + "symfony/uid": "^5.4|^6.0" }, "conflict": { "phpunit/phpunit": "<5.4.3", - "symfony/console": "<4.4", - "symfony/dependency-injection": "<4.4", - "symfony/doctrine-bridge": "<4.4", - "symfony/error-handler": "<4.4.5", - "symfony/framework-bundle": "<4.4", - "symfony/http-kernel": "<4.4", - "symfony/translation": "<4.4", + "symfony/console": "<5.4", + "symfony/dependency-injection": "<5.4", + "symfony/doctrine-bridge": "<5.4", + "symfony/error-handler": "<5.4", + "symfony/framework-bundle": "<5.4", + "symfony/http-kernel": "<5.4", + "symfony/translation": "<5.4", "symfony/translation-contracts": "<1.1.7", - "symfony/twig-bridge": "<4.4" + "symfony/twig-bridge": "<5.4" }, "suggest": { "symfony/validator": "For form validation.", From 9518c6b5208bbd252407befc3793cfd2208ba387 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Deruss=C3=A9?= Date: Wed, 19 May 2021 20:52:47 +0200 Subject: [PATCH 003/208] Remove constraint for PHP < 8 --- .../DateTimeImmutableToDateTimeTransformer.php | 6 +----- Tests/Extension/Core/DataMapper/DataMapperTest.php | 6 ------ Tests/Extension/Core/DataMapper/PropertyPathMapperTest.php | 6 ------ 3 files changed, 1 insertion(+), 17 deletions(-) diff --git a/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php b/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php index 6eb40af9d8..0ef9e22139 100644 --- a/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php @@ -38,11 +38,7 @@ public function transform($value): ?\DateTime throw new TransformationFailedException('Expected a \DateTimeImmutable.'); } - if (\PHP_VERSION_ID >= 70300) { - return \DateTime::createFromImmutable($value); - } - - return \DateTime::createFromFormat('U.u', $value->format('U.u'))->setTimezone($value->getTimezone()); + return \DateTime::createFromImmutable($value); } /** diff --git a/Tests/Extension/Core/DataMapper/DataMapperTest.php b/Tests/Extension/Core/DataMapper/DataMapperTest.php index bc6efb6d3b..b29cb3b5e8 100644 --- a/Tests/Extension/Core/DataMapper/DataMapperTest.php +++ b/Tests/Extension/Core/DataMapper/DataMapperTest.php @@ -106,9 +106,6 @@ public function testMapDataToFormsIgnoresUnmapped() self::assertNull($form->getData()); } - /** - * @requires PHP 7.4 - */ public function testMapDataToFormsIgnoresUninitializedProperties() { $engineForm = new Form(new FormConfigBuilder('engine', null, $this->dispatcher)); @@ -310,9 +307,6 @@ public function testMapFormsToDataIgnoresDisabled() self::assertSame($initialEngine, $car->engine); } - /** - * @requires PHP 7.4 - */ public function testMapFormsToUninitializedProperties() { $car = new TypehintedPropertiesCar(); diff --git a/Tests/Extension/Core/DataMapper/PropertyPathMapperTest.php b/Tests/Extension/Core/DataMapper/PropertyPathMapperTest.php index 780d9988fd..d29c86e4b7 100644 --- a/Tests/Extension/Core/DataMapper/PropertyPathMapperTest.php +++ b/Tests/Extension/Core/DataMapper/PropertyPathMapperTest.php @@ -117,9 +117,6 @@ public function testMapDataToFormsIgnoresUnmapped() $this->assertNull($form->getData()); } - /** - * @requires PHP 7.4 - */ public function testMapDataToFormsIgnoresUninitializedProperties() { $engineForm = new Form(new FormConfigBuilder('engine', null, $this->dispatcher)); @@ -321,9 +318,6 @@ public function testMapFormsToDataIgnoresDisabled() $this->assertSame($initialEngine, $car->engine); } - /** - * @requires PHP 7.4 - */ public function testMapFormsToUninitializedProperties() { $car = new TypehintedPropertiesCar(); From d1e00ceeca63de0ae4db50ee8077934dd8db5959 Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Thu, 20 May 2021 00:47:05 +0200 Subject: [PATCH 004/208] Remove Serializable implementations --- Tests/Fixtures/CustomArrayObject.php | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/Tests/Fixtures/CustomArrayObject.php b/Tests/Fixtures/CustomArrayObject.php index 5c12b6b400..d210377a5e 100644 --- a/Tests/Fixtures/CustomArrayObject.php +++ b/Tests/Fixtures/CustomArrayObject.php @@ -15,7 +15,7 @@ * This class is a hand written simplified version of PHP native `ArrayObject` * class, to show that it behaves differently than the PHP native implementation. */ -class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable, \Serializable +class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable { private $array; @@ -63,18 +63,8 @@ public function __serialize(): array return $this->array; } - public function serialize(): string - { - return serialize($this->__serialize()); - } - public function __unserialize(array $data): void { $this->array = $data; } - - public function unserialize($serialized) - { - $this->__unserialize((array) unserialize((string) $serialized)); - } } From 6beb513c6fe30ba6210d2dcf74fa336f2570066d Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 28 May 2021 17:52:26 +0200 Subject: [PATCH 005/208] Add return type to __toString() --- Extension/Validator/ViolationMapper/ViolationPath.php | 5 +---- FormErrorIterator.php | 4 +--- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Extension/Validator/ViolationMapper/ViolationPath.php b/Extension/Validator/ViolationMapper/ViolationPath.php index 6e318a62da..8481141691 100644 --- a/Extension/Validator/ViolationMapper/ViolationPath.php +++ b/Extension/Validator/ViolationMapper/ViolationPath.php @@ -112,10 +112,7 @@ public function __construct(string $violationPath) $this->buildString(); } - /** - * {@inheritdoc} - */ - public function __toString() + public function __toString(): string { return $this->pathAsString; } diff --git a/FormErrorIterator.php b/FormErrorIterator.php index ee350dd3e4..3943278ac3 100644 --- a/FormErrorIterator.php +++ b/FormErrorIterator.php @@ -58,10 +58,8 @@ public function __construct(FormInterface $form, array $errors) /** * Returns all iterated error messages as string. - * - * @return string The iterated error messages */ - public function __toString() + public function __toString(): string { $string = ''; From 58fd160d1038c30946a4a7491ac7b0fc2265f4b9 Mon Sep 17 00:00:00 2001 From: Yonel Ceruto Date: Thu, 20 May 2021 03:06:58 -0400 Subject: [PATCH 006/208] [Form] Remove deprecated code --- ButtonBuilder.php | 2 +- CHANGELOG.md | 14 + DependencyInjection/FormPass.php | 43 +-- .../Core/DataMapper/CheckboxListMapper.php | 12 +- Extension/Core/DataMapper/DataMapper.php | 12 +- .../Core/DataMapper/PropertyPathMapper.php | 113 ------ Extension/Core/DataMapper/RadioListMapper.php | 8 +- Extension/Core/Type/FormType.php | 7 - Extension/Validator/Util/ServerParams.php | 25 -- Form.php | 10 +- FormConfigBuilder.php | 2 +- FormConfigBuilderInterface.php | 10 +- FormConfigInterface.php | 7 +- .../DataMapper/PropertyPathMapperTest.php | 362 ------------------ .../Validator/Util/LegacyServerParamsTest.php | 31 -- 15 files changed, 48 insertions(+), 610 deletions(-) delete mode 100644 Extension/Core/DataMapper/PropertyPathMapper.php delete mode 100644 Extension/Validator/Util/ServerParams.php delete mode 100644 Tests/Extension/Core/DataMapper/PropertyPathMapperTest.php delete mode 100644 Tests/Extension/Validator/Util/LegacyServerParamsTest.php diff --git a/ButtonBuilder.php b/ButtonBuilder.php index 87adc69475..bf020baf53 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -471,7 +471,7 @@ public function getFormConfig() * * @throws BadMethodCallException */ - public function setIsEmptyCallback(?callable $isEmptyCallback) + public function setIsEmptyCallback(?callable $isEmptyCallback): static { throw new BadMethodCallException('Buttons do not support "is empty" callback.'); } diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a8dae4739..5b2c551b2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,20 @@ CHANGELOG ========= +6.0 +--- + + * Remove `PropertyPathMaper` + * Remove `Symfony\Component\Form\Extension\Validator\Util\ServiceParams` + * Remove `FormPass` configuration + * Add `FormConfigInterface::getIsEmptyCallback()` and `FormConfigBuilderInterface::setIsEmptyCallback()` + * Change `$forms` parameter type of the `DataMapper::mapDataToForms()` method from `iterable` to `\Traversable` + * Change `$forms` parameter type of the `DataMapper::mapFormsToData()` method from `iterable` to `\Traversable` + * Change `$checkboxes` parameter type of the `CheckboxListMapper::mapDataToForms()` method from `iterable` to `\Traversable` + * Change `$checkboxes` parameter type of the `CheckboxListMapper::mapFormsToData()` method from `iterable` to `\Traversable` + * Change `$radios` parameter type of the `RadioListMapper::mapDataToForms()` method from `iterable` to `\Traversable` + * Change `$radios` parameter type of the `RadioListMapper::mapFormsToData()` method from `iterable` to `\Traversable` + 5.3 --- diff --git a/DependencyInjection/FormPass.php b/DependencyInjection/FormPass.php index 0ba46117c5..cba1aeeb2c 100644 --- a/DependencyInjection/FormPass.php +++ b/DependencyInjection/FormPass.php @@ -30,32 +30,13 @@ class FormPass implements CompilerPassInterface { use PriorityTaggedServiceTrait; - private $formExtensionService; - private $formTypeTag; - private $formTypeExtensionTag; - private $formTypeGuesserTag; - private $formDebugCommandService; - - public function __construct(string $formExtensionService = 'form.extension', string $formTypeTag = 'form.type', string $formTypeExtensionTag = 'form.type_extension', string $formTypeGuesserTag = 'form.type_guesser', string $formDebugCommandService = 'console.command.form_debug') - { - if (0 < \func_num_args()) { - trigger_deprecation('symfony/http-kernel', '5.3', 'Configuring "%s" is deprecated.', __CLASS__); - } - - $this->formExtensionService = $formExtensionService; - $this->formTypeTag = $formTypeTag; - $this->formTypeExtensionTag = $formTypeExtensionTag; - $this->formTypeGuesserTag = $formTypeGuesserTag; - $this->formDebugCommandService = $formDebugCommandService; - } - public function process(ContainerBuilder $container) { - if (!$container->hasDefinition($this->formExtensionService)) { + if (!$container->hasDefinition('form.extension')) { return; } - $definition = $container->getDefinition($this->formExtensionService); + $definition = $container->getDefinition('form.extension'); $definition->replaceArgument(0, $this->processFormTypes($container)); $definition->replaceArgument(1, $this->processFormTypeExtensions($container)); $definition->replaceArgument(2, $this->processFormTypeGuessers($container)); @@ -68,15 +49,15 @@ private function processFormTypes(ContainerBuilder $container): Reference $namespaces = ['Symfony\Component\Form\Extension\Core\Type' => true]; // Builds an array with fully-qualified type class names as keys and service IDs as values - foreach ($container->findTaggedServiceIds($this->formTypeTag, true) as $serviceId => $tag) { + foreach ($container->findTaggedServiceIds('form.type', true) as $serviceId => $tag) { // Add form type service to the service locator $serviceDefinition = $container->getDefinition($serviceId); $servicesMap[$formType = $serviceDefinition->getClass()] = new Reference($serviceId); $namespaces[substr($formType, 0, strrpos($formType, '\\'))] = true; } - if ($container->hasDefinition($this->formDebugCommandService)) { - $commandDefinition = $container->getDefinition($this->formDebugCommandService); + if ($container->hasDefinition('console.command.form_debug')) { + $commandDefinition = $container->getDefinition('console.command.form_debug'); $commandDefinition->setArgument(1, array_keys($namespaces)); $commandDefinition->setArgument(2, array_keys($servicesMap)); } @@ -88,11 +69,11 @@ private function processFormTypeExtensions(ContainerBuilder $container): array { $typeExtensions = []; $typeExtensionsClasses = []; - foreach ($this->findAndSortTaggedServices($this->formTypeExtensionTag, $container) as $reference) { + foreach ($this->findAndSortTaggedServices('form.type_extension', $container) as $reference) { $serviceId = (string) $reference; $serviceDefinition = $container->getDefinition($serviceId); - $tag = $serviceDefinition->getTag($this->formTypeExtensionTag); + $tag = $serviceDefinition->getTag('form.type_extension'); $typeExtensionClass = $container->getParameterBag()->resolveValue($serviceDefinition->getClass()); if (isset($tag[0]['extended_type'])) { @@ -117,8 +98,8 @@ private function processFormTypeExtensions(ContainerBuilder $container): array $typeExtensions[$extendedType] = new IteratorArgument($extensions); } - if ($container->hasDefinition($this->formDebugCommandService)) { - $commandDefinition = $container->getDefinition($this->formDebugCommandService); + if ($container->hasDefinition('console.command.form_debug')) { + $commandDefinition = $container->getDefinition('console.command.form_debug'); $commandDefinition->setArgument(3, $typeExtensionsClasses); } @@ -129,15 +110,15 @@ private function processFormTypeGuessers(ContainerBuilder $container): ArgumentI { $guessers = []; $guessersClasses = []; - foreach ($container->findTaggedServiceIds($this->formTypeGuesserTag, true) as $serviceId => $tags) { + foreach ($container->findTaggedServiceIds('form.type_guesser', true) as $serviceId => $tags) { $guessers[] = new Reference($serviceId); $serviceDefinition = $container->getDefinition($serviceId); $guessersClasses[] = $serviceDefinition->getClass(); } - if ($container->hasDefinition($this->formDebugCommandService)) { - $commandDefinition = $container->getDefinition($this->formDebugCommandService); + if ($container->hasDefinition('console.command.form_debug')) { + $commandDefinition = $container->getDefinition('console.command.form_debug'); $commandDefinition->setArgument(4, $guessersClasses); } diff --git a/Extension/Core/DataMapper/CheckboxListMapper.php b/Extension/Core/DataMapper/CheckboxListMapper.php index ecfd83a066..a6014d7076 100644 --- a/Extension/Core/DataMapper/CheckboxListMapper.php +++ b/Extension/Core/DataMapper/CheckboxListMapper.php @@ -28,12 +28,8 @@ class CheckboxListMapper implements DataMapperInterface /** * {@inheritdoc} */ - public function mapDataToForms($choices, iterable $checkboxes) + public function mapDataToForms($choices, \Traversable $checkboxes) { - if (\is_array($checkboxes)) { - trigger_deprecation('symfony/form', '5.3', 'Passing an array as the second argument of the "%s()" method is deprecated, pass "\Traversable" instead.', __METHOD__); - } - if (null === $choices) { $choices = []; } @@ -51,12 +47,8 @@ public function mapDataToForms($choices, iterable $checkboxes) /** * {@inheritdoc} */ - public function mapFormsToData(iterable $checkboxes, &$choices) + public function mapFormsToData(\Traversable $checkboxes, &$choices) { - if (\is_array($checkboxes)) { - trigger_deprecation('symfony/form', '5.3', 'Passing an array as the first argument of the "%s()" method is deprecated, pass "\Traversable" instead.', __METHOD__); - } - if (!\is_array($choices)) { throw new UnexpectedTypeException($choices, 'array'); } diff --git a/Extension/Core/DataMapper/DataMapper.php b/Extension/Core/DataMapper/DataMapper.php index 5f4c498a33..1e98740d2e 100644 --- a/Extension/Core/DataMapper/DataMapper.php +++ b/Extension/Core/DataMapper/DataMapper.php @@ -38,12 +38,8 @@ public function __construct(DataAccessorInterface $dataAccessor = null) /** * {@inheritdoc} */ - public function mapDataToForms($data, iterable $forms): void + public function mapDataToForms($data, \Traversable $forms): void { - if (\is_array($forms)) { - trigger_deprecation('symfony/form', '5.3', 'Passing an array as the second argument of the "%s()" method is deprecated, pass "\Traversable" instead.', __METHOD__); - } - $empty = null === $data || [] === $data; if (!$empty && !\is_array($data) && !\is_object($data)) { @@ -64,12 +60,8 @@ public function mapDataToForms($data, iterable $forms): void /** * {@inheritdoc} */ - public function mapFormsToData(iterable $forms, &$data): void + public function mapFormsToData(\Traversable $forms, &$data): void { - if (\is_array($forms)) { - trigger_deprecation('symfony/form', '5.3', 'Passing an array as the first argument of the "%s()" method is deprecated, pass "\Traversable" instead.', __METHOD__); - } - if (null === $data) { return; } diff --git a/Extension/Core/DataMapper/PropertyPathMapper.php b/Extension/Core/DataMapper/PropertyPathMapper.php deleted file mode 100644 index 7dbc214ca6..0000000000 --- a/Extension/Core/DataMapper/PropertyPathMapper.php +++ /dev/null @@ -1,113 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Form\Extension\Core\DataMapper; - -use Symfony\Component\Form\DataMapperInterface; -use Symfony\Component\Form\Exception\UnexpectedTypeException; -use Symfony\Component\PropertyAccess\Exception\AccessException; -use Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException; -use Symfony\Component\PropertyAccess\PropertyAccess; -use Symfony\Component\PropertyAccess\PropertyAccessorInterface; - -trigger_deprecation('symfony/form', '5.2', 'The "%s" class is deprecated. Use "%s" instead.', PropertyPathMapper::class, DataMapper::class); - -/** - * Maps arrays/objects to/from forms using property paths. - * - * @author Bernhard Schussek - * - * @deprecated since symfony/form 5.2. Use {@see DataMapper} instead. - */ -class PropertyPathMapper implements DataMapperInterface -{ - private $propertyAccessor; - - public function __construct(PropertyAccessorInterface $propertyAccessor = null) - { - $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor(); - } - - /** - * {@inheritdoc} - */ - public function mapDataToForms($data, iterable $forms) - { - $empty = null === $data || [] === $data; - - if (!$empty && !\is_array($data) && !\is_object($data)) { - throw new UnexpectedTypeException($data, 'object, array or empty'); - } - - foreach ($forms as $form) { - $propertyPath = $form->getPropertyPath(); - $config = $form->getConfig(); - - if (!$empty && null !== $propertyPath && $config->getMapped()) { - $form->setData($this->getPropertyValue($data, $propertyPath)); - } else { - $form->setData($config->getData()); - } - } - } - - /** - * {@inheritdoc} - */ - public function mapFormsToData(iterable $forms, &$data) - { - if (null === $data) { - return; - } - - if (!\is_array($data) && !\is_object($data)) { - throw new UnexpectedTypeException($data, 'object, array or empty'); - } - - foreach ($forms as $form) { - $propertyPath = $form->getPropertyPath(); - $config = $form->getConfig(); - - // Write-back is disabled if the form is not synchronized (transformation failed), - // if the form was not submitted and if the form is disabled (modification not allowed) - if (null !== $propertyPath && $config->getMapped() && $form->isSubmitted() && $form->isSynchronized() && !$form->isDisabled()) { - $propertyValue = $form->getData(); - // If the field is of type DateTimeInterface and the data is the same skip the update to - // keep the original object hash - if ($propertyValue instanceof \DateTimeInterface && $propertyValue == $this->getPropertyValue($data, $propertyPath)) { - continue; - } - - // If the data is identical to the value in $data, we are - // dealing with a reference - if (!\is_object($data) || !$config->getByReference() || $propertyValue !== $this->getPropertyValue($data, $propertyPath)) { - $this->propertyAccessor->setValue($data, $propertyPath, $propertyValue); - } - } - } - } - - private function getPropertyValue($data, $propertyPath) - { - try { - return $this->propertyAccessor->getValue($data, $propertyPath); - } catch (AccessException $e) { - if (!$e instanceof UninitializedPropertyException - // For versions without UninitializedPropertyException check the exception message - && (class_exists(UninitializedPropertyException::class) || false === strpos($e->getMessage(), 'You should initialize it')) - ) { - throw $e; - } - - return null; - } - } -} diff --git a/Extension/Core/DataMapper/RadioListMapper.php b/Extension/Core/DataMapper/RadioListMapper.php index b54adfa5d1..16f02a5cab 100644 --- a/Extension/Core/DataMapper/RadioListMapper.php +++ b/Extension/Core/DataMapper/RadioListMapper.php @@ -28,7 +28,7 @@ class RadioListMapper implements DataMapperInterface /** * {@inheritdoc} */ - public function mapDataToForms($choice, iterable $radios) + public function mapDataToForms($choice, \Traversable $radios) { if (\is_array($radios)) { trigger_deprecation('symfony/form', '5.3', 'Passing an array as the second argument of the "%s()" method is deprecated, pass "\Traversable" instead.', __METHOD__); @@ -47,12 +47,8 @@ public function mapDataToForms($choice, iterable $radios) /** * {@inheritdoc} */ - public function mapFormsToData(iterable $radios, &$choice) + public function mapFormsToData(\Traversable $radios, &$choice) { - if (\is_array($radios)) { - trigger_deprecation('symfony/form', '5.3', 'Passing an array as the first argument of the "%s()" method is deprecated, pass "\Traversable" instead.', __METHOD__); - } - if (null !== $choice && !\is_string($choice)) { throw new UnexpectedTypeException($choice, 'null or string'); } diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index 7fa7b60fc1..c7973980b1 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -18,7 +18,6 @@ use Symfony\Component\Form\Extension\Core\DataMapper\DataMapper; use Symfony\Component\Form\Extension\Core\EventListener\TrimListener; use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\Form\FormConfigBuilderInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; use Symfony\Component\OptionsResolver\Options; @@ -66,12 +65,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) $builder->addEventSubscriber(new TrimListener()); } - if (!method_exists($builder, 'setIsEmptyCallback')) { - trigger_deprecation('symfony/form', '5.1', 'Not implementing the "%s::setIsEmptyCallback()" method in "%s" is deprecated.', FormConfigBuilderInterface::class, get_debug_type($builder)); - - return; - } - $builder->setIsEmptyCallback($options['is_empty_callback']); } diff --git a/Extension/Validator/Util/ServerParams.php b/Extension/Validator/Util/ServerParams.php deleted file mode 100644 index 98e9f0c98a..0000000000 --- a/Extension/Validator/Util/ServerParams.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Form\Extension\Validator\Util; - -use Symfony\Component\Form\Util\ServerParams as BaseServerParams; - -trigger_deprecation('symfony/form', '5.1', 'The "%s" class is deprecated. Use "%s" instead.', ServerParams::class, BaseServerParams::class); - -/** - * @author Bernhard Schussek - * - * @deprecated since Symfony 5.1. Use {@see BaseServerParams} instead. - */ -class ServerParams extends BaseServerParams -{ -} diff --git a/Form.php b/Form.php index 1901524562..82bd8a660b 100644 --- a/Form.php +++ b/Form.php @@ -724,15 +724,7 @@ public function isEmpty() } } - if (!method_exists($this->config, 'getIsEmptyCallback')) { - trigger_deprecation('symfony/form', '5.1', 'Not implementing the "%s::getIsEmptyCallback()" method in "%s" is deprecated.', FormConfigInterface::class, \get_class($this->config)); - - $isEmptyCallback = null; - } else { - $isEmptyCallback = $this->config->getIsEmptyCallback(); - } - - if (null !== $isEmptyCallback) { + if (null !== $isEmptyCallback = $this->config->getIsEmptyCallback()) { return $isEmptyCallback($this->modelData); } diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 7e7b40edac..69acee4d99 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -773,7 +773,7 @@ public function getFormConfig() /** * {@inheritdoc} */ - public function setIsEmptyCallback(?callable $isEmptyCallback) + public function setIsEmptyCallback(?callable $isEmptyCallback): static { $this->isEmptyCallback = $isEmptyCallback; diff --git a/FormConfigBuilderInterface.php b/FormConfigBuilderInterface.php index d9064c1434..fb4a835ba6 100644 --- a/FormConfigBuilderInterface.php +++ b/FormConfigBuilderInterface.php @@ -16,8 +16,6 @@ /** * @author Bernhard Schussek - * - * @method $this setIsEmptyCallback(callable|null $isEmptyCallback) Sets the callback that will be called to determine if the model data of the form is empty or not - not implementing it is deprecated since Symfony 5.1 */ interface FormConfigBuilderInterface extends FormConfigInterface { @@ -251,4 +249,12 @@ public function setAutoInitialize(bool $initialize); * @return FormConfigInterface */ public function getFormConfig(); + + /** + * Sets the callback that will be called to determine if the model + * data of the form is empty or not. + * + * @return $this + */ + public function setIsEmptyCallback(?callable $isEmptyCallback): static; } diff --git a/FormConfigInterface.php b/FormConfigInterface.php index e76986c4fb..c73eb5d74a 100644 --- a/FormConfigInterface.php +++ b/FormConfigInterface.php @@ -18,8 +18,6 @@ * The configuration of a {@link Form} object. * * @author Bernhard Schussek - * - * @method callable|null getIsEmptyCallback() Returns a callable that takes the model data as argument and that returns if it is empty or not - not implementing it is deprecated since Symfony 5.1 */ interface FormConfigInterface { @@ -247,4 +245,9 @@ public function hasOption(string $name); * @return mixed The option value */ public function getOption(string $name, $default = null); + + /** + * Returns a callable that takes the model data as argument and that returns if it is empty or not. + */ + public function getIsEmptyCallback(): ?callable; } diff --git a/Tests/Extension/Core/DataMapper/PropertyPathMapperTest.php b/Tests/Extension/Core/DataMapper/PropertyPathMapperTest.php deleted file mode 100644 index d29c86e4b7..0000000000 --- a/Tests/Extension/Core/DataMapper/PropertyPathMapperTest.php +++ /dev/null @@ -1,362 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Form\Tests\Extension\Core\DataMapper; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\EventDispatcher\EventDispatcher; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper; -use Symfony\Component\Form\Form; -use Symfony\Component\Form\FormConfigBuilder; -use Symfony\Component\Form\Tests\Fixtures\TypehintedPropertiesCar; -use Symfony\Component\PropertyAccess\PropertyAccess; -use Symfony\Component\PropertyAccess\PropertyAccessorInterface; -use Symfony\Component\PropertyAccess\PropertyPath; - -/** - * @group legacy - */ -class PropertyPathMapperTest extends TestCase -{ - /** - * @var PropertyPathMapper - */ - private $mapper; - - /** - * @var EventDispatcherInterface - */ - private $dispatcher; - - /** - * @var PropertyAccessorInterface - */ - private $propertyAccessor; - - protected function setUp(): void - { - $this->dispatcher = new EventDispatcher(); - $this->propertyAccessor = PropertyAccess::createPropertyAccessor(); - $this->mapper = new PropertyPathMapper($this->propertyAccessor); - } - - public function testMapDataToFormsPassesObjectRefIfByReference() - { - $car = new \stdClass(); - $engine = new \stdClass(); - $car->engine = $engine; - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(true); - $config->setPropertyPath($propertyPath); - $form = new Form($config); - - $this->mapper->mapDataToForms($car, [$form]); - - $this->assertSame($engine, $form->getData()); - } - - public function testMapDataToFormsPassesObjectCloneIfNotByReference() - { - $car = new \stdClass(); - $engine = new \stdClass(); - $engine->brand = 'Rolls-Royce'; - $car->engine = $engine; - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(false); - $config->setPropertyPath($propertyPath); - $form = new Form($config); - - $this->mapper->mapDataToForms($car, [$form]); - - $this->assertNotSame($engine, $form->getData()); - $this->assertEquals($engine, $form->getData()); - } - - public function testMapDataToFormsIgnoresEmptyPropertyPath() - { - $car = new \stdClass(); - - $config = new FormConfigBuilder(null, '\stdClass', $this->dispatcher); - $config->setByReference(true); - $form = new Form($config); - - $this->assertNull($form->getPropertyPath()); - - $this->mapper->mapDataToForms($car, [$form]); - - $this->assertNull($form->getData()); - } - - public function testMapDataToFormsIgnoresUnmapped() - { - $car = new \stdClass(); - $car->engine = new \stdClass(); - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(true); - $config->setMapped(false); - $config->setPropertyPath($propertyPath); - $form = new Form($config); - - $this->mapper->mapDataToForms($car, [$form]); - - $this->assertNull($form->getData()); - } - - public function testMapDataToFormsIgnoresUninitializedProperties() - { - $engineForm = new Form(new FormConfigBuilder('engine', null, $this->dispatcher)); - $colorForm = new Form(new FormConfigBuilder('color', null, $this->dispatcher)); - - $car = new TypehintedPropertiesCar(); - $car->engine = 'BMW'; - - $this->mapper->mapDataToForms($car, [$engineForm, $colorForm]); - - $this->assertSame($car->engine, $engineForm->getData()); - $this->assertNull($colorForm->getData()); - } - - public function testMapDataToFormsSetsDefaultDataIfPassedDataIsNull() - { - $default = new \stdClass(); - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(true); - $config->setPropertyPath($propertyPath); - $config->setData($default); - - $form = new Form($config); - - $this->mapper->mapDataToForms(null, [$form]); - - $this->assertSame($default, $form->getData()); - } - - public function testMapDataToFormsSetsDefaultDataIfPassedDataIsEmptyArray() - { - $default = new \stdClass(); - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(true); - $config->setPropertyPath($propertyPath); - $config->setData($default); - - $form = new Form($config); - - $this->mapper->mapDataToForms([], [$form]); - - $this->assertSame($default, $form->getData()); - } - - public function testMapFormsToDataWritesBackIfNotByReference() - { - $car = new \stdClass(); - $car->engine = new \stdClass(); - $engine = new \stdClass(); - $engine->brand = 'Rolls-Royce'; - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(false); - $config->setPropertyPath($propertyPath); - $config->setData($engine); - $form = new SubmittedForm($config); - - $this->mapper->mapFormsToData([$form], $car); - - $this->assertEquals($engine, $car->engine); - $this->assertNotSame($engine, $car->engine); - } - - public function testMapFormsToDataWritesBackIfByReferenceButNoReference() - { - $car = new \stdClass(); - $car->engine = new \stdClass(); - $engine = new \stdClass(); - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(true); - $config->setPropertyPath($propertyPath); - $config->setData($engine); - $form = new SubmittedForm($config); - - $this->mapper->mapFormsToData([$form], $car); - - $this->assertSame($engine, $car->engine); - } - - public function testMapFormsToDataWritesBackIfByReferenceAndReference() - { - $car = new \stdClass(); - $car->engine = 'BMW'; - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('engine', null, $this->dispatcher); - $config->setByReference(true); - $config->setPropertyPath($propertyPath); - $config->setData('Rolls-Royce'); - $form = new SubmittedForm($config); - - $car->engine = 'Rolls-Royce'; - - $this->mapper->mapFormsToData([$form], $car); - - $this->assertSame('Rolls-Royce', $car->engine); - } - - public function testMapFormsToDataIgnoresUnmapped() - { - $initialEngine = new \stdClass(); - $car = new \stdClass(); - $car->engine = $initialEngine; - $engine = new \stdClass(); - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(true); - $config->setPropertyPath($propertyPath); - $config->setData($engine); - $config->setMapped(false); - $form = new SubmittedForm($config); - - $this->mapper->mapFormsToData([$form], $car); - - $this->assertSame($initialEngine, $car->engine); - } - - public function testMapFormsToDataIgnoresUnsubmittedForms() - { - $initialEngine = new \stdClass(); - $car = new \stdClass(); - $car->engine = $initialEngine; - $engine = new \stdClass(); - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(true); - $config->setPropertyPath($propertyPath); - $config->setData($engine); - $form = new Form($config); - - $this->mapper->mapFormsToData([$form], $car); - - $this->assertSame($initialEngine, $car->engine); - } - - public function testMapFormsToDataIgnoresEmptyData() - { - $initialEngine = new \stdClass(); - $car = new \stdClass(); - $car->engine = $initialEngine; - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(true); - $config->setPropertyPath($propertyPath); - $config->setData(null); - $form = new Form($config); - - $this->mapper->mapFormsToData([$form], $car); - - $this->assertSame($initialEngine, $car->engine); - } - - public function testMapFormsToDataIgnoresUnsynchronized() - { - $initialEngine = new \stdClass(); - $car = new \stdClass(); - $car->engine = $initialEngine; - $engine = new \stdClass(); - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(true); - $config->setPropertyPath($propertyPath); - $config->setData($engine); - $form = new NotSynchronizedForm($config); - - $this->mapper->mapFormsToData([$form], $car); - - $this->assertSame($initialEngine, $car->engine); - } - - public function testMapFormsToDataIgnoresDisabled() - { - $initialEngine = new \stdClass(); - $car = new \stdClass(); - $car->engine = $initialEngine; - $engine = new \stdClass(); - $propertyPath = new PropertyPath('engine'); - - $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher); - $config->setByReference(true); - $config->setPropertyPath($propertyPath); - $config->setData($engine); - $config->setDisabled(true); - $form = new SubmittedForm($config); - - $this->mapper->mapFormsToData([$form], $car); - - $this->assertSame($initialEngine, $car->engine); - } - - public function testMapFormsToUninitializedProperties() - { - $car = new TypehintedPropertiesCar(); - $config = new FormConfigBuilder('engine', null, $this->dispatcher); - $config->setData('BMW'); - $form = new SubmittedForm($config); - - $this->mapper->mapFormsToData([$form], $car); - - $this->assertSame('BMW', $car->engine); - } - - /** - * @dataProvider provideDate - */ - public function testMapFormsToDataDoesNotChangeEqualDateTimeInstance($date) - { - $article = []; - $publishedAt = $date; - $publishedAtValue = clone $publishedAt; - $article['publishedAt'] = $publishedAtValue; - $propertyPath = new PropertyPath('[publishedAt]'); - - $config = new FormConfigBuilder('publishedAt', \get_class($publishedAt), $this->dispatcher); - $config->setByReference(false); - $config->setPropertyPath($propertyPath); - $config->setData($publishedAt); - $form = new SubmittedForm($config); - - $this->mapper->mapFormsToData([$form], $article); - - $this->assertSame($publishedAtValue, $article['publishedAt']); - } - - public function provideDate() - { - return [ - [new \DateTime()], - [new \DateTimeImmutable()], - ]; - } -} diff --git a/Tests/Extension/Validator/Util/LegacyServerParamsTest.php b/Tests/Extension/Validator/Util/LegacyServerParamsTest.php deleted file mode 100644 index 8b0b0d7ecf..0000000000 --- a/Tests/Extension/Validator/Util/LegacyServerParamsTest.php +++ /dev/null @@ -1,31 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Form\Tests\Extension\Validator\Util; - -use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; -use Symfony\Component\Form\Extension\Validator\Util\ServerParams; - -class LegacyServerParamsTest extends TestCase -{ - use ExpectDeprecationTrait; - - /** - * @group legacy - */ - public function testClassIsDeprecated() - { - $this->expectDeprecation('Since symfony/form 5.1: The "Symfony\Component\Form\Extension\Validator\Util\ServerParams" class is deprecated. Use "Symfony\Component\Form\Util\ServerParams" instead.'); - - new ServerParams(); - } -} From 105a2be4b4ef627e50a6e7c3906ef34167c453d5 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 2 Jun 2021 18:09:43 +0200 Subject: [PATCH 007/208] Update phpunit.xml.dist files for phpunit >= 9.3 --- phpunit.xml.dist | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index ede79e207d..148f8f58dd 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,7 +1,7 @@ - - + + ./ - - ./Resources - ./Tests - ./vendor - - - + + + ./Resources + ./Tests + ./vendor + + From 45b35b109854cfcc5eb8b44d0147b26e4786563f Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Mon, 14 Jun 2021 09:32:03 +0200 Subject: [PATCH 008/208] remove deprecated constants --- CHANGELOG.md | 1 + .../NumberToLocalizedStringTransformer.php | 35 ------------------- 2 files changed, 1 insertion(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b2c551b2b..59a1810180 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ CHANGELOG * Remove `PropertyPathMaper` * Remove `Symfony\Component\Form\Extension\Validator\Util\ServiceParams` * Remove `FormPass` configuration + * Remove the `NumberToLocalizedStringTransformer::ROUND_*` constants, use `\NumberFormatter::ROUND_*` instead * Add `FormConfigInterface::getIsEmptyCallback()` and `FormConfigBuilderInterface::setIsEmptyCallback()` * Change `$forms` parameter type of the `DataMapper::mapDataToForms()` method from `iterable` to `\Traversable` * Change `$forms` parameter type of the `DataMapper::mapFormsToData()` method from `iterable` to `\Traversable` diff --git a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index 20d7cf4ebb..cbf1da1618 100644 --- a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -23,41 +23,6 @@ */ class NumberToLocalizedStringTransformer implements DataTransformerInterface { - /** - * @deprecated since Symfony 5.1, use \NumberFormatter::ROUND_CEILING instead. - */ - public const ROUND_CEILING = \NumberFormatter::ROUND_CEILING; - - /** - * @deprecated since Symfony 5.1, use \NumberFormatter::ROUND_FLOOR instead. - */ - public const ROUND_FLOOR = \NumberFormatter::ROUND_FLOOR; - - /** - * @deprecated since Symfony 5.1, use \NumberFormatter::ROUND_UP instead. - */ - public const ROUND_UP = \NumberFormatter::ROUND_UP; - - /** - * @deprecated since Symfony 5.1, use \NumberFormatter::ROUND_DOWN instead. - */ - public const ROUND_DOWN = \NumberFormatter::ROUND_DOWN; - - /** - * @deprecated since Symfony 5.1, use \NumberFormatter::ROUND_HALFEVEN instead. - */ - public const ROUND_HALF_EVEN = \NumberFormatter::ROUND_HALFEVEN; - - /** - * @deprecated since Symfony 5.1, use \NumberFormatter::ROUND_HALFUP instead. - */ - public const ROUND_HALF_UP = \NumberFormatter::ROUND_HALFUP; - - /** - * @deprecated since Symfony 5.1, use \NumberFormatter::ROUND_HALFDOWN instead. - */ - public const ROUND_HALF_DOWN = \NumberFormatter::ROUND_HALFDOWN; - protected $grouping; protected $roundingMode; From 65f52d6ca8cf3a54cc296dec76921f88e24b2635 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Fri, 18 Jun 2021 11:38:37 +0200 Subject: [PATCH 009/208] remove remaining deprecation layers --- .../Factory/CachingFactoryDecorator.php | 11 +++----- .../Factory/ChoiceListFactoryInterface.php | 6 ++--- .../Factory/DefaultChoiceListFactory.php | 15 +++-------- .../Factory/PropertyAccessDecorator.php | 11 +++----- Extension/Core/DataMapper/RadioListMapper.php | 4 --- .../PercentToLocalizedStringTransformer.php | 14 ++++------ Extension/Core/Type/BirthdayType.php | 7 +---- Extension/Core/Type/CheckboxType.php | 7 +---- Extension/Core/Type/ChoiceType.php | 26 ++----------------- Extension/Core/Type/CollectionType.php | 6 +---- Extension/Core/Type/ColorType.php | 7 +---- Extension/Core/Type/CountryType.php | 6 +---- Extension/Core/Type/CurrencyType.php | 6 +---- Extension/Core/Type/DateIntervalType.php | 6 +---- Extension/Core/Type/DateTimeType.php | 6 +---- Extension/Core/Type/DateType.php | 6 +---- Extension/Core/Type/EmailType.php | 7 +---- Extension/Core/Type/FileType.php | 6 +---- Extension/Core/Type/HiddenType.php | 7 +---- Extension/Core/Type/IntegerType.php | 7 +---- Extension/Core/Type/LanguageType.php | 6 +---- Extension/Core/Type/LocaleType.php | 6 +---- Extension/Core/Type/MoneyType.php | 6 +---- Extension/Core/Type/NumberType.php | 6 +---- Extension/Core/Type/PasswordType.php | 7 +---- Extension/Core/Type/PercentType.php | 21 ++------------- Extension/Core/Type/RadioType.php | 7 +---- Extension/Core/Type/RangeType.php | 7 +---- Extension/Core/Type/RepeatedType.php | 7 +---- Extension/Core/Type/SearchType.php | 7 +---- Extension/Core/Type/TelType.php | 6 +---- Extension/Core/Type/TimeType.php | 6 +---- Extension/Core/Type/TimezoneType.php | 6 +---- Extension/Core/Type/UlidType.php | 6 +---- Extension/Core/Type/UrlType.php | 6 +---- Extension/Core/Type/UuidType.php | 6 +---- Extension/Core/Type/WeekType.php | 4 +-- .../Type/FormTypeValidatorExtension.php | 7 ----- Tests/Command/DebugCommandTest.php | 5 ---- ...ercentToLocalizedStringTransformerTest.php | 9 ++----- Tests/Extension/Core/Type/ChoiceTypeTest.php | 14 ---------- Tests/Extension/Core/Type/PercentTypeTest.php | 24 +---------------- .../FormValidatorFunctionalTest.php | 4 +-- .../BirthdayTypeValidatorExtensionTest.php | 14 ---------- .../CheckboxTypeValidatorExtensionTest.php | 14 ---------- .../Type/ChoiceTypeValidatorExtensionTest.php | 14 ---------- .../CollectionTypeValidatorExtensionTest.php | 14 ---------- .../Type/ColorTypeValidatorExtensionTest.php | 14 ---------- .../CountryTypeValidatorExtensionTest.php | 14 ---------- .../CurrencyTypeValidatorExtensionTest.php | 14 ---------- ...DateIntervalTypeValidatorExtensionTest.php | 14 ---------- .../DateTimeTypeValidatorExtensionTest.php | 14 ---------- .../Type/DateTypeValidatorExtensionTest.php | 14 ---------- .../Type/EmailTypeValidatorExtensionTest.php | 14 ---------- .../Type/FileTypeValidatorExtensionTest.php | 14 ---------- .../Type/FormTypeValidatorExtensionTest.php | 12 --------- .../Type/HiddenTypeValidatorExtensionTest.php | 14 ---------- .../IntegerTypeValidatorExtensionTest.php | 14 ---------- .../LanguageTypeValidatorExtensionTest.php | 14 ---------- .../Type/LocaleTypeValidatorExtensionTest.php | 14 ---------- .../Type/MoneyTypeValidatorExtensionTest.php | 14 ---------- .../Type/NumberTypeValidatorExtensionTest.php | 14 ---------- .../PasswordTypeValidatorExtensionTest.php | 14 ---------- .../PercentTypeValidatorExtensionTest.php | 14 ---------- .../Type/RadioTypeValidatorExtensionTest.php | 14 ---------- .../Type/RangeTypeValidatorExtensionTest.php | 14 ---------- .../RepeatedTypeValidatorExtensionTest.php | 14 ---------- .../Type/SearchTypeValidatorExtensionTest.php | 14 ---------- .../Type/TelTypeValidatorExtensionTest.php | 14 ---------- .../Type/TimeTypeValidatorExtensionTest.php | 14 ---------- .../TimezoneTypeValidatorExtensionTest.php | 14 ---------- .../Type/UrlTypeValidatorExtensionTest.php | 14 ---------- .../DeprecatedChoiceListFactory.php | 22 ---------------- 73 files changed, 55 insertions(+), 725 deletions(-) delete mode 100644 Tests/Fixtures/ChoiceList/DeprecatedChoiceListFactory.php diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index c376f1a2d1..746a1ad064 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -89,10 +89,8 @@ public function getDecoratedFactory() * @param callable|Cache\ChoiceFilter|null $filter The callable or static option for * filtering the choices */ - public function createListFromChoices(iterable $choices, $value = null/*, $filter = null*/) + public function createListFromChoices(iterable $choices, $value = null, $filter = null) { - $filter = \func_num_args() > 2 ? func_get_arg(2) : null; - if ($choices instanceof \Traversable) { $choices = iterator_to_array($choices); } @@ -134,10 +132,8 @@ public function createListFromChoices(iterable $choices, $value = null/*, $filte * @param callable|Cache\ChoiceFilter|null $filter The callable or static option for * filtering the choices */ - public function createListFromLoader(ChoiceLoaderInterface $loader, $value = null/*, $filter = null*/) + public function createListFromLoader(ChoiceLoaderInterface $loader, $value = null, $filter = null) { - $filter = \func_num_args() > 2 ? func_get_arg(2) : null; - $cache = true; if ($loader instanceof Cache\ChoiceLoader) { @@ -181,9 +177,8 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, $value = nul * @param array|callable|Cache\ChoiceAttr|null $attr The option or static option generating the HTML attributes * @param array|callable|Cache\ChoiceTranslationParameters $labelTranslationParameters The parameters used to translate the choice labels */ - public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, $index = null, $groupBy = null, $attr = null/*, $labelTranslationParameters = []*/) + public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, $index = null, $groupBy = null, $attr = null, $labelTranslationParameters = []) { - $labelTranslationParameters = \func_num_args() > 6 ? func_get_arg(6) : []; $cache = true; if ($preferredChoices instanceof Cache\PreferredChoice) { diff --git a/ChoiceList/Factory/ChoiceListFactoryInterface.php b/ChoiceList/Factory/ChoiceListFactoryInterface.php index 6834009190..311d552616 100644 --- a/ChoiceList/Factory/ChoiceListFactoryInterface.php +++ b/ChoiceList/Factory/ChoiceListFactoryInterface.php @@ -35,7 +35,7 @@ interface ChoiceListFactoryInterface * * @return ChoiceListInterface The choice list */ - public function createListFromChoices(iterable $choices, callable $value = null/*, callable $filter = null*/); + public function createListFromChoices(iterable $choices, callable $value = null, callable $filter = null); /** * Creates a choice list that is loaded with the given loader. @@ -48,7 +48,7 @@ public function createListFromChoices(iterable $choices, callable $value = null/ * * @return ChoiceListInterface The choice list */ - public function createListFromLoader(ChoiceLoaderInterface $loader, callable $value = null/*, callable $filter = null*/); + public function createListFromLoader(ChoiceLoaderInterface $loader, callable $value = null, callable $filter = null); /** * Creates a view for the given choice list. @@ -84,5 +84,5 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $va * * @return ChoiceListView The choice list view */ - public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, callable $index = null, callable $groupBy = null, $attr = null/*, $labelTranslationParameters = []*/); + public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, callable $index = null, callable $groupBy = null, $attr = null, $labelTranslationParameters = []); } diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index c4aa752611..8d5e650c59 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -32,13 +32,9 @@ class DefaultChoiceListFactory implements ChoiceListFactoryInterface { /** * {@inheritdoc} - * - * @param callable|null $filter */ - public function createListFromChoices(iterable $choices, callable $value = null/*, callable $filter = null*/) + public function createListFromChoices(iterable $choices, callable $value = null, callable $filter = null) { - $filter = \func_num_args() > 2 ? func_get_arg(2) : null; - if ($filter) { // filter the choice list lazily return $this->createListFromLoader(new FilterChoiceLoaderDecorator( @@ -53,13 +49,9 @@ public function createListFromChoices(iterable $choices, callable $value = null/ /** * {@inheritdoc} - * - * @param callable|null $filter */ - public function createListFromLoader(ChoiceLoaderInterface $loader, callable $value = null/*, callable $filter = null*/) + public function createListFromLoader(ChoiceLoaderInterface $loader, callable $value = null, callable $filter = null) { - $filter = \func_num_args() > 2 ? func_get_arg(2) : null; - if ($filter) { $loader = new FilterChoiceLoaderDecorator($loader, $filter); } @@ -72,9 +64,8 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $va * * @param array|callable $labelTranslationParameters The parameters used to translate the choice labels */ - public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, callable $index = null, callable $groupBy = null, $attr = null/*, $labelTranslationParameters = []*/) + public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, callable $index = null, callable $groupBy = null, $attr = null, $labelTranslationParameters = []) { - $labelTranslationParameters = \func_num_args() > 6 ? func_get_arg(6) : []; $preferredViews = []; $preferredViewsOrder = []; $otherViews = []; diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index 6d323fbb08..492074286f 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -66,10 +66,8 @@ public function getDecoratedFactory() * * @return ChoiceListInterface The choice list */ - public function createListFromChoices(iterable $choices, $value = null/*, $filter = null*/) + public function createListFromChoices(iterable $choices, $value = null, $filter = null) { - $filter = \func_num_args() > 2 ? func_get_arg(2) : null; - if (\is_string($value)) { $value = new PropertyPath($value); } @@ -109,10 +107,8 @@ public function createListFromChoices(iterable $choices, $value = null/*, $filte * * @return ChoiceListInterface The choice list */ - public function createListFromLoader(ChoiceLoaderInterface $loader, $value = null/*, $filter = null*/) + public function createListFromLoader(ChoiceLoaderInterface $loader, $value = null, $filter = null) { - $filter = \func_num_args() > 2 ? func_get_arg(2) : null; - if (\is_string($value)) { $value = new PropertyPath($value); } @@ -154,9 +150,8 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, $value = nul * * @return ChoiceListView The choice list view */ - public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, $index = null, $groupBy = null, $attr = null/*, $labelTranslationParameters = []*/) + public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, $index = null, $groupBy = null, $attr = null, $labelTranslationParameters = []) { - $labelTranslationParameters = \func_num_args() > 6 ? func_get_arg(6) : []; $accessor = $this->propertyAccessor; if (\is_string($label)) { diff --git a/Extension/Core/DataMapper/RadioListMapper.php b/Extension/Core/DataMapper/RadioListMapper.php index 16f02a5cab..11f54a9cd2 100644 --- a/Extension/Core/DataMapper/RadioListMapper.php +++ b/Extension/Core/DataMapper/RadioListMapper.php @@ -30,10 +30,6 @@ class RadioListMapper implements DataMapperInterface */ public function mapDataToForms($choice, \Traversable $radios) { - if (\is_array($radios)) { - trigger_deprecation('symfony/form', '5.3', 'Passing an array as the second argument of the "%s()" method is deprecated, pass "\Traversable" instead.', __METHOD__); - } - if (!\is_string($choice)) { throw new UnexpectedTypeException($choice, 'string'); } diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index 0ee621be23..92ef2e299b 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -39,14 +39,14 @@ class PercentToLocalizedStringTransformer implements DataTransformerInterface /** * @see self::$types for a list of supported types * - * @param int $scale The scale - * @param string $type One of the supported types - * @param int|null $roundingMode A value from \NumberFormatter, such as \NumberFormatter::ROUND_HALFUP - * @param bool $html5Format Use an HTML5 specific format, see https://www.w3.org/TR/html51/sec-forms.html#date-time-and-number-formats + * @param int $scale The scale + * @param string $type One of the supported types + * @param int $roundingMode A value from \NumberFormatter, such as \NumberFormatter::ROUND_HALFUP + * @param bool $html5Format Use an HTML5 specific format, see https://www.w3.org/TR/html51/sec-forms.html#date-time-and-number-formats * * @throws UnexpectedTypeException if the given value of type is unknown */ - public function __construct(int $scale = null, string $type = null, ?int $roundingMode = null, bool $html5Format = false) + public function __construct(int $scale = null, string $type = null, int $roundingMode = \NumberFormatter::ROUND_HALFUP, bool $html5Format = false) { if (null === $scale) { $scale = 0; @@ -56,10 +56,6 @@ public function __construct(int $scale = null, string $type = null, ?int $roundi $type = self::FRACTIONAL; } - if (null === $roundingMode && (\func_num_args() < 4 || func_get_arg(3))) { - trigger_deprecation('symfony/form', '5.1', 'Not passing a rounding mode to "%s()" is deprecated. Starting with Symfony 6.0 it will default to "\NumberFormatter::ROUND_HALFUP".', __METHOD__); - } - if (!\in_array($type, self::$types, true)) { throw new UnexpectedTypeException($type, implode('", "', self::$types)); } diff --git a/Extension/Core/Type/BirthdayType.php b/Extension/Core/Type/BirthdayType.php index 50d8b1e210..c5d096db11 100644 --- a/Extension/Core/Type/BirthdayType.php +++ b/Extension/Core/Type/BirthdayType.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class BirthdayType extends AbstractType @@ -24,11 +23,7 @@ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'years' => range((int) date('Y') - 120, date('Y')), - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a valid birthdate.'; - }, + 'invalid_message' => 'Please enter a valid birthdate.', ]); $resolver->setAllowedTypes('years', 'array'); diff --git a/Extension/Core/Type/CheckboxType.php b/Extension/Core/Type/CheckboxType.php index 6de35b9d48..eb82e574f2 100644 --- a/Extension/Core/Type/CheckboxType.php +++ b/Extension/Core/Type/CheckboxType.php @@ -16,7 +16,6 @@ use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class CheckboxType extends AbstractType @@ -61,11 +60,7 @@ public function configureOptions(OptionsResolver $resolver) 'empty_data' => $emptyData, 'compound' => false, 'false_values' => [null], - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'The checkbox has an invalid value.'; - }, + 'invalid_message' => 'The checkbox has an invalid value.', 'is_empty_callback' => static function ($modelData): bool { return false === $modelData; }, diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index c2899bbd78..d0b75475dd 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -52,31 +52,13 @@ class ChoiceType extends AbstractType private $choiceListFactory; private $translator; - /** - * @param TranslatorInterface $translator - */ - public function __construct(ChoiceListFactoryInterface $choiceListFactory = null, $translator = null) + public function __construct(ChoiceListFactoryInterface $choiceListFactory = null, TranslatorInterface $translator = null) { $this->choiceListFactory = $choiceListFactory ?? new CachingFactoryDecorator( new PropertyAccessDecorator( new DefaultChoiceListFactory() ) ); - - // BC, to be removed in 6.0 - if ($this->choiceListFactory instanceof CachingFactoryDecorator) { - return; - } - - $ref = new \ReflectionMethod($this->choiceListFactory, 'createListFromChoices'); - - if ($ref->getNumberOfParameters() < 3) { - trigger_deprecation('symfony/form', '5.1', 'Not defining a third parameter "callable|null $filter" in "%s::%s()" is deprecated.', $ref->class, $ref->name); - } - - if (null !== $translator && !$translator instanceof TranslatorInterface) { - throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be han instance of "%s", "%s" given.', __METHOD__, TranslatorInterface::class, \is_object($translator) ? \get_class($translator) : \gettype($translator))); - } $this->translator = $translator; } @@ -390,11 +372,7 @@ public function configureOptions(OptionsResolver $resolver) 'data_class' => null, 'choice_translation_domain' => true, 'trim' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'The selected choice is invalid.'; - }, + 'invalid_message' => 'The selected choice is invalid.', ]); $resolver->setNormalizer('placeholder', $placeholderNormalizer); diff --git a/Extension/Core/Type/CollectionType.php b/Extension/Core/Type/CollectionType.php index 5cabf16658..946c6c3d18 100644 --- a/Extension/Core/Type/CollectionType.php +++ b/Extension/Core/Type/CollectionType.php @@ -121,11 +121,7 @@ public function configureOptions(OptionsResolver $resolver) 'entry_type' => TextType::class, 'entry_options' => [], 'delete_empty' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'The collection is invalid.'; - }, + 'invalid_message' => 'The collection is invalid.', ]); $resolver->setNormalizer('entry_options', $entryOptionsNormalizer); diff --git a/Extension/Core/Type/ColorType.php b/Extension/Core/Type/ColorType.php index f4cc05247e..2f50f55a36 100644 --- a/Extension/Core/Type/ColorType.php +++ b/Extension/Core/Type/ColorType.php @@ -16,7 +16,6 @@ use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Contracts\Translation\TranslatorInterface; @@ -70,11 +69,7 @@ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'html5' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please select a valid color.'; - }, + 'invalid_message' => 'Please select a valid color.', ]); $resolver->setAllowedTypes('html5', 'bool'); diff --git a/Extension/Core/Type/CountryType.php b/Extension/Core/Type/CountryType.php index 85293bc284..d978973cb0 100644 --- a/Extension/Core/Type/CountryType.php +++ b/Extension/Core/Type/CountryType.php @@ -43,11 +43,7 @@ public function configureOptions(OptionsResolver $resolver) 'choice_translation_domain' => false, 'choice_translation_locale' => null, 'alpha3' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please select a valid country.'; - }, + 'invalid_message' => 'Please select a valid country.', ]); $resolver->setAllowedTypes('choice_translation_locale', ['null', 'string']); diff --git a/Extension/Core/Type/CurrencyType.php b/Extension/Core/Type/CurrencyType.php index 427b493f7e..12c4e65777 100644 --- a/Extension/Core/Type/CurrencyType.php +++ b/Extension/Core/Type/CurrencyType.php @@ -41,11 +41,7 @@ public function configureOptions(OptionsResolver $resolver) }, 'choice_translation_domain' => false, 'choice_translation_locale' => null, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please select a valid currency.'; - }, + 'invalid_message' => 'Please select a valid currency.', ]); $resolver->setAllowedTypes('choice_translation_locale', ['null', 'string']); diff --git a/Extension/Core/Type/DateIntervalType.php b/Extension/Core/Type/DateIntervalType.php index 0f7457d438..9f5dc41568 100644 --- a/Extension/Core/Type/DateIntervalType.php +++ b/Extension/Core/Type/DateIntervalType.php @@ -234,11 +234,7 @@ public function configureOptions(OptionsResolver $resolver) 'compound' => $compound, 'empty_data' => $emptyData, 'labels' => [], - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please choose a valid date interval.'; - }, + 'invalid_message' => 'Please choose a valid date interval.', ]); $resolver->setNormalizer('placeholder', $placeholderNormalizer); $resolver->setNormalizer('labels', $labelsNormalizer); diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index 2f397f8ed0..bcfd25b179 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -273,11 +273,7 @@ public function configureOptions(OptionsResolver $resolver) return $options['compound'] ? [] : ''; }, 'input_format' => 'Y-m-d H:i:s', - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a valid date and time.'; - }, + 'invalid_message' => 'Please enter a valid date and time.', ]); // Don't add some defaults in order to preserve the defaults diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index e39a8607bd..aafc1a0ad4 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -299,11 +299,7 @@ public function configureOptions(OptionsResolver $resolver) }, 'choice_translation_domain' => false, 'input_format' => 'Y-m-d', - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a valid date.'; - }, + 'invalid_message' => 'Please enter a valid date.', ]); $resolver->setNormalizer('placeholder', $placeholderNormalizer); diff --git a/Extension/Core/Type/EmailType.php b/Extension/Core/Type/EmailType.php index 486bc0217f..925054e4f8 100644 --- a/Extension/Core/Type/EmailType.php +++ b/Extension/Core/Type/EmailType.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class EmailType extends AbstractType @@ -23,11 +22,7 @@ class EmailType extends AbstractType public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a valid email address.'; - }, + 'invalid_message' => 'Please enter a valid email address.', ]); } diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index fc7091bad8..6868afc562 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -130,11 +130,7 @@ public function configureOptions(OptionsResolver $resolver) 'empty_data' => $emptyData, 'multiple' => false, 'allow_file_upload' => true, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please select a valid file.'; - }, + 'invalid_message' => 'Please select a valid file.', ]); } diff --git a/Extension/Core/Type/HiddenType.php b/Extension/Core/Type/HiddenType.php index f4258ec011..4292bb3b96 100644 --- a/Extension/Core/Type/HiddenType.php +++ b/Extension/Core/Type/HiddenType.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class HiddenType extends AbstractType @@ -28,11 +27,7 @@ public function configureOptions(OptionsResolver $resolver) // Pass errors to the parent 'error_bubbling' => true, 'compound' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'The hidden field is invalid.'; - }, + 'invalid_message' => 'The hidden field is invalid.', ]); } diff --git a/Extension/Core/Type/IntegerType.php b/Extension/Core/Type/IntegerType.php index a1cd058a94..fbb6128fb6 100644 --- a/Extension/Core/Type/IntegerType.php +++ b/Extension/Core/Type/IntegerType.php @@ -16,7 +16,6 @@ use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class IntegerType extends AbstractType @@ -49,11 +48,7 @@ public function configureOptions(OptionsResolver $resolver) // Integer cast rounds towards 0, so do the same when displaying fractions 'rounding_mode' => \NumberFormatter::ROUND_DOWN, 'compound' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter an integer.'; - }, + 'invalid_message' => 'Please enter an integer.', ]); $resolver->setAllowedValues('rounding_mode', [ diff --git a/Extension/Core/Type/LanguageType.php b/Extension/Core/Type/LanguageType.php index 7bcbda2077..871a293705 100644 --- a/Extension/Core/Type/LanguageType.php +++ b/Extension/Core/Type/LanguageType.php @@ -58,11 +58,7 @@ public function configureOptions(OptionsResolver $resolver) 'choice_translation_locale' => null, 'alpha3' => false, 'choice_self_translation' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please select a valid language.'; - }, + 'invalid_message' => 'Please select a valid language.', ]); $resolver->setAllowedTypes('choice_self_translation', ['bool']); diff --git a/Extension/Core/Type/LocaleType.php b/Extension/Core/Type/LocaleType.php index 14113e4ac1..3e3a55bdb4 100644 --- a/Extension/Core/Type/LocaleType.php +++ b/Extension/Core/Type/LocaleType.php @@ -41,11 +41,7 @@ public function configureOptions(OptionsResolver $resolver) }, 'choice_translation_domain' => false, 'choice_translation_locale' => null, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please select a valid locale.'; - }, + 'invalid_message' => 'Please select a valid locale.', ]); $resolver->setAllowedTypes('choice_translation_locale', ['null', 'string']); diff --git a/Extension/Core/Type/MoneyType.php b/Extension/Core/Type/MoneyType.php index 6bf7a201f3..19417cf16c 100644 --- a/Extension/Core/Type/MoneyType.php +++ b/Extension/Core/Type/MoneyType.php @@ -67,11 +67,7 @@ public function configureOptions(OptionsResolver $resolver) 'currency' => 'EUR', 'compound' => false, 'html5' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a valid money amount.'; - }, + 'invalid_message' => 'Please enter a valid money amount.', ]); $resolver->setAllowedValues('rounding_mode', [ diff --git a/Extension/Core/Type/NumberType.php b/Extension/Core/Type/NumberType.php index 2f6ac6cc2a..6e7c76f259 100644 --- a/Extension/Core/Type/NumberType.php +++ b/Extension/Core/Type/NumberType.php @@ -63,11 +63,7 @@ public function configureOptions(OptionsResolver $resolver) 'compound' => false, 'input' => 'number', 'html5' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a number.'; - }, + 'invalid_message' => 'Please enter a number.', ]); $resolver->setAllowedValues('rounding_mode', [ diff --git a/Extension/Core/Type/PasswordType.php b/Extension/Core/Type/PasswordType.php index 779f94d43b..c31d4b4341 100644 --- a/Extension/Core/Type/PasswordType.php +++ b/Extension/Core/Type/PasswordType.php @@ -14,7 +14,6 @@ use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class PasswordType extends AbstractType @@ -37,11 +36,7 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setDefaults([ 'always_empty' => true, 'trim' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'The password is invalid.'; - }, + 'invalid_message' => 'The password is invalid.', ]); } diff --git a/Extension/Core/Type/PercentType.php b/Extension/Core/Type/PercentType.php index 90e8fa6e14..41f3476365 100644 --- a/Extension/Core/Type/PercentType.php +++ b/Extension/Core/Type/PercentType.php @@ -16,7 +16,6 @@ use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class PercentType extends AbstractType @@ -53,20 +52,12 @@ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'scale' => 0, - 'rounding_mode' => function (Options $options) { - trigger_deprecation('symfony/form', '5.1', 'Not configuring the "rounding_mode" option is deprecated. It will default to "\NumberFormatter::ROUND_HALFUP" in Symfony 6.0.'); - - return null; - }, + 'rounding_mode' => \NumberFormatter::ROUND_HALFUP, 'symbol' => '%', 'type' => 'fractional', 'compound' => false, 'html5' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a percentage value.'; - }, + 'invalid_message' => 'Please enter a percentage value.', ]); $resolver->setAllowedValues('type', [ @@ -74,7 +65,6 @@ public function configureOptions(OptionsResolver $resolver) 'integer', ]); $resolver->setAllowedValues('rounding_mode', [ - null, \NumberFormatter::ROUND_FLOOR, \NumberFormatter::ROUND_DOWN, \NumberFormatter::ROUND_HALFDOWN, @@ -85,13 +75,6 @@ public function configureOptions(OptionsResolver $resolver) ]); $resolver->setAllowedTypes('scale', 'int'); $resolver->setAllowedTypes('symbol', ['bool', 'string']); - $resolver->setDeprecated('rounding_mode', 'symfony/form', '5.1', function (Options $options, $roundingMode) { - if (null === $roundingMode) { - return 'Not configuring the "rounding_mode" option is deprecated. It will default to "\NumberFormatter::ROUND_HALFUP" in Symfony 6.0.'; - } - - return ''; - }); $resolver->setAllowedTypes('html5', 'bool'); } diff --git a/Extension/Core/Type/RadioType.php b/Extension/Core/Type/RadioType.php index ed999f52b8..81a5e58aaf 100644 --- a/Extension/Core/Type/RadioType.php +++ b/Extension/Core/Type/RadioType.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class RadioType extends AbstractType @@ -23,11 +22,7 @@ class RadioType extends AbstractType public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please select a valid option.'; - }, + 'invalid_message' => 'Please select a valid option.', ]); } diff --git a/Extension/Core/Type/RangeType.php b/Extension/Core/Type/RangeType.php index 73ec6e1631..c52a6e8221 100644 --- a/Extension/Core/Type/RangeType.php +++ b/Extension/Core/Type/RangeType.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class RangeType extends AbstractType @@ -23,11 +22,7 @@ class RangeType extends AbstractType public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please choose a valid range.'; - }, + 'invalid_message' => 'Please choose a valid range.', ]); } diff --git a/Extension/Core/Type/RepeatedType.php b/Extension/Core/Type/RepeatedType.php index 16fa1a7bb7..f2a6f577b4 100644 --- a/Extension/Core/Type/RepeatedType.php +++ b/Extension/Core/Type/RepeatedType.php @@ -14,7 +14,6 @@ use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\DataTransformer\ValueToDuplicatesTransformer; use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class RepeatedType extends AbstractType @@ -58,11 +57,7 @@ public function configureOptions(OptionsResolver $resolver) 'first_name' => 'first', 'second_name' => 'second', 'error_bubbling' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'The values do not match.'; - }, + 'invalid_message' => 'The values do not match.', ]); $resolver->setAllowedTypes('options', 'array'); diff --git a/Extension/Core/Type/SearchType.php b/Extension/Core/Type/SearchType.php index 682277e615..0a8c1d723b 100644 --- a/Extension/Core/Type/SearchType.php +++ b/Extension/Core/Type/SearchType.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class SearchType extends AbstractType @@ -23,11 +22,7 @@ class SearchType extends AbstractType public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a valid search term.'; - }, + 'invalid_message' => 'Please enter a valid search term.', ]); } diff --git a/Extension/Core/Type/TelType.php b/Extension/Core/Type/TelType.php index bc25fd94ca..4076f81e00 100644 --- a/Extension/Core/Type/TelType.php +++ b/Extension/Core/Type/TelType.php @@ -23,11 +23,7 @@ class TelType extends AbstractType public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please provide a valid phone number.'; - }, + 'invalid_message' => 'Please provide a valid phone number.', ]); } diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 56d7a9921d..3eece06c1e 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -336,11 +336,7 @@ public function configureOptions(OptionsResolver $resolver) }, 'compound' => $compound, 'choice_translation_domain' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a valid time.'; - }, + 'invalid_message' => 'Please enter a valid time.', ]); $resolver->setNormalizer('view_timezone', function (Options $options, $viewTimezone): ?string { diff --git a/Extension/Core/Type/TimezoneType.php b/Extension/Core/Type/TimezoneType.php index 31b5df5c3c..0c472b6055 100644 --- a/Extension/Core/Type/TimezoneType.php +++ b/Extension/Core/Type/TimezoneType.php @@ -66,11 +66,7 @@ public function configureOptions(OptionsResolver $resolver) 'choice_translation_domain' => false, 'choice_translation_locale' => null, 'input' => 'string', - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please select a valid timezone.'; - }, + 'invalid_message' => 'Please select a valid timezone.', 'regions' => \DateTimeZone::ALL, ]); diff --git a/Extension/Core/Type/UlidType.php b/Extension/Core/Type/UlidType.php index 640d38ffa9..08e65801a8 100644 --- a/Extension/Core/Type/UlidType.php +++ b/Extension/Core/Type/UlidType.php @@ -39,11 +39,7 @@ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'compound' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a valid ULID.'; - }, + 'invalid_message' => 'Please enter a valid ULID.', ]); } } diff --git a/Extension/Core/Type/UrlType.php b/Extension/Core/Type/UrlType.php index f294a10ac2..2dde5d1625 100644 --- a/Extension/Core/Type/UrlType.php +++ b/Extension/Core/Type/UrlType.php @@ -49,11 +49,7 @@ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'default_protocol' => 'http', - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a valid URL.'; - }, + 'invalid_message' => 'Please enter a valid URL.', ]); $resolver->setAllowedTypes('default_protocol', ['null', 'string']); diff --git a/Extension/Core/Type/UuidType.php b/Extension/Core/Type/UuidType.php index 0c27802b37..c292b4bd1b 100644 --- a/Extension/Core/Type/UuidType.php +++ b/Extension/Core/Type/UuidType.php @@ -39,11 +39,7 @@ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'compound' => false, - 'invalid_message' => function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) - ? $previousValue - : 'Please enter a valid UUID.'; - }, + 'invalid_message' => 'Please enter a valid UUID.', ]); } } diff --git a/Extension/Core/Type/WeekType.php b/Extension/Core/Type/WeekType.php index b7f8887d95..40b08c8af8 100644 --- a/Extension/Core/Type/WeekType.php +++ b/Extension/Core/Type/WeekType.php @@ -155,9 +155,7 @@ public function configureOptions(OptionsResolver $resolver) }, 'compound' => $compound, 'choice_translation_domain' => false, - 'invalid_message' => static function (Options $options, $previousValue) { - return ($options['legacy_error_messages'] ?? true) ? $previousValue : 'Please enter a valid week.'; - }, + 'invalid_message' => 'Please enter a valid week.', ]); $resolver->setNormalizer('placeholder', $placeholderNormalizer); diff --git a/Extension/Validator/Type/FormTypeValidatorExtension.php b/Extension/Validator/Type/FormTypeValidatorExtension.php index aa6a8e4030..0a27c1729f 100644 --- a/Extension/Validator/Type/FormTypeValidatorExtension.php +++ b/Extension/Validator/Type/FormTypeValidatorExtension.php @@ -67,13 +67,6 @@ public function configureOptions(OptionsResolver $resolver) 'extra_fields_message' => 'This form should not contain extra fields.', ]); $resolver->setAllowedTypes('legacy_error_messages', 'bool'); - $resolver->setDeprecated('legacy_error_messages', 'symfony/form', '5.2', function (Options $options, $value) { - if (true === $value) { - return 'Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'; - } - - return ''; - }); $resolver->setNormalizer('constraints', $constraintsNormalizer); } diff --git a/Tests/Command/DebugCommandTest.php b/Tests/Command/DebugCommandTest.php index 586a488d2d..8da340595d 100644 --- a/Tests/Command/DebugCommandTest.php +++ b/Tests/Command/DebugCommandTest.php @@ -42,11 +42,6 @@ public function testDebugDeprecatedDefaults() $this->assertEquals(0, $ret, 'Returns 0 in case of success'); $this->assertSame(<<assertEquals('12,34', $transformer->transform(0.1234)); } - /** - * @group legacy - */ - public function testReverseTransformWithScaleAndRoundingDisabled() + public function testReverseTransformWithScaleAndImplicitRounding() { - $this->expectDeprecation('Since symfony/form 5.1: Not passing a rounding mode to "Symfony\Component\Form\Extension\Core\DataTransformer\PercentToLocalizedStringTransformer::__construct()" is deprecated. Starting with Symfony 6.0 it will default to "\NumberFormatter::ROUND_HALFUP".'); - $transformer = new PercentToLocalizedStringTransformer(2, PercentToLocalizedStringTransformer::FRACTIONAL); - $this->assertEquals(0.0123456, $transformer->reverseTransform('1.23456')); + $this->assertEquals(0.0123, $transformer->reverseTransform('1.23456')); } public function testReverseTransform() diff --git a/Tests/Extension/Core/Type/ChoiceTypeTest.php b/Tests/Extension/Core/Type/ChoiceTypeTest.php index 50b259f58e..bca4a4cd8e 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -15,9 +15,7 @@ use Symfony\Component\Form\ChoiceList\Loader\CallbackChoiceLoader; use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView; use Symfony\Component\Form\ChoiceList\View\ChoiceView; -use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\FormInterface; -use Symfony\Component\Form\Tests\Fixtures\ChoiceList\DeprecatedChoiceListFactory; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class ChoiceTypeTest extends BaseTypeTest @@ -2252,16 +2250,4 @@ public function testFilteredChoiceLoader() new ChoiceView('c', 'c', 'Kris'), ], $form->createView()->vars['choices']); } - - /** - * @group legacy - */ - public function testUsingDeprecatedChoiceListFactory() - { - $this->expectDeprecation('The "Symfony\Component\Form\Tests\Fixtures\ChoiceList\DeprecatedChoiceListFactory::createListFromChoices()" method will require a new "callable|null $filter" argument in the next major version of its interface "Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface", not defining it is deprecated.'); - $this->expectDeprecation('The "Symfony\Component\Form\Tests\Fixtures\ChoiceList\DeprecatedChoiceListFactory::createListFromLoader()" method will require a new "callable|null $filter" argument in the next major version of its interface "Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface", not defining it is deprecated.'); - $this->expectDeprecation('Since symfony/form 5.1: Not defining a third parameter "callable|null $filter" in "Symfony\Component\Form\Tests\Fixtures\ChoiceList\DeprecatedChoiceListFactory::createListFromChoices()" is deprecated.'); - - new ChoiceType(new DeprecatedChoiceListFactory()); - } } diff --git a/Tests/Extension/Core/Type/PercentTypeTest.php b/Tests/Extension/Core/Type/PercentTypeTest.php index 875ac905f7..a4e3617d54 100644 --- a/Tests/Extension/Core/Type/PercentTypeTest.php +++ b/Tests/Extension/Core/Type/PercentTypeTest.php @@ -83,36 +83,14 @@ public function testHtml5EnablesSpecificFormatting() $this->assertSame('number', $form->createView()->vars['type']); } - /** - * @group legacy - */ public function testSubmitWithoutRoundingMode() { - $this->expectDeprecation('Since symfony/form 5.1: Not configuring the "rounding_mode" option is deprecated. It will default to "\NumberFormatter::ROUND_HALFUP" in Symfony 6.0.'); - - $form = $this->factory->create(self::TESTED_TYPE, null, [ - 'scale' => 2, - ]); - - $form->submit('1.23456'); - - $this->assertEquals(0.0123456, $form->getData()); - } - - /** - * @group legacy - */ - public function testSubmitWithNullRoundingMode() - { - $this->expectDeprecation('Since symfony/form 5.1: Not configuring the "rounding_mode" option is deprecated. It will default to "\NumberFormatter::ROUND_HALFUP" in Symfony 6.0.'); - $form = $this->factory->create(self::TESTED_TYPE, null, [ - 'rounding_mode' => null, 'scale' => 2, ]); $form->submit('1.23456'); - $this->assertEquals(0.0123456, $form->getData()); + $this->assertEquals(0.0123, $form->getData()); } } diff --git a/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php b/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php index 16c65fb71b..bac6cdfcac 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php @@ -409,9 +409,9 @@ public function testSubmitFormChoiceInvalid() $this->assertTrue($form->isSubmitted()); $this->assertFalse($form->isValid()); $this->assertCount(2, $form->getErrors()); - $this->assertSame('This value is not valid.', $form->getErrors()[0]->getMessage()); + $this->assertSame('Please enter a valid date.', $form->getErrors()[0]->getMessage()); $this->assertSame($form->get('year'), $form->getErrors()[0]->getOrigin()); - $this->assertSame('This value is not valid.', $form->getErrors()[1]->getMessage()); + $this->assertSame('Please enter a valid date.', $form->getErrors()[1]->getMessage()); $this->assertSame($form->get('month'), $form->getErrors()[1]->getOrigin()); } diff --git a/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php index 68c7ad7b77..51e10719d3 100644 --- a/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please enter a valid birthdate.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php index cdb648a19d..89b26d5644 100644 --- a/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('The checkbox has an invalid value.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php index d09b292bcc..432e7072fc 100644 --- a/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('The selected choice is invalid.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php index 41c606c87b..1985a925e7 100644 --- a/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('The collection is invalid.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php index 9ba71f1c02..059e39eefd 100644 --- a/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please select a valid color.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php index cfcc2a1e31..cd95fb04df 100644 --- a/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please select a valid country.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php index 67d5763878..57d68b6c14 100644 --- a/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please select a valid currency.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php index 8469d2bc5d..be2d5f3d96 100644 --- a/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please choose a valid date interval.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php index a1590d5211..013b964e25 100644 --- a/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please enter a valid date and time.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php index b90be94d45..f5a702a491 100644 --- a/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please enter a valid date.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php index c478070a67..db2e3b5e75 100644 --- a/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please enter a valid email address.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php index c905b5d3e7..78b38efe2e 100644 --- a/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please select a valid file.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php index bdeef07c87..ad7d00bc34 100644 --- a/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php @@ -142,18 +142,6 @@ public function testInvalidMessage() $this->assertEquals('This value is not valid.', $form->getConfig()->getOption('invalid_message')); } - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm(['legacy_error_messages' => true]); - - $this->assertEquals('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } - protected function createForm(array $options = []) { return $this->factory->create(FormTypeTest::TESTED_TYPE, null, $options); diff --git a/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php index 38fd4bb859..29e5bdb325 100644 --- a/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('The hidden field is invalid.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php index fbfede9156..5d101ef2dd 100644 --- a/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please enter an integer.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php index 3ac1177375..3a3e09a1aa 100644 --- a/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please select a valid language.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php index 427db032fc..bbb8048c77 100644 --- a/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please select a valid locale.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php index b030ed47ab..f8668caf46 100644 --- a/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please enter a valid money amount.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php index a417dc1af6..1d693133a4 100644 --- a/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please enter a number.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php index 629e016d39..1c55d87774 100644 --- a/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('The password is invalid.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php index 80fc502c29..dd05b64a88 100644 --- a/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please enter a percentage value.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php index 508eb38599..4ca686ac38 100644 --- a/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please select a valid option.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php index 3b33dde9a5..2832ef9eca 100644 --- a/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please choose a valid range.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php index 584dcd9265..8bb635e077 100644 --- a/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('The values do not match.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php index af57e23dc8..5ce3fff70a 100644 --- a/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please enter a valid search term.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php index 87dc2d76d5..969f2c9f2a 100644 --- a/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please provide a valid phone number.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php index 7f5b938475..29019cd0b6 100644 --- a/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please enter a valid time.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php index 833602989d..7e00cff6d4 100644 --- a/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please select a valid timezone.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php index 927891ba42..698b181314 100644 --- a/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php @@ -31,18 +31,4 @@ public function testInvalidMessage() $this->assertSame('Please enter a valid URL.', $form->getConfig()->getOption('invalid_message')); } - - /** - * @group legacy - */ - public function testLegacyInvalidMessage() - { - $this->expectDeprecation('Since symfony/form 5.2: Setting the "legacy_error_messages" option to "true" is deprecated. It will be disabled in Symfony 6.0.'); - - $form = $this->createForm([ - 'legacy_error_messages' => true, - ]); - - $this->assertSame('This value is not valid.', $form->getConfig()->getOption('invalid_message')); - } } diff --git a/Tests/Fixtures/ChoiceList/DeprecatedChoiceListFactory.php b/Tests/Fixtures/ChoiceList/DeprecatedChoiceListFactory.php deleted file mode 100644 index 6361c2eedc..0000000000 --- a/Tests/Fixtures/ChoiceList/DeprecatedChoiceListFactory.php +++ /dev/null @@ -1,22 +0,0 @@ - Date: Mon, 21 Jun 2021 11:50:22 +0200 Subject: [PATCH 010/208] Remove code for old libxml versions Signed-off-by: Alexander M. Turek --- Tests/Resources/TranslationFilesTest.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/Tests/Resources/TranslationFilesTest.php b/Tests/Resources/TranslationFilesTest.php index 4d59b73583..1b83bfc3bf 100644 --- a/Tests/Resources/TranslationFilesTest.php +++ b/Tests/Resources/TranslationFilesTest.php @@ -37,9 +37,6 @@ public function testTranslationFileIsValidWithoutEntityLoader($filePath) { $document = new \DOMDocument(); $document->loadXML(file_get_contents($filePath)); - if (\LIBXML_VERSION < 20900) { - libxml_disable_entity_loader(true); - } $errors = XliffUtils::validateSchema($document); From 34f9e8701fe96aea210c725d091c756d46910053 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Fri, 2 Jul 2021 17:01:07 +0200 Subject: [PATCH 011/208] update changelog --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 59a1810180..a6cc01cf43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,11 @@ CHANGELOG --- * Remove `PropertyPathMaper` - * Remove `Symfony\Component\Form\Extension\Validator\Util\ServiceParams` + * Remove `Symfony\Component\Form\Extension\Validator\Util\ServerParams` * Remove `FormPass` configuration * Remove the `NumberToLocalizedStringTransformer::ROUND_*` constants, use `\NumberFormatter::ROUND_*` instead + * The `rounding_mode` option of the `PercentType` defaults to `\NumberFormatter::ROUND_HALFUP` + * The rounding mode argument of the constructor of `PercentToLocalizedStringTransformer` defaults to `\NumberFormatter::ROUND_HALFUP` * Add `FormConfigInterface::getIsEmptyCallback()` and `FormConfigBuilderInterface::setIsEmptyCallback()` * Change `$forms` parameter type of the `DataMapper::mapDataToForms()` method from `iterable` to `\Traversable` * Change `$forms` parameter type of the `DataMapper::mapFormsToData()` method from `iterable` to `\Traversable` From c3d0fd33ed601ba3f5771159f2190d78ffd24283 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 6 Jul 2021 10:45:38 +0200 Subject: [PATCH 012/208] [Form] add union types --- AbstractRendererEngine.php | 2 +- Button.php | 32 +++------ ButtonBuilder.php | 25 +++---- CallbackTransformer.php | 4 +- ChoiceList/ChoiceList.php | 70 ++++++++----------- .../Factory/Cache/AbstractStaticOption.php | 11 +-- .../Factory/CachingFactoryDecorator.php | 34 +++++---- .../Factory/ChoiceListFactoryInterface.php | 2 +- .../Factory/DefaultChoiceListFactory.php | 4 +- .../Factory/PropertyAccessDecorator.php | 6 +- ChoiceList/View/ChoiceView.php | 2 +- Console/Descriptor/Descriptor.php | 2 +- DataAccessorInterface.php | 21 ++---- DataMapperInterface.php | 4 +- DataTransformerInterface.php | 4 +- Exception/UnexpectedTypeException.php | 2 +- .../Core/DataAccessor/CallbackAccessor.php | 8 +-- Extension/Core/DataAccessor/ChainAccessor.php | 8 +-- .../DataAccessor/PropertyPathAccessor.php | 17 ++--- .../Core/DataMapper/CheckboxListMapper.php | 2 +- Extension/Core/DataMapper/DataMapper.php | 2 +- Extension/Core/DataMapper/RadioListMapper.php | 2 +- .../ArrayToPartsTransformer.php | 4 +- .../BooleanToStringTransformer.php | 4 +- .../ChoiceToValueTransformer.php | 4 +- .../ChoicesToValuesTransformer.php | 4 +- .../DataTransformer/DataTransformerChain.php | 4 +- .../DateIntervalToArrayTransformer.php | 4 +- .../DateIntervalToStringTransformer.php | 4 +- ...DateTimeImmutableToDateTimeTransformer.php | 4 +- .../DateTimeToArrayTransformer.php | 4 +- ...ateTimeToHtml5LocalDateTimeTransformer.php | 4 +- .../DateTimeToLocalizedStringTransformer.php | 4 +- .../DateTimeToRfc3339Transformer.php | 4 +- .../DateTimeToStringTransformer.php | 4 +- .../DateTimeToTimestampTransformer.php | 4 +- .../DateTimeZoneToStringTransformer.php | 4 +- .../IntegerToLocalizedStringTransformer.php | 4 +- .../IntlTimeZoneToStringTransformer.php | 4 +- .../MoneyToLocalizedStringTransformer.php | 4 +- .../NumberToLocalizedStringTransformer.php | 12 ++-- .../PercentToLocalizedStringTransformer.php | 4 +- .../StringToFloatTransformer.php | 4 +- .../UlidToStringTransformer.php | 4 +- .../UuidToStringTransformer.php | 4 +- .../ValueToDuplicatesTransformer.php | 8 +-- .../WeekToArrayTransformer.php | 4 +- .../Core/EventListener/ResizeFormListener.php | 7 +- Extension/Core/Type/FileType.php | 4 +- Extension/Core/Type/TextType.php | 4 +- .../HttpFoundationRequestHandler.php | 6 +- .../Validator/Constraints/FormValidator.php | 18 +++-- Extension/Validator/ValidatorTypeGuesser.php | 2 +- Form.php | 24 +++---- FormBuilder.php | 10 +-- FormBuilderInterface.php | 5 +- FormConfigBuilder.php | 12 ++-- FormConfigBuilderInterface.php | 8 +-- FormConfigInterface.php | 8 +-- FormError.php | 2 +- FormErrorIterator.php | 14 ++-- FormEvent.php | 9 +-- FormFactory.php | 14 ++-- FormFactoryInterface.php | 14 ++-- FormInterface.php | 10 ++- FormRenderer.php | 2 +- FormRendererEngineInterface.php | 4 +- FormRendererInterface.php | 2 +- FormView.php | 8 +-- Guess/ValueGuess.php | 6 +- NativeRequestHandler.php | 10 +-- RequestHandlerInterface.php | 8 +-- ReversedTransformer.php | 4 +- SubmitButton.php | 5 +- Tests/FormBuilderTest.php | 6 -- Tests/VersionAwareTest.php | 5 +- Util/FormUtil.php | 4 +- Util/OptionsResolverWrapper.php | 8 ++- Util/OrderedHashMap.php | 8 +-- 79 files changed, 269 insertions(+), 358 deletions(-) diff --git a/AbstractRendererEngine.php b/AbstractRendererEngine.php index 905c98bbeb..4179e392d7 100644 --- a/AbstractRendererEngine.php +++ b/AbstractRendererEngine.php @@ -44,7 +44,7 @@ public function __construct(array $defaultThemes = []) /** * {@inheritdoc} */ - public function setTheme(FormView $view, $themes, bool $useDefaultThemes = true) + public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true) { $cacheKey = $view->vars[self::CACHE_KEY_VAR]; diff --git a/Button.php b/Button.php index e8d521047f..2761db7e32 100644 --- a/Button.php +++ b/Button.php @@ -47,11 +47,9 @@ public function __construct(FormConfigInterface $config) /** * Unsupported method. * - * @param mixed $offset - * * @return bool Always returns false */ - public function offsetExists($offset) + public function offsetExists(mixed $offset) { return false; } @@ -61,11 +59,9 @@ public function offsetExists($offset) * * This method should not be invoked. * - * @param mixed $offset - * * @throws BadMethodCallException */ - public function offsetGet($offset) + public function offsetGet(mixed $offset) { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -75,12 +71,9 @@ public function offsetGet($offset) * * This method should not be invoked. * - * @param mixed $offset - * @param mixed $value - * * @throws BadMethodCallException */ - public function offsetSet($offset, $value) + public function offsetSet(mixed $offset, mixed $value) { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -90,11 +83,9 @@ public function offsetSet($offset, $value) * * This method should not be invoked. * - * @param mixed $offset - * * @throws BadMethodCallException */ - public function offsetUnset($offset) + public function offsetUnset(mixed $offset) { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -128,7 +119,7 @@ public function getParent() * * @throws BadMethodCallException */ - public function add($child, string $type = null, array $options = []) + public function add(string|FormInterface $child, string $type = null, array $options = []) { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -188,11 +179,9 @@ public function getErrors(bool $deep = false, bool $flatten = true) * * This method should not be invoked. * - * @param mixed $modelData - * * @return $this */ - public function setData($modelData) + public function setData(mixed $modelData) { // no-op, called during initialization of the form tree return $this; @@ -353,11 +342,9 @@ public function initialize() /** * Unsupported method. * - * @param mixed $request - * * @throws BadMethodCallException */ - public function handleRequest($request = null) + public function handleRequest(mixed $request = null) { throw new BadMethodCallException('Buttons cannot handle requests. Call handleRequest() on the root form instead.'); } @@ -365,14 +352,11 @@ public function handleRequest($request = null) /** * Submits data to the button. * - * @param string|null $submittedData Not used - * @param bool $clearMissing Not used - * * @return $this * * @throws Exception\AlreadySubmittedException if the button has already been submitted */ - public function submit($submittedData, bool $clearMissing = true) + public function submit(array|string|null $submittedData, bool $clearMissing = true) { if ($this->submitted) { throw new AlreadySubmittedException('A form can only be submitted once.'); diff --git a/ButtonBuilder.php b/ButtonBuilder.php index bf020baf53..8c5a8b9a6d 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -14,6 +14,7 @@ use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Form\Exception\BadMethodCallException; use Symfony\Component\Form\Exception\InvalidArgumentException; +use Symfony\Component\PropertyAccess\PropertyPathInterface; /** * A builder for {@link Button} instances. @@ -71,7 +72,7 @@ public function __construct(?string $name, array $options = []) * * @throws BadMethodCallException */ - public function add($child, string $type = null, array $options = []) + public function add(string|FormBuilderInterface $child, string $type = null, array $options = []) { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -217,7 +218,7 @@ public function resetModelTransformers() /** * {@inheritdoc} */ - public function setAttribute(string $name, $value) + public function setAttribute(string $name, mixed $value) { $this->attributes[$name] = $value; @@ -263,11 +264,9 @@ public function setDisabled(bool $disabled) * * This method should not be invoked. * - * @param mixed $emptyData - * * @throws BadMethodCallException */ - public function setEmptyData($emptyData) + public function setEmptyData(mixed $emptyData) { throw new BadMethodCallException('Buttons do not support empty data.'); } @@ -301,11 +300,9 @@ public function setRequired(bool $required) * * This method should not be invoked. * - * @param null $propertyPath - * * @throws BadMethodCallException */ - public function setPropertyPath($propertyPath) + public function setPropertyPath(string|PropertyPathInterface|null $propertyPath) { throw new BadMethodCallException('Buttons do not support property paths.'); } @@ -363,11 +360,9 @@ public function setType(ResolvedFormTypeInterface $type) * * This method should not be invoked. * - * @param mixed $data - * * @throws BadMethodCallException */ - public function setData($data) + public function setData(mixed $data) { throw new BadMethodCallException('Buttons do not support data.'); } @@ -629,11 +624,9 @@ public function hasAttribute(string $name) /** * Returns the value of the given attribute. * - * @param mixed $default The value returned if the attribute does not exist - * * @return mixed The attribute value */ - public function getAttribute(string $name, $default = null) + public function getAttribute(string $name, mixed $default = null) { return \array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; } @@ -739,11 +732,9 @@ public function hasOption(string $name) /** * Returns the value of a specific option. * - * @param mixed $default The value returned if the option does not exist - * * @return mixed The option value */ - public function getOption(string $name, $default = null) + public function getOption(string $name, mixed $default = null) { return \array_key_exists($name, $this->options) ? $this->options[$name] : $default; } diff --git a/CallbackTransformer.php b/CallbackTransformer.php index 5125214ff9..0f7422ae64 100644 --- a/CallbackTransformer.php +++ b/CallbackTransformer.php @@ -29,7 +29,7 @@ public function __construct(callable $transform, callable $reverseTransform) /** * {@inheritdoc} */ - public function transform($data) + public function transform(mixed $data) { return ($this->transform)($data); } @@ -37,7 +37,7 @@ public function transform($data) /** * {@inheritdoc} */ - public function reverseTransform($data) + public function reverseTransform(mixed $data) { return ($this->reverseTransform)($data); } diff --git a/ChoiceList/ChoiceList.php b/ChoiceList/ChoiceList.php index df63c83d89..31166c1bdf 100644 --- a/ChoiceList/ChoiceList.php +++ b/ChoiceList/ChoiceList.php @@ -35,11 +35,10 @@ final class ChoiceList /** * Creates a cacheable loader from any callable providing iterable choices. * - * @param FormTypeInterface|FormTypeExtensionInterface $formType A form type or type extension configuring a cacheable choice list - * @param callable $choices A callable that must return iterable choices or grouped choices - * @param mixed|null $vary Dynamic data used to compute a unique hash when caching the loader + * @param callable $choices A callable that must return iterable choices or grouped choices + * @param mixed $vary Dynamic data used to compute a unique hash when caching the loader */ - public static function lazy($formType, callable $choices, $vary = null): ChoiceLoader + public static function lazy(FormTypeInterface|FormTypeExtensionInterface $formType, callable $choices, mixed $vary = null): ChoiceLoader { return self::loader($formType, new CallbackChoiceLoader($choices), $vary); } @@ -47,11 +46,10 @@ public static function lazy($formType, callable $choices, $vary = null): ChoiceL /** * Decorates a loader to make it cacheable. * - * @param FormTypeInterface|FormTypeExtensionInterface $formType A form type or type extension configuring a cacheable choice list - * @param ChoiceLoaderInterface $loader A loader responsible for creating loading choices or grouped choices - * @param mixed|null $vary Dynamic data used to compute a unique hash when caching the loader + * @param ChoiceLoaderInterface $loader A loader responsible for creating loading choices or grouped choices + * @param mixed $vary Dynamic data used to compute a unique hash when caching the loader */ - public static function loader($formType, ChoiceLoaderInterface $loader, $vary = null): ChoiceLoader + public static function loader(FormTypeInterface|FormTypeExtensionInterface $formType, ChoiceLoaderInterface $loader, mixed $vary = null): ChoiceLoader { return new ChoiceLoader($formType, $loader, $vary); } @@ -59,21 +57,19 @@ public static function loader($formType, ChoiceLoaderInterface $loader, $vary = /** * Decorates a "choice_value" callback to make it cacheable. * - * @param FormTypeInterface|FormTypeExtensionInterface $formType A form type or type extension configuring a cacheable choice list - * @param callable $value Any pseudo callable to create a unique string value from a choice - * @param mixed|null $vary Dynamic data used to compute a unique hash when caching the callback + * @param callable|array $value Any pseudo callable to create a unique string value from a choice + * @param mixed $vary Dynamic data used to compute a unique hash when caching the callback */ - public static function value($formType, $value, $vary = null): ChoiceValue + public static function value(FormTypeInterface|FormTypeExtensionInterface $formType, callable|array $value, mixed $vary = null): ChoiceValue { return new ChoiceValue($formType, $value, $vary); } /** - * @param FormTypeInterface|FormTypeExtensionInterface $formType A form type or type extension configuring a cacheable choice list - * @param callable $filter Any pseudo callable to filter a choice list - * @param mixed|null $vary Dynamic data used to compute a unique hash when caching the callback + * @param callable|array $filter Any pseudo callable to filter a choice list + * @param mixed $vary Dynamic data used to compute a unique hash when caching the callback */ - public static function filter($formType, $filter, $vary = null): ChoiceFilter + public static function filter(FormTypeInterface|FormTypeExtensionInterface $formType, callable|array $filter, mixed $vary = null): ChoiceFilter { return new ChoiceFilter($formType, $filter, $vary); } @@ -81,11 +77,10 @@ public static function filter($formType, $filter, $vary = null): ChoiceFilter /** * Decorates a "choice_label" option to make it cacheable. * - * @param FormTypeInterface|FormTypeExtensionInterface $formType A form type or type extension configuring a cacheable choice list - * @param callable|false $label Any pseudo callable to create a label from a choice or false to discard it - * @param mixed|null $vary Dynamic data used to compute a unique hash when caching the option + * @param callable|false $label Any pseudo callable to create a label from a choice or false to discard it + * @param mixed $vary Dynamic data used to compute a unique hash when caching the option */ - public static function label($formType, $label, $vary = null): ChoiceLabel + public static function label(FormTypeInterface|FormTypeExtensionInterface $formType, callable|false $label, mixed $vary = null): ChoiceLabel { return new ChoiceLabel($formType, $label, $vary); } @@ -93,11 +88,10 @@ public static function label($formType, $label, $vary = null): ChoiceLabel /** * Decorates a "choice_name" callback to make it cacheable. * - * @param FormTypeInterface|FormTypeExtensionInterface $formType A form type or type extension configuring a cacheable choice list - * @param callable $fieldName Any pseudo callable to create a field name from a choice - * @param mixed|null $vary Dynamic data used to compute a unique hash when caching the callback + * @param callable|array $fieldName Any pseudo callable to create a field name from a choice + * @param mixed $vary Dynamic data used to compute a unique hash when caching the callback */ - public static function fieldName($formType, $fieldName, $vary = null): ChoiceFieldName + public static function fieldName(FormTypeInterface|FormTypeExtensionInterface $formType, callable|array $fieldName, mixed $vary = null): ChoiceFieldName { return new ChoiceFieldName($formType, $fieldName, $vary); } @@ -105,11 +99,10 @@ public static function fieldName($formType, $fieldName, $vary = null): ChoiceFie /** * Decorates a "choice_attr" option to make it cacheable. * - * @param FormTypeInterface|FormTypeExtensionInterface $formType A form type or type extension configuring a cacheable choice list - * @param callable|array $attr Any pseudo callable or array to create html attributes from a choice - * @param mixed|null $vary Dynamic data used to compute a unique hash when caching the option + * @param callable|array $attr Any pseudo callable or array to create html attributes from a choice + * @param mixed $vary Dynamic data used to compute a unique hash when caching the option */ - public static function attr($formType, $attr, $vary = null): ChoiceAttr + public static function attr(FormTypeInterface|FormTypeExtensionInterface $formType, callable|array $attr, mixed $vary = null): ChoiceAttr { return new ChoiceAttr($formType, $attr, $vary); } @@ -117,11 +110,10 @@ public static function attr($formType, $attr, $vary = null): ChoiceAttr /** * Decorates a "choice_translation_parameters" option to make it cacheable. * - * @param FormTypeInterface|FormTypeExtensionInterface $formType A form type or type extension configuring a cacheable choice list - * @param callable|array $translationParameters Any pseudo callable or array to create translation parameters from a choice - * @param mixed|null $vary Dynamic data used to compute a unique hash when caching the option + * @param callable|array $translationParameters Any pseudo callable or array to create translation parameters from a choice + * @param mixed $vary Dynamic data used to compute a unique hash when caching the option */ - public static function translationParameters($formType, $translationParameters, $vary = null): ChoiceTranslationParameters + public static function translationParameters(FormTypeInterface|FormTypeExtensionInterface $formType, callable|array $translationParameters, mixed $vary = null): ChoiceTranslationParameters { return new ChoiceTranslationParameters($formType, $translationParameters, $vary); } @@ -129,11 +121,10 @@ public static function translationParameters($formType, $translationParameters, /** * Decorates a "group_by" callback to make it cacheable. * - * @param FormTypeInterface|FormTypeExtensionInterface $formType A form type or type extension configuring a cacheable choice list - * @param callable $groupBy Any pseudo callable to return a group name from a choice - * @param mixed|null $vary Dynamic data used to compute a unique hash when caching the callback + * @param callable|array $groupBy Any pseudo callable to return a group name from a choice + * @param mixed $vary Dynamic data used to compute a unique hash when caching the callback */ - public static function groupBy($formType, $groupBy, $vary = null): GroupBy + public static function groupBy(FormTypeInterface|FormTypeExtensionInterface $formType, callable|array $groupBy, mixed $vary = null): GroupBy { return new GroupBy($formType, $groupBy, $vary); } @@ -141,11 +132,10 @@ public static function groupBy($formType, $groupBy, $vary = null): GroupBy /** * Decorates a "preferred_choices" option to make it cacheable. * - * @param FormTypeInterface|FormTypeExtensionInterface $formType A form type or type extension configuring a cacheable choice list - * @param callable|array $preferred Any pseudo callable or array to return a group name from a choice - * @param mixed|null $vary Dynamic data used to compute a unique hash when caching the option + * @param callable|array $preferred Any pseudo callable or array to return a group name from a choice + * @param mixed $vary Dynamic data used to compute a unique hash when caching the option */ - public static function preferred($formType, $preferred, $vary = null): PreferredChoice + public static function preferred(FormTypeInterface|FormTypeExtensionInterface $formType, callable|array $preferred, mixed $vary = null): PreferredChoice { return new PreferredChoice($formType, $preferred, $vary); } diff --git a/ChoiceList/Factory/Cache/AbstractStaticOption.php b/ChoiceList/Factory/Cache/AbstractStaticOption.php index 42b31e0275..e209cf1565 100644 --- a/ChoiceList/Factory/Cache/AbstractStaticOption.php +++ b/ChoiceList/Factory/Cache/AbstractStaticOption.php @@ -34,16 +34,11 @@ abstract class AbstractStaticOption private $option; /** - * @param FormTypeInterface|FormTypeExtensionInterface $formType A form type or type extension configuring a cacheable choice list - * @param mixed $option Any pseudo callable, array, string or bool to define a choice list option - * @param mixed|null $vary Dynamic data used to compute a unique hash when caching the option + * @param mixed $option Any pseudo callable, array, string or bool to define a choice list option + * @param mixed $vary Dynamic data used to compute a unique hash when caching the option */ - final public function __construct($formType, $option, $vary = null) + final public function __construct(FormTypeInterface|FormTypeExtensionInterface $formType, mixed $option, mixed $vary = null) { - if (!$formType instanceof FormTypeInterface && !$formType instanceof FormTypeExtensionInterface) { - throw new \TypeError(sprintf('Expected an instance of "%s" or "%s", but got "%s".', FormTypeInterface::class, FormTypeExtensionInterface::class, get_debug_type($formType))); - } - $hash = CachingFactoryDecorator::generateHash([static::class, $formType, $vary]); $this->option = self::$options[$hash] ?? self::$options[$hash] = $option; diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index 746a1ad064..268f35ce11 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -45,13 +45,11 @@ class CachingFactoryDecorator implements ChoiceListFactoryInterface, ResetInterf * Optionally, a namespace string can be passed. Calling this method will * the same values, but different namespaces, will return different hashes. * - * @param mixed $value The value to hash - * * @return string The SHA-256 hash * * @internal */ - public static function generateHash($value, string $namespace = ''): string + public static function generateHash(mixed $value, string $namespace = ''): string { if (\is_object($value)) { $value = spl_object_hash($value); @@ -84,12 +82,12 @@ public function getDecoratedFactory() /** * {@inheritdoc} * - * @param callable|Cache\ChoiceValue|null $value The callable or static option for - * generating the choice values - * @param callable|Cache\ChoiceFilter|null $filter The callable or static option for - * filtering the choices + * @param callable|string|Cache\ChoiceValue|null $value The callable or static option for + * generating the choice values + * @param callable|string|Cache\ChoiceFilter|null $filter The callable or static option for + * filtering the choices */ - public function createListFromChoices(iterable $choices, $value = null, $filter = null) + public function createListFromChoices(iterable $choices, callable|string|Cache\ChoiceValue $value = null, callable|string|Cache\ChoiceFilter $filter = null) { if ($choices instanceof \Traversable) { $choices = iterator_to_array($choices); @@ -127,12 +125,12 @@ public function createListFromChoices(iterable $choices, $value = null, $filter * * @param ChoiceLoaderInterface|Cache\ChoiceLoader $loader The loader or static loader to load * the choices lazily - * @param callable|Cache\ChoiceValue|null $value The callable or static option for + * @param callable|string|Cache\ChoiceValue|null $value The callable or static option for * generating the choice values - * @param callable|Cache\ChoiceFilter|null $filter The callable or static option for + * @param callable|string|Cache\ChoiceFilter|null $filter The callable or static option for * filtering the choices */ - public function createListFromLoader(ChoiceLoaderInterface $loader, $value = null, $filter = null) + public function createListFromLoader(ChoiceLoaderInterface|Cache\ChoiceLoader $loader, callable|string|Cache\ChoiceValue $value = null, callable|string|Cache\ChoiceFilter $filter = null) { $cache = true; @@ -170,14 +168,14 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, $value = nul /** * {@inheritdoc} * - * @param array|callable|Cache\PreferredChoice|null $preferredChoices The preferred choices - * @param callable|false|Cache\ChoiceLabel|null $label The option or static option generating the choice labels - * @param callable|Cache\ChoiceFieldName|null $index The option or static option generating the view indices - * @param callable|Cache\GroupBy|null $groupBy The option or static option generating the group names - * @param array|callable|Cache\ChoiceAttr|null $attr The option or static option generating the HTML attributes - * @param array|callable|Cache\ChoiceTranslationParameters $labelTranslationParameters The parameters used to translate the choice labels + * @param array|callable|string|Cache\PreferredChoice|null $preferredChoices The preferred choices + * @param callable|false|string|Cache\ChoiceLabel|null $label The option or static option generating the choice labels + * @param callable|string|Cache\ChoiceFieldName|null $index The option or static option generating the view indices + * @param callable|string|Cache\GroupBy|null $groupBy The option or static option generating the group names + * @param array|callable|string|Cache\ChoiceAttr|null $attr The option or static option generating the HTML attributes + * @param array|callable|string|Cache\ChoiceTranslationParameters $labelTranslationParameters The parameters used to translate the choice labels */ - public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, $index = null, $groupBy = null, $attr = null, $labelTranslationParameters = []) + public function createView(ChoiceListInterface $list, array|callable|string|Cache\PreferredChoice $preferredChoices = null, callable|false|string|Cache\ChoiceLabel $label = null, callable|string|Cache\ChoiceFieldName $index = null, callable|string|Cache\GroupBy $groupBy = null, array|callable|string|Cache\ChoiceAttr $attr = null, array|callable|string|Cache\ChoiceTranslationParameters $labelTranslationParameters = []) { $cache = true; diff --git a/ChoiceList/Factory/ChoiceListFactoryInterface.php b/ChoiceList/Factory/ChoiceListFactoryInterface.php index 311d552616..91aad19865 100644 --- a/ChoiceList/Factory/ChoiceListFactoryInterface.php +++ b/ChoiceList/Factory/ChoiceListFactoryInterface.php @@ -84,5 +84,5 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $va * * @return ChoiceListView The choice list view */ - public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, callable $index = null, callable $groupBy = null, $attr = null, $labelTranslationParameters = []); + public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []); } diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index 8d5e650c59..13c7a96dc0 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -61,10 +61,8 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $va /** * {@inheritdoc} - * - * @param array|callable $labelTranslationParameters The parameters used to translate the choice labels */ - public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, callable $index = null, callable $groupBy = null, $attr = null, $labelTranslationParameters = []) + public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []) { $preferredViews = []; $preferredViewsOrder = []; diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index 492074286f..50ab6972c0 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -66,7 +66,7 @@ public function getDecoratedFactory() * * @return ChoiceListInterface The choice list */ - public function createListFromChoices(iterable $choices, $value = null, $filter = null) + public function createListFromChoices(iterable $choices, callable|string|PropertyPath $value = null, callable|string|PropertyPath $filter = null) { if (\is_string($value)) { $value = new PropertyPath($value); @@ -107,7 +107,7 @@ public function createListFromChoices(iterable $choices, $value = null, $filter * * @return ChoiceListInterface The choice list */ - public function createListFromLoader(ChoiceLoaderInterface $loader, $value = null, $filter = null) + public function createListFromLoader(ChoiceLoaderInterface $loader, callable|string|PropertyPath $value = null, callable|string|PropertyPath $filter = null) { if (\is_string($value)) { $value = new PropertyPath($value); @@ -150,7 +150,7 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, $value = nul * * @return ChoiceListView The choice list view */ - public function createView(ChoiceListInterface $list, $preferredChoices = null, $label = null, $index = null, $groupBy = null, $attr = null, $labelTranslationParameters = []) + public function createView(ChoiceListInterface $list, array|callable|string|PropertyPath $preferredChoices = null, callable|false|string|PropertyPath $label = null, callable|string|PropertyPath $index = null, callable|string|PropertyPath $groupBy = null, array|callable|string|PropertyPath $attr = null, array|callable|string|PropertyPath $labelTranslationParameters = []) { $accessor = $this->propertyAccessor; diff --git a/ChoiceList/View/ChoiceView.php b/ChoiceList/View/ChoiceView.php index e1d8ac92d8..a98dd79541 100644 --- a/ChoiceList/View/ChoiceView.php +++ b/ChoiceList/View/ChoiceView.php @@ -43,7 +43,7 @@ class ChoiceView * @param array $attr Additional attributes for the HTML tag * @param array $labelTranslationParameters Additional parameters used to translate the label */ - public function __construct($data, string $value, $label, array $attr = [], array $labelTranslationParameters = []) + public function __construct(mixed $data, string $value, string|TranslatableMessage|false $label, array $attr = [], array $labelTranslationParameters = []) { $this->data = $data; $this->value = $value; diff --git a/Console/Descriptor/Descriptor.php b/Console/Descriptor/Descriptor.php index 4aceafbe69..50a9351fbe 100644 --- a/Console/Descriptor/Descriptor.php +++ b/Console/Descriptor/Descriptor.php @@ -43,7 +43,7 @@ abstract class Descriptor implements DescriptorInterface /** * {@inheritdoc} */ - public function describe(OutputInterface $output, $object, array $options = []) + public function describe(OutputInterface $output, ?object $object, array $options = []) { $this->output = $output instanceof OutputStyle ? $output : new SymfonyStyle(new ArrayInput([]), $output); diff --git a/DataAccessorInterface.php b/DataAccessorInterface.php index d128dde074..9a27cfc39a 100644 --- a/DataAccessorInterface.php +++ b/DataAccessorInterface.php @@ -21,25 +21,18 @@ interface DataAccessorInterface /** * Returns the value at the end of the property of the object graph. * - * @param object|array $viewData The view data of the compound form - * @param FormInterface $form The {@link FormInterface()} instance to check - * * @return mixed The value at the end of the property * * @throws Exception\AccessException If unable to read from the given form data */ - public function getValue($viewData, FormInterface $form); + public function getValue(object|array $viewData, FormInterface $form); /** * Sets the value at the end of the property of the object graph. * - * @param object|array $viewData The view data of the compound form - * @param mixed $value The value to set at the end of the object graph - * @param FormInterface $form The {@link FormInterface()} instance to check - * * @throws Exception\AccessException If unable to write the given value */ - public function setValue(&$viewData, $value, FormInterface $form): void; + public function setValue(object|array &$viewData, mixed $value, FormInterface $form): void; /** * Returns whether a value can be read from an object graph. @@ -47,12 +40,9 @@ public function setValue(&$viewData, $value, FormInterface $form): void; * Whenever this method returns true, {@link getValue()} is guaranteed not * to throw an exception when called with the same arguments. * - * @param object|array $viewData The view data of the compound form - * @param FormInterface $form The {@link FormInterface()} instance to check - * * @return bool Whether the value can be read */ - public function isReadable($viewData, FormInterface $form): bool; + public function isReadable(object|array $viewData, FormInterface $form): bool; /** * Returns whether a value can be written at a given object graph. @@ -60,10 +50,7 @@ public function isReadable($viewData, FormInterface $form): bool; * Whenever this method returns true, {@link setValue()} is guaranteed not * to throw an exception when called with the same arguments. * - * @param object|array $viewData The view data of the compound form - * @param FormInterface $form The {@link FormInterface()} instance to check - * * @return bool Whether the value can be set */ - public function isWritable($viewData, FormInterface $form): bool; + public function isWritable(object|array $viewData, FormInterface $form): bool; } diff --git a/DataMapperInterface.php b/DataMapperInterface.php index c2cd3601e4..b668de3f35 100644 --- a/DataMapperInterface.php +++ b/DataMapperInterface.php @@ -27,7 +27,7 @@ interface DataMapperInterface * * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported */ - public function mapDataToForms($viewData, \Traversable $forms); + public function mapDataToForms(mixed $viewData, \Traversable $forms); /** * Maps the model data of a list of children forms into the view data of their parent. @@ -58,5 +58,5 @@ public function mapDataToForms($viewData, \Traversable $forms); * * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported */ - public function mapFormsToData(\Traversable $forms, &$viewData); + public function mapFormsToData(\Traversable $forms, mixed &$viewData); } diff --git a/DataTransformerInterface.php b/DataTransformerInterface.php index e5ac599294..7dd07db70a 100644 --- a/DataTransformerInterface.php +++ b/DataTransformerInterface.php @@ -59,7 +59,7 @@ interface DataTransformerInterface * * @throws TransformationFailedException when the transformation fails */ - public function transform($value); + public function transform(mixed $value); /** * Transforms a value from the transformed representation to its original @@ -88,5 +88,5 @@ public function transform($value); * * @throws TransformationFailedException when the transformation fails */ - public function reverseTransform($value); + public function reverseTransform(mixed $value); } diff --git a/Exception/UnexpectedTypeException.php b/Exception/UnexpectedTypeException.php index d25d4705fa..7a4dc295c6 100644 --- a/Exception/UnexpectedTypeException.php +++ b/Exception/UnexpectedTypeException.php @@ -13,7 +13,7 @@ class UnexpectedTypeException extends InvalidArgumentException { - public function __construct($value, string $expectedType) + public function __construct(mixed $value, string $expectedType) { parent::__construct(sprintf('Expected argument of type "%s", "%s" given', $expectedType, get_debug_type($value))); } diff --git a/Extension/Core/DataAccessor/CallbackAccessor.php b/Extension/Core/DataAccessor/CallbackAccessor.php index fb121450a4..5dccf0a0fe 100644 --- a/Extension/Core/DataAccessor/CallbackAccessor.php +++ b/Extension/Core/DataAccessor/CallbackAccessor.php @@ -25,7 +25,7 @@ class CallbackAccessor implements DataAccessorInterface /** * {@inheritdoc} */ - public function getValue($data, FormInterface $form) + public function getValue(object|array $data, FormInterface $form) { if (null === $getter = $form->getConfig()->getOption('getter')) { throw new AccessException('Unable to read from the given form data as no getter is defined.'); @@ -37,7 +37,7 @@ public function getValue($data, FormInterface $form) /** * {@inheritdoc} */ - public function setValue(&$data, $value, FormInterface $form): void + public function setValue(object|array &$data, mixed $value, FormInterface $form): void { if (null === $setter = $form->getConfig()->getOption('setter')) { throw new AccessException('Unable to write the given value as no setter is defined.'); @@ -49,7 +49,7 @@ public function setValue(&$data, $value, FormInterface $form): void /** * {@inheritdoc} */ - public function isReadable($data, FormInterface $form): bool + public function isReadable(object|array $data, FormInterface $form): bool { return null !== $form->getConfig()->getOption('getter'); } @@ -57,7 +57,7 @@ public function isReadable($data, FormInterface $form): bool /** * {@inheritdoc} */ - public function isWritable($data, FormInterface $form): bool + public function isWritable(object|array $data, FormInterface $form): bool { return null !== $form->getConfig()->getOption('setter'); } diff --git a/Extension/Core/DataAccessor/ChainAccessor.php b/Extension/Core/DataAccessor/ChainAccessor.php index 39e444bb7b..dfd7907c8e 100644 --- a/Extension/Core/DataAccessor/ChainAccessor.php +++ b/Extension/Core/DataAccessor/ChainAccessor.php @@ -33,7 +33,7 @@ public function __construct(iterable $accessors) /** * {@inheritdoc} */ - public function getValue($data, FormInterface $form) + public function getValue(object|array $data, FormInterface $form) { foreach ($this->accessors as $accessor) { if ($accessor->isReadable($data, $form)) { @@ -47,7 +47,7 @@ public function getValue($data, FormInterface $form) /** * {@inheritdoc} */ - public function setValue(&$data, $value, FormInterface $form): void + public function setValue(object|array &$data, mixed $value, FormInterface $form): void { foreach ($this->accessors as $accessor) { if ($accessor->isWritable($data, $form)) { @@ -63,7 +63,7 @@ public function setValue(&$data, $value, FormInterface $form): void /** * {@inheritdoc} */ - public function isReadable($data, FormInterface $form): bool + public function isReadable(object|array $data, FormInterface $form): bool { foreach ($this->accessors as $accessor) { if ($accessor->isReadable($data, $form)) { @@ -77,7 +77,7 @@ public function isReadable($data, FormInterface $form): bool /** * {@inheritdoc} */ - public function isWritable($data, FormInterface $form): bool + public function isWritable(object|array $data, FormInterface $form): bool { foreach ($this->accessors as $accessor) { if ($accessor->isWritable($data, $form)) { diff --git a/Extension/Core/DataAccessor/PropertyPathAccessor.php b/Extension/Core/DataAccessor/PropertyPathAccessor.php index bd1c382151..e8ff3e0c08 100644 --- a/Extension/Core/DataAccessor/PropertyPathAccessor.php +++ b/Extension/Core/DataAccessor/PropertyPathAccessor.php @@ -18,6 +18,7 @@ use Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; +use Symfony\Component\PropertyAccess\PropertyPathInterface; /** * Writes and reads values to/from an object or array using property path. @@ -37,7 +38,7 @@ public function __construct(PropertyAccessorInterface $propertyAccessor = null) /** * {@inheritdoc} */ - public function getValue($data, FormInterface $form) + public function getValue(object|array $data, FormInterface $form) { if (null === $propertyPath = $form->getPropertyPath()) { throw new AccessException('Unable to read from the given form data as no property path is defined.'); @@ -49,7 +50,7 @@ public function getValue($data, FormInterface $form) /** * {@inheritdoc} */ - public function setValue(&$data, $propertyValue, FormInterface $form): void + public function setValue(object|array &$data, mixed $value, FormInterface $form): void { if (null === $propertyPath = $form->getPropertyPath()) { throw new AccessException('Unable to write the given value as no property path is defined.'); @@ -57,21 +58,21 @@ public function setValue(&$data, $propertyValue, FormInterface $form): void // If the field is of type DateTimeInterface and the data is the same skip the update to // keep the original object hash - if ($propertyValue instanceof \DateTimeInterface && $propertyValue == $this->getPropertyValue($data, $propertyPath)) { + if ($value instanceof \DateTimeInterface && $value == $this->getPropertyValue($data, $propertyPath)) { return; } // If the data is identical to the value in $data, we are // dealing with a reference - if (!\is_object($data) || !$form->getConfig()->getByReference() || $propertyValue !== $this->getPropertyValue($data, $propertyPath)) { - $this->propertyAccessor->setValue($data, $propertyPath, $propertyValue); + if (!\is_object($data) || !$form->getConfig()->getByReference() || $value !== $this->getPropertyValue($data, $propertyPath)) { + $this->propertyAccessor->setValue($data, $propertyPath, $value); } } /** * {@inheritdoc} */ - public function isReadable($data, FormInterface $form): bool + public function isReadable(object|array $data, FormInterface $form): bool { return null !== $form->getPropertyPath(); } @@ -79,12 +80,12 @@ public function isReadable($data, FormInterface $form): bool /** * {@inheritdoc} */ - public function isWritable($data, FormInterface $form): bool + public function isWritable(object|array $data, FormInterface $form): bool { return null !== $form->getPropertyPath(); } - private function getPropertyValue($data, $propertyPath) + private function getPropertyValue(object|array $data, PropertyPathInterface $propertyPath) { try { return $this->propertyAccessor->getValue($data, $propertyPath); diff --git a/Extension/Core/DataMapper/CheckboxListMapper.php b/Extension/Core/DataMapper/CheckboxListMapper.php index a6014d7076..64240151d4 100644 --- a/Extension/Core/DataMapper/CheckboxListMapper.php +++ b/Extension/Core/DataMapper/CheckboxListMapper.php @@ -28,7 +28,7 @@ class CheckboxListMapper implements DataMapperInterface /** * {@inheritdoc} */ - public function mapDataToForms($choices, \Traversable $checkboxes) + public function mapDataToForms(mixed $choices, \Traversable $checkboxes) { if (null === $choices) { $choices = []; diff --git a/Extension/Core/DataMapper/DataMapper.php b/Extension/Core/DataMapper/DataMapper.php index 1e98740d2e..1665ab3d20 100644 --- a/Extension/Core/DataMapper/DataMapper.php +++ b/Extension/Core/DataMapper/DataMapper.php @@ -38,7 +38,7 @@ public function __construct(DataAccessorInterface $dataAccessor = null) /** * {@inheritdoc} */ - public function mapDataToForms($data, \Traversable $forms): void + public function mapDataToForms(mixed $data, \Traversable $forms): void { $empty = null === $data || [] === $data; diff --git a/Extension/Core/DataMapper/RadioListMapper.php b/Extension/Core/DataMapper/RadioListMapper.php index 11f54a9cd2..afdacf6528 100644 --- a/Extension/Core/DataMapper/RadioListMapper.php +++ b/Extension/Core/DataMapper/RadioListMapper.php @@ -28,7 +28,7 @@ class RadioListMapper implements DataMapperInterface /** * {@inheritdoc} */ - public function mapDataToForms($choice, \Traversable $radios) + public function mapDataToForms(mixed $choice, \Traversable $radios) { if (!\is_string($choice)) { throw new UnexpectedTypeException($choice, 'string'); diff --git a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php index f79920971c..0d9aaf0564 100644 --- a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php +++ b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php @@ -26,7 +26,7 @@ public function __construct(array $partMapping) $this->partMapping = $partMapping; } - public function transform($array) + public function transform(mixed $array) { if (null === $array) { $array = []; @@ -49,7 +49,7 @@ public function transform($array) return $result; } - public function reverseTransform($array) + public function reverseTransform(mixed $array) { if (!\is_array($array)) { throw new TransformationFailedException('Expected an array.'); diff --git a/Extension/Core/DataTransformer/BooleanToStringTransformer.php b/Extension/Core/DataTransformer/BooleanToStringTransformer.php index f4fd09b627..ec93fbe990 100644 --- a/Extension/Core/DataTransformer/BooleanToStringTransformer.php +++ b/Extension/Core/DataTransformer/BooleanToStringTransformer.php @@ -48,7 +48,7 @@ public function __construct(string $trueValue, array $falseValues = [null]) * * @throws TransformationFailedException if the given value is not a Boolean */ - public function transform($value) + public function transform(mixed $value) { if (null === $value) { return null; @@ -70,7 +70,7 @@ public function transform($value) * * @throws TransformationFailedException if the given value is not a string */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (\in_array($value, $this->falseValues, true)) { return false; diff --git a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php index e1feafe62e..f7e13ea6ff 100644 --- a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php +++ b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php @@ -27,12 +27,12 @@ public function __construct(ChoiceListInterface $choiceList) $this->choiceList = $choiceList; } - public function transform($choice) + public function transform(mixed $choice) { return (string) current($this->choiceList->getValuesForChoices([$choice])); } - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null !== $value && !\is_string($value)) { throw new TransformationFailedException('Expected a string or null.'); diff --git a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php index 6c9e4fe9dc..0b40a0fcd8 100644 --- a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php +++ b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php @@ -32,7 +32,7 @@ public function __construct(ChoiceListInterface $choiceList) * * @throws TransformationFailedException if the given value is not an array */ - public function transform($array) + public function transform(mixed $array) { if (null === $array) { return []; @@ -52,7 +52,7 @@ public function transform($array) * or if no matching choice could be * found for some given value */ - public function reverseTransform($array) + public function reverseTransform(mixed $array) { if (null === $array) { return []; diff --git a/Extension/Core/DataTransformer/DataTransformerChain.php b/Extension/Core/DataTransformer/DataTransformerChain.php index 72d1586d49..55de5bdb56 100644 --- a/Extension/Core/DataTransformer/DataTransformerChain.php +++ b/Extension/Core/DataTransformer/DataTransformerChain.php @@ -47,7 +47,7 @@ public function __construct(array $transformers) * * @throws TransformationFailedException */ - public function transform($value) + public function transform(mixed $value) { foreach ($this->transformers as $transformer) { $value = $transformer->transform($value); @@ -71,7 +71,7 @@ public function transform($value) * * @throws TransformationFailedException */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { for ($i = \count($this->transformers) - 1; $i >= 0; --$i) { $value = $this->transformers[$i]->reverseTransform($value); diff --git a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php index bb461bb3b0..3d32a653c4 100644 --- a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php @@ -64,7 +64,7 @@ public function __construct(array $fields = null, bool $pad = false) * * @throws UnexpectedTypeException if the given value is not a \DateInterval instance */ - public function transform($dateInterval) + public function transform(mixed $dateInterval) { if (null === $dateInterval) { return array_intersect_key( @@ -111,7 +111,7 @@ public function transform($dateInterval) * @throws UnexpectedTypeException if the given value is not an array * @throws TransformationFailedException if the value could not be transformed */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php index 8ae0cdb666..9c22416a2a 100644 --- a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php @@ -45,7 +45,7 @@ public function __construct(string $format = 'P%yY%mM%dDT%hH%iM%sS') * * @throws UnexpectedTypeException if the given value is not a \DateInterval instance */ - public function transform($value) + public function transform(mixed $value) { if (null === $value) { return ''; @@ -67,7 +67,7 @@ public function transform($value) * @throws UnexpectedTypeException if the given value is not a string * @throws TransformationFailedException if the date interval could not be parsed */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php b/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php index 0ef9e22139..5726147dbb 100644 --- a/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php @@ -28,7 +28,7 @@ final class DateTimeImmutableToDateTimeTransformer implements DataTransformerInt * * @throws TransformationFailedException If the given value is not a \DateTimeImmutable */ - public function transform($value): ?\DateTime + public function transform(mixed $value): ?\DateTime { if (null === $value) { return null; @@ -48,7 +48,7 @@ public function transform($value): ?\DateTime * * @throws TransformationFailedException If the given value is not a \DateTime */ - public function reverseTransform($value): ?\DateTimeImmutable + public function reverseTransform(mixed $value): ?\DateTimeImmutable { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php index 2a4d10c0e3..1d5cf3e612 100644 --- a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php @@ -54,7 +54,7 @@ public function __construct(string $inputTimezone = null, string $outputTimezone * * @throws TransformationFailedException If the given value is not a \DateTimeInterface */ - public function transform($dateTime) + public function transform(mixed $dateTime) { if (null === $dateTime) { return array_intersect_key([ @@ -110,7 +110,7 @@ public function transform($dateTime) * @throws TransformationFailedException If the given value is not an array, * if the value could not be transformed */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php index 3b2123bd96..1c2d1313cb 100644 --- a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php @@ -36,7 +36,7 @@ class DateTimeToHtml5LocalDateTimeTransformer extends BaseDateTimeTransformer * @throws TransformationFailedException If the given value is not an * instance of \DateTime or \DateTimeInterface */ - public function transform($dateTime) + public function transform(mixed $dateTime) { if (null === $dateTime) { return ''; @@ -71,7 +71,7 @@ public function transform($dateTime) * @throws TransformationFailedException If the given value is not a string, * if the value could not be transformed */ - public function reverseTransform($dateTimeLocal) + public function reverseTransform(mixed $dateTimeLocal) { if (!\is_string($dateTimeLocal)) { throw new TransformationFailedException('Expected a string.'); diff --git a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php index 5dd5b498c6..b1248e4858 100644 --- a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php @@ -75,7 +75,7 @@ public function __construct(string $inputTimezone = null, string $outputTimezone * @throws TransformationFailedException if the given value is not a \DateTimeInterface * or if the date could not be transformed */ - public function transform($dateTime) + public function transform(mixed $dateTime) { if (null === $dateTime) { return ''; @@ -104,7 +104,7 @@ public function transform($dateTime) * @throws TransformationFailedException if the given value is not a string, * if the date could not be parsed */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (!\is_string($value)) { throw new TransformationFailedException('Expected a string.'); diff --git a/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php b/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php index a3437b895f..a35d06aac5 100644 --- a/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php +++ b/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php @@ -27,7 +27,7 @@ class DateTimeToRfc3339Transformer extends BaseDateTimeTransformer * * @throws TransformationFailedException If the given value is not a \DateTimeInterface */ - public function transform($dateTime) + public function transform(mixed $dateTime) { if (null === $dateTime) { return ''; @@ -58,7 +58,7 @@ public function transform($dateTime) * @throws TransformationFailedException If the given value is not a string, * if the value could not be transformed */ - public function reverseTransform($rfc3339) + public function reverseTransform(mixed $rfc3339) { if (!\is_string($rfc3339)) { throw new TransformationFailedException('Expected a string.'); diff --git a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php index d27a8ff6c4..ee691f41ee 100644 --- a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php @@ -77,7 +77,7 @@ public function __construct(string $inputTimezone = null, string $outputTimezone * * @throws TransformationFailedException If the given value is not a \DateTimeInterface */ - public function transform($dateTime) + public function transform(mixed $dateTime) { if (null === $dateTime) { return ''; @@ -106,7 +106,7 @@ public function transform($dateTime) * @throws TransformationFailedException If the given value is not a string, * or could not be transformed */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (empty($value)) { return null; diff --git a/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php b/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php index 5a52038650..11ba01abb7 100644 --- a/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php @@ -30,7 +30,7 @@ class DateTimeToTimestampTransformer extends BaseDateTimeTransformer * * @throws TransformationFailedException If the given value is not a \DateTimeInterface */ - public function transform($dateTime) + public function transform(mixed $dateTime) { if (null === $dateTime) { return null; @@ -53,7 +53,7 @@ public function transform($dateTime) * @throws TransformationFailedException If the given value is not a timestamp * or if the given timestamp is invalid */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php index 6dfccdfd3d..407c4aa4e2 100644 --- a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php @@ -31,7 +31,7 @@ public function __construct(bool $multiple = false) /** * {@inheritdoc} */ - public function transform($dateTimeZone) + public function transform(mixed $dateTimeZone) { if (null === $dateTimeZone) { return null; @@ -55,7 +55,7 @@ public function transform($dateTimeZone) /** * {@inheritdoc} */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php index 2439e676c7..04c20b54ee 100644 --- a/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php @@ -36,7 +36,7 @@ public function __construct(?bool $grouping = false, ?int $roundingMode = \Numbe /** * {@inheritdoc} */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { $decimalSeparator = $this->getNumberFormatter()->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL); @@ -52,7 +52,7 @@ public function reverseTransform($value) /** * @internal */ - protected function castParsedValue($value) + protected function castParsedValue(int|float $value): int|float { return $value; } diff --git a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php index aa4629f2ef..afc7e9d662 100644 --- a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php @@ -31,7 +31,7 @@ public function __construct(bool $multiple = false) /** * {@inheritdoc} */ - public function transform($intlTimeZone) + public function transform(mixed $intlTimeZone) { if (null === $intlTimeZone) { return null; @@ -55,7 +55,7 @@ public function transform($intlTimeZone) /** * {@inheritdoc} */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null === $value) { return; diff --git a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php index 2cd4688b01..7f79ebc38b 100644 --- a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php @@ -52,7 +52,7 @@ public function __construct(?int $scale = 2, ?bool $grouping = true, ?int $round * @throws TransformationFailedException if the given value is not numeric or * if the value can not be transformed */ - public function transform($value) + public function transform(mixed $value) { if (null !== $value && 1 !== $this->divisor) { if (!is_numeric($value)) { @@ -74,7 +74,7 @@ public function transform($value) * @throws TransformationFailedException if the given value is not a string * or if the value can not be transformed */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { $value = parent::reverseTransform($value); if (null !== $value && 1 !== $this->divisor) { diff --git a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index cbf1da1618..9a215b47e2 100644 --- a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -56,7 +56,7 @@ public function __construct(int $scale = null, ?bool $grouping = false, ?int $ro * @throws TransformationFailedException if the given value is not numeric * or if the value can not be transformed */ - public function transform($value) + public function transform(mixed $value) { if (null === $value) { return ''; @@ -89,7 +89,7 @@ public function transform($value) * @throws TransformationFailedException if the given value is not a string * or if the value can not be transformed */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null !== $value && !\is_string($value)) { throw new TransformationFailedException('Expected a string.'); @@ -182,7 +182,7 @@ protected function getNumberFormatter() /** * @internal */ - protected function castParsedValue($value) + protected function castParsedValue(int|float $value): int|float { if (\is_int($value) && $value === (int) $float = (float) $value) { return $float; @@ -193,12 +193,8 @@ protected function castParsedValue($value) /** * Rounds a number according to the configured scale and rounding mode. - * - * @param int|float $number A number - * - * @return int|float The rounded number */ - private function round($number) + private function round(int|float $number): int|float { if (null !== $this->scale && null !== $this->roundingMode) { // shift number to maintain the correct scale during rounding diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index 92ef2e299b..960201bd91 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -76,7 +76,7 @@ public function __construct(int $scale = null, string $type = null, int $roundin * @throws TransformationFailedException if the given value is not numeric or * if the value could not be transformed */ - public function transform($value) + public function transform(mixed $value) { if (null === $value) { return ''; @@ -111,7 +111,7 @@ public function transform($value) * @throws TransformationFailedException if the given value is not a string or * if the value could not be transformed */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (!\is_string($value)) { throw new TransformationFailedException('Expected a string.'); diff --git a/Extension/Core/DataTransformer/StringToFloatTransformer.php b/Extension/Core/DataTransformer/StringToFloatTransformer.php index 27e60b4306..da50887cc5 100644 --- a/Extension/Core/DataTransformer/StringToFloatTransformer.php +++ b/Extension/Core/DataTransformer/StringToFloatTransformer.php @@ -28,7 +28,7 @@ public function __construct(int $scale = null) * * @return float|null */ - public function transform($value) + public function transform(mixed $value) { if (null === $value) { return null; @@ -46,7 +46,7 @@ public function transform($value) * * @return string|null */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/UlidToStringTransformer.php b/Extension/Core/DataTransformer/UlidToStringTransformer.php index ea3fdec341..242db09099 100644 --- a/Extension/Core/DataTransformer/UlidToStringTransformer.php +++ b/Extension/Core/DataTransformer/UlidToStringTransformer.php @@ -31,7 +31,7 @@ class UlidToStringTransformer implements DataTransformerInterface * * @throws TransformationFailedException If the given value is not a Ulid object */ - public function transform($value) + public function transform(mixed $value) { if (null === $value) { return null; @@ -54,7 +54,7 @@ public function transform($value) * @throws TransformationFailedException If the given value is not a string, * or could not be transformed */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null === $value || '' === $value) { return null; diff --git a/Extension/Core/DataTransformer/UuidToStringTransformer.php b/Extension/Core/DataTransformer/UuidToStringTransformer.php index a019847ae4..a992967d5f 100644 --- a/Extension/Core/DataTransformer/UuidToStringTransformer.php +++ b/Extension/Core/DataTransformer/UuidToStringTransformer.php @@ -31,7 +31,7 @@ class UuidToStringTransformer implements DataTransformerInterface * * @throws TransformationFailedException If the given value is not a Uuid object */ - public function transform($value) + public function transform(mixed $value) { if (null === $value) { return null; @@ -54,7 +54,7 @@ public function transform($value) * @throws TransformationFailedException If the given value is not a string, * or could not be transformed */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null === $value || '' === $value) { return null; diff --git a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php index 4f04645eb7..3bd7419c71 100644 --- a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php +++ b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php @@ -29,11 +29,9 @@ public function __construct(array $keys) /** * Duplicates the given value through the array. * - * @param mixed $value The value - * * @return array The array */ - public function transform($value) + public function transform(mixed $value) { $result = []; @@ -47,12 +45,10 @@ public function transform($value) /** * Extracts the duplicated value from an array. * - * @return mixed The value - * * @throws TransformationFailedException if the given value is not an array or * if the given array can not be transformed */ - public function reverseTransform($array) + public function reverseTransform(mixed $array) { if (!\is_array($array)) { throw new TransformationFailedException('Expected an array.'); diff --git a/Extension/Core/DataTransformer/WeekToArrayTransformer.php b/Extension/Core/DataTransformer/WeekToArrayTransformer.php index 37405998fa..3c4d480721 100644 --- a/Extension/Core/DataTransformer/WeekToArrayTransformer.php +++ b/Extension/Core/DataTransformer/WeekToArrayTransformer.php @@ -31,7 +31,7 @@ class WeekToArrayTransformer implements DataTransformerInterface * @throws TransformationFailedException If the given value is not a string, * or if the given value does not follow the right format */ - public function transform($value) + public function transform(mixed $value) { if (null === $value) { return ['year' => null, 'week' => null]; @@ -61,7 +61,7 @@ public function transform($value) * @throws TransformationFailedException If the given value can not be merged in a valid week date string, * or if the obtained week date does not exists */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { if (null === $value || [] === $value) { return null; diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index 813456b95e..940ce39203 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -31,12 +31,7 @@ class ResizeFormListener implements EventSubscriberInterface private $deleteEmpty; - /** - * @param bool $allowAdd Whether children could be added to the group - * @param bool $allowDelete Whether children could be removed from the group - * @param bool|callable $deleteEmpty - */ - public function __construct(string $type, array $options = [], bool $allowAdd = false, bool $allowDelete = false, $deleteEmpty = false) + public function __construct(string $type, array $options = [], bool $allowAdd = false, bool $allowDelete = false, bool|callable $deleteEmpty = false) { $this->type = $type; $this->allowAdd = $allowAdd; diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index 6868afc562..ab9413a563 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -210,10 +210,8 @@ private static function getMaxFilesize() * (i.e. try "MB", then "kB", then "bytes"). * * This method should be kept in sync with Symfony\Component\Validator\Constraints\FileValidator::factorizeSizes(). - * - * @param int|float $limit */ - private function factorizeSizes(int $size, $limit) + private function factorizeSizes(int $size, int|float $limit) { $coef = self::MIB_BYTES; $coefFactor = self::KIB_BYTES; diff --git a/Extension/Core/Type/TextType.php b/Extension/Core/Type/TextType.php index 9b3c59db85..11e63f59be 100644 --- a/Extension/Core/Type/TextType.php +++ b/Extension/Core/Type/TextType.php @@ -51,7 +51,7 @@ public function getBlockPrefix() /** * {@inheritdoc} */ - public function transform($data) + public function transform(mixed $data) { // Model data should not be transformed return $data; @@ -60,7 +60,7 @@ public function transform($data) /** * {@inheritdoc} */ - public function reverseTransform($data) + public function reverseTransform(mixed $data) { return null === $data ? '' : $data; } diff --git a/Extension/HttpFoundation/HttpFoundationRequestHandler.php b/Extension/HttpFoundation/HttpFoundationRequestHandler.php index 05503ff529..c62932cee5 100644 --- a/Extension/HttpFoundation/HttpFoundationRequestHandler.php +++ b/Extension/HttpFoundation/HttpFoundationRequestHandler.php @@ -38,7 +38,7 @@ public function __construct(ServerParams $serverParams = null) /** * {@inheritdoc} */ - public function handleRequest(FormInterface $form, $request = null) + public function handleRequest(FormInterface $form, mixed $request = null) { if (!$request instanceof Request) { throw new UnexpectedTypeException($request, 'Symfony\Component\HttpFoundation\Request'); @@ -112,7 +112,7 @@ public function handleRequest(FormInterface $form, $request = null) /** * {@inheritdoc} */ - public function isFileUpload($data) + public function isFileUpload(mixed $data) { return $data instanceof File; } @@ -120,7 +120,7 @@ public function isFileUpload($data) /** * @return int|null */ - public function getUploadFileError($data) + public function getUploadFileError(mixed $data) { if (!$data instanceof UploadedFile || $data->isValid()) { return null; diff --git a/Extension/Validator/Constraints/FormValidator.php b/Extension/Validator/Constraints/FormValidator.php index d14055f16c..c669d56b87 100644 --- a/Extension/Validator/Constraints/FormValidator.php +++ b/Extension/Validator/Constraints/FormValidator.php @@ -29,7 +29,7 @@ class FormValidator extends ConstraintValidator /** * {@inheritdoc} */ - public function validate($form, Constraint $formConstraint) + public function validate(mixed $form, Constraint $formConstraint) { if (!$formConstraint instanceof Form) { throw new UnexpectedTypeException($formConstraint, Form::class); @@ -246,7 +246,7 @@ private function getValidationGroups(FormInterface $form) * * @return GroupSequence|array The validation groups */ - private static function resolveValidationGroups($groups, FormInterface $form) + private static function resolveValidationGroups(string|GroupSequence|array|callable $groups, FormInterface $form): GroupSequence|array { if (!\is_string($groups) && \is_callable($groups)) { $groups = $groups($form); @@ -259,10 +259,18 @@ private static function resolveValidationGroups($groups, FormInterface $form) return (array) $groups; } - private static function getConstraintsInGroups($constraints, $group) + private static function getConstraintsInGroups(array $constraints, string|array $group): array { - return array_filter($constraints, static function (Constraint $constraint) use ($group) { - return \in_array($group, $constraint->groups, true); + $groups = (array) $group; + + return array_filter($constraints, static function (Constraint $constraint) use ($groups) { + foreach ($groups as $group) { + if (\in_array($group, $constraint->groups, true)) { + return true; + } + } + + return false; }); } } diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index 97e16caea8..72b98f5451 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -259,7 +259,7 @@ public function guessPatternForConstraint(Constraint $constraint) * * @return Guess|null The guessed value with the highest confidence */ - protected function guess(string $class, string $property, \Closure $closure, $defaultValue = null) + protected function guess(string $class, string $property, \Closure $closure, mixed $defaultValue = null) { $guesses = []; $classMetadata = $this->metadataFactory->getMetadataFor($class); diff --git a/Form.php b/Form.php index 82bd8a660b..985b6a9174 100644 --- a/Form.php +++ b/Form.php @@ -304,7 +304,7 @@ public function isRoot() /** * {@inheritdoc} */ - public function setData($modelData) + public function setData(mixed $modelData) { // If the form is submitted while disabled, it is set to submitted, but the data is not // changed. In such cases (i.e. when the form is not initialized yet) don't @@ -485,7 +485,7 @@ public function initialize() /** * {@inheritdoc} */ - public function handleRequest($request = null) + public function handleRequest(mixed $request = null) { $this->config->getRequestHandler()->handleRequest($this, $request); @@ -495,7 +495,7 @@ public function handleRequest($request = null) /** * {@inheritdoc} */ - public function submit($submittedData, bool $clearMissing = true) + public function submit(mixed $submittedData, bool $clearMissing = true) { if ($this->submitted) { throw new AlreadySubmittedException('A form can only be submitted once.'); @@ -831,7 +831,7 @@ public function all() /** * {@inheritdoc} */ - public function add($child, string $type = null, array $options = []) + public function add(FormInterface|string $child, string $type = null, array $options = []) { if ($this->submitted) { throw new AlreadySubmittedException('You cannot add children to a submitted form.'); @@ -946,7 +946,7 @@ public function get(string $name) * * @return bool */ - public function offsetExists($name) + public function offsetExists(mixed $name) { return $this->has($name); } @@ -960,7 +960,7 @@ public function offsetExists($name) * * @throws OutOfBoundsException if the named child does not exist */ - public function offsetGet($name) + public function offsetGet(mixed $name) { return $this->get($name); } @@ -976,7 +976,7 @@ public function offsetGet($name) * * @see self::add() */ - public function offsetSet($name, $child) + public function offsetSet(mixed $name, mixed $child) { $this->add($child); } @@ -988,7 +988,7 @@ public function offsetSet($name, $child) * * @throws AlreadySubmittedException if the form has already been submitted */ - public function offsetUnset($name) + public function offsetUnset(mixed $name) { $this->remove($name); } @@ -1075,7 +1075,7 @@ private function sort(array &$children): void * * @throws TransformationFailedException If the underlying data cannot be transformed to "normalized" format */ - private function modelToNorm($value) + private function modelToNorm(mixed $value) { try { foreach ($this->config->getModelTransformers() as $transformer) { @@ -1095,7 +1095,7 @@ private function modelToNorm($value) * * @throws TransformationFailedException If the value cannot be transformed to "model" format */ - private function normToModel($value) + private function normToModel(mixed $value) { try { $transformers = $this->config->getModelTransformers(); @@ -1117,7 +1117,7 @@ private function normToModel($value) * * @throws TransformationFailedException If the normalized value cannot be transformed to "view" format */ - private function normToView($value) + private function normToView(mixed $value) { // Scalar values should be converted to strings to // facilitate differentiation between empty ("") and zero (0). @@ -1146,7 +1146,7 @@ private function normToView($value) * * @throws TransformationFailedException If the submitted value cannot be transformed to "normalized" format */ - private function viewToNorm($value) + private function viewToNorm(mixed $value) { if (!$transformers = $this->config->getViewTransformers()) { return '' === $value ? null : $value; diff --git a/FormBuilder.php b/FormBuilder.php index 8c92046ee3..89e959130f 100644 --- a/FormBuilder.php +++ b/FormBuilder.php @@ -47,7 +47,7 @@ public function __construct(?string $name, ?string $dataClass, EventDispatcherIn /** * {@inheritdoc} */ - public function add($child, string $type = null, array $options = []) + public function add(FormBuilderInterface|string $child, string $type = null, array $options = []) { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -80,7 +80,7 @@ public function add($child, string $type = null, array $options = []) /** * {@inheritdoc} */ - public function create($name, string $type = null, array $options = []) + public function create(string $name, string $type = null, array $options = []) { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -100,7 +100,7 @@ public function create($name, string $type = null, array $options = []) /** * {@inheritdoc} */ - public function get($name) + public function get(string $name) { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -120,7 +120,7 @@ public function get($name) /** * {@inheritdoc} */ - public function remove($name) + public function remove(string $name) { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -134,7 +134,7 @@ public function remove($name) /** * {@inheritdoc} */ - public function has($name) + public function has(string $name) { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); diff --git a/FormBuilderInterface.php b/FormBuilderInterface.php index d95a528bb5..e3f5028d60 100644 --- a/FormBuilderInterface.php +++ b/FormBuilderInterface.php @@ -25,12 +25,11 @@ interface FormBuilderInterface extends \Traversable, \Countable, FormConfigBuild * If you add a nested group, this group should also be represented in the * object hierarchy. * - * @param string|FormBuilderInterface $child - * @param array $options + * @param array $options * * @return self */ - public function add($child, string $type = null, array $options = []); + public function add(string|FormBuilderInterface $child, string $type = null, array $options = []); /** * Creates a form builder. diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 69acee4d99..caa5cc0789 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -362,7 +362,7 @@ public function hasAttribute(string $name) /** * {@inheritdoc} */ - public function getAttribute(string $name, $default = null) + public function getAttribute(string $name, mixed $default = null) { return \array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; } @@ -457,7 +457,7 @@ public function hasOption(string $name) /** * {@inheritdoc} */ - public function getOption(string $name, $default = null) + public function getOption(string $name, mixed $default = null) { return \array_key_exists($name, $this->options) ? $this->options[$name] : $default; } @@ -473,7 +473,7 @@ public function getIsEmptyCallback(): ?callable /** * {@inheritdoc} */ - public function setAttribute(string $name, $value) + public function setAttribute(string $name, mixed $value) { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -529,7 +529,7 @@ public function setDisabled(bool $disabled) /** * {@inheritdoc} */ - public function setEmptyData($emptyData) + public function setEmptyData(mixed $emptyData) { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -571,7 +571,7 @@ public function setRequired(bool $required) /** * {@inheritdoc} */ - public function setPropertyPath($propertyPath) + public function setPropertyPath(string|PropertyPathInterface|null $propertyPath) { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -659,7 +659,7 @@ public function setType(ResolvedFormTypeInterface $type) /** * {@inheritdoc} */ - public function setData($data) + public function setData(mixed $data) { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); diff --git a/FormConfigBuilderInterface.php b/FormConfigBuilderInterface.php index fb4a835ba6..05d527480b 100644 --- a/FormConfigBuilderInterface.php +++ b/FormConfigBuilderInterface.php @@ -86,7 +86,7 @@ public function resetModelTransformers(); * * @return $this The configuration object */ - public function setAttribute(string $name, $value); + public function setAttribute(string $name, mixed $value); /** * Sets the attributes. @@ -116,7 +116,7 @@ public function setDisabled(bool $disabled); * * @return $this The configuration object */ - public function setEmptyData($emptyData); + public function setEmptyData(mixed $emptyData); /** * Sets whether errors bubble up to the parent. @@ -140,7 +140,7 @@ public function setRequired(bool $required); * * @return $this The configuration object */ - public function setPropertyPath($propertyPath); + public function setPropertyPath(string|PropertyPathInterface|null $propertyPath); /** * Sets whether the form should be mapped to an element of its @@ -187,7 +187,7 @@ public function setType(ResolvedFormTypeInterface $type); * * @return $this The configuration object */ - public function setData($data); + public function setData(mixed $data); /** * Locks the form's data to the data passed in the configuration. diff --git a/FormConfigInterface.php b/FormConfigInterface.php index e012b780b3..c1ee87d41a 100644 --- a/FormConfigInterface.php +++ b/FormConfigInterface.php @@ -156,11 +156,9 @@ public function hasAttribute(string $name); /** * Returns the value of the given attribute. * - * @param mixed $default The value returned if the attribute does not exist - * * @return mixed The attribute value */ - public function getAttribute(string $name, $default = null); + public function getAttribute(string $name, mixed $default = null); /** * Returns the initial data of the form. @@ -240,11 +238,9 @@ public function hasOption(string $name); /** * Returns the value of a specific option. * - * @param mixed $default The value returned if the option does not exist - * * @return mixed The option value */ - public function getOption(string $name, $default = null); + public function getOption(string $name, mixed $default = null); /** * Returns a callable that takes the model data as argument and that returns if it is empty or not. diff --git a/FormError.php b/FormError.php index 8ea67c4412..8d5c571bfc 100644 --- a/FormError.php +++ b/FormError.php @@ -47,7 +47,7 @@ class FormError * * @see \Symfony\Component\Translation\Translator */ - public function __construct(string $message, string $messageTemplate = null, array $messageParameters = [], int $messagePluralization = null, $cause = null) + public function __construct(string $message, string $messageTemplate = null, array $messageParameters = [], int $messagePluralization = null, mixed $cause = null) { $this->message = $message; $this->messageTemplate = $messageTemplate ?: $message; diff --git a/FormErrorIterator.php b/FormErrorIterator.php index 3943278ac3..dc58ce5d33 100644 --- a/FormErrorIterator.php +++ b/FormErrorIterator.php @@ -142,7 +142,7 @@ public function rewind() * * @return bool Whether that position exists */ - public function offsetExists($position) + public function offsetExists(mixed $position) { return isset($this->errors[$position]); } @@ -156,7 +156,7 @@ public function offsetExists($position) * * @throws OutOfBoundsException If the given position does not exist */ - public function offsetGet($position) + public function offsetGet(mixed $position) { if (!isset($this->errors[$position])) { throw new OutOfBoundsException('The offset '.$position.' does not exist.'); @@ -170,7 +170,7 @@ public function offsetGet($position) * * @throws BadMethodCallException */ - public function offsetSet($position, $value) + public function offsetSet(mixed $position, mixed $value) { throw new BadMethodCallException('The iterator doesn\'t support modification of elements.'); } @@ -180,7 +180,7 @@ public function offsetSet($position, $value) * * @throws BadMethodCallException */ - public function offsetUnset($position) + public function offsetUnset(mixed $position) { throw new BadMethodCallException('The iterator doesn\'t support modification of elements.'); } @@ -229,11 +229,9 @@ public function count() /** * Sets the position of the iterator. * - * @param int $position The new position - * * @throws OutOfBoundsException If the position is invalid */ - public function seek($position) + public function seek(int $position) { if (!isset($this->errors[$position])) { throw new OutOfBoundsException('The offset '.$position.' does not exist.'); @@ -253,7 +251,7 @@ public function seek($position) * * @return static new instance which contains only specific errors */ - public function findByCodes($codes) + public function findByCodes(string|array $codes) { $codes = (array) $codes; $errors = []; diff --git a/FormEvent.php b/FormEvent.php index c466fafdc6..b50e637b05 100644 --- a/FormEvent.php +++ b/FormEvent.php @@ -21,10 +21,7 @@ class FormEvent extends Event private $form; protected $data; - /** - * @param mixed $data The data - */ - public function __construct(FormInterface $form, $data) + public function __construct(FormInterface $form, mixed $data) { $this->form = $form; $this->data = $data; @@ -52,10 +49,8 @@ public function getData() /** * Allows updating with some filtered data. - * - * @param mixed $data */ - public function setData($data) + public function setData(mixed $data) { $this->data = $data; } diff --git a/FormFactory.php b/FormFactory.php index 5e7e807333..d518e2ff15 100644 --- a/FormFactory.php +++ b/FormFactory.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Form; +use Symfony\Component\Form\Extension\Core\Type\FormType; + class FormFactory implements FormFactoryInterface { private $registry; @@ -23,7 +25,7 @@ public function __construct(FormRegistryInterface $registry) /** * {@inheritdoc} */ - public function create(string $type = 'Symfony\Component\Form\Extension\Core\Type\FormType', $data = null, array $options = []) + public function create(string $type = FormType::class, mixed $data = null, array $options = []) { return $this->createBuilder($type, $data, $options)->getForm(); } @@ -31,7 +33,7 @@ public function create(string $type = 'Symfony\Component\Form\Extension\Core\Typ /** * {@inheritdoc} */ - public function createNamed(string $name, string $type = 'Symfony\Component\Form\Extension\Core\Type\FormType', $data = null, array $options = []) + public function createNamed(string $name, string $type = FormType::class, mixed $data = null, array $options = []) { return $this->createNamedBuilder($name, $type, $data, $options)->getForm(); } @@ -39,7 +41,7 @@ public function createNamed(string $name, string $type = 'Symfony\Component\Form /** * {@inheritdoc} */ - public function createForProperty(string $class, string $property, $data = null, array $options = []) + public function createForProperty(string $class, string $property, mixed $data = null, array $options = []) { return $this->createBuilderForProperty($class, $property, $data, $options)->getForm(); } @@ -47,7 +49,7 @@ public function createForProperty(string $class, string $property, $data = null, /** * {@inheritdoc} */ - public function createBuilder(string $type = 'Symfony\Component\Form\Extension\Core\Type\FormType', $data = null, array $options = []) + public function createBuilder(string $type = FormType::class, mixed $data = null, array $options = []) { return $this->createNamedBuilder($this->registry->getType($type)->getBlockPrefix(), $type, $data, $options); } @@ -55,7 +57,7 @@ public function createBuilder(string $type = 'Symfony\Component\Form\Extension\C /** * {@inheritdoc} */ - public function createNamedBuilder(string $name, string $type = 'Symfony\Component\Form\Extension\Core\Type\FormType', $data = null, array $options = []) + public function createNamedBuilder(string $name, string $type = FormType::class, mixed $data = null, array $options = []) { if (null !== $data && !\array_key_exists('data', $options)) { $options['data'] = $data; @@ -75,7 +77,7 @@ public function createNamedBuilder(string $name, string $type = 'Symfony\Compone /** * {@inheritdoc} */ - public function createBuilderForProperty(string $class, string $property, $data = null, array $options = []) + public function createBuilderForProperty(string $class, string $property, mixed $data = null, array $options = []) { if (null === $guesser = $this->registry->getTypeGuesser()) { return $this->createNamedBuilder($property, 'Symfony\Component\Form\Extension\Core\Type\TextType', $data, $options); diff --git a/FormFactoryInterface.php b/FormFactoryInterface.php index 2f1acf5424..77b8309a8f 100644 --- a/FormFactoryInterface.php +++ b/FormFactoryInterface.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Form; +use Symfony\Component\Form\Extension\Core\Type\FormType; + /** * Allows creating a form based on a name, a class or a property. * @@ -29,7 +31,7 @@ interface FormFactoryInterface * * @throws \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException if any given option is not applicable to the given type */ - public function create(string $type = 'Symfony\Component\Form\Extension\Core\Type\FormType', $data = null, array $options = []); + public function create(string $type = FormType::class, mixed $data = null, array $options = []); /** * Returns a form. @@ -42,7 +44,7 @@ public function create(string $type = 'Symfony\Component\Form\Extension\Core\Typ * * @throws \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException if any given option is not applicable to the given type */ - public function createNamed(string $name, string $type = 'Symfony\Component\Form\Extension\Core\Type\FormType', $data = null, array $options = []); + public function createNamed(string $name, string $type = FormType::class, mixed $data = null, array $options = []); /** * Returns a form for a property of a class. @@ -57,7 +59,7 @@ public function createNamed(string $name, string $type = 'Symfony\Component\Form * * @throws \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException if any given option is not applicable to the form type */ - public function createForProperty(string $class, string $property, $data = null, array $options = []); + public function createForProperty(string $class, string $property, mixed $data = null, array $options = []); /** * Returns a form builder. @@ -68,7 +70,7 @@ public function createForProperty(string $class, string $property, $data = null, * * @throws \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException if any given option is not applicable to the given type */ - public function createBuilder(string $type = 'Symfony\Component\Form\Extension\Core\Type\FormType', $data = null, array $options = []); + public function createBuilder(string $type = FormType::class, mixed $data = null, array $options = []); /** * Returns a form builder. @@ -79,7 +81,7 @@ public function createBuilder(string $type = 'Symfony\Component\Form\Extension\C * * @throws \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException if any given option is not applicable to the given type */ - public function createNamedBuilder(string $name, string $type = 'Symfony\Component\Form\Extension\Core\Type\FormType', $data = null, array $options = []); + public function createNamedBuilder(string $name, string $type = FormType::class, mixed $data = null, array $options = []); /** * Returns a form builder for a property of a class. @@ -95,5 +97,5 @@ public function createNamedBuilder(string $name, string $type = 'Symfony\Compone * * @throws \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException if any given option is not applicable to the form type */ - public function createBuilderForProperty(string $class, string $property, $data = null, array $options = []); + public function createBuilderForProperty(string $class, string $property, mixed $data = null, array $options = []); } diff --git a/FormInterface.php b/FormInterface.php index 25e9561d5c..7e8e43bdc9 100644 --- a/FormInterface.php +++ b/FormInterface.php @@ -53,7 +53,7 @@ public function getParent(); * @throws Exception\LogicException when trying to add a child to a non-compound form * @throws Exception\UnexpectedTypeException if $child or $type has an unexpected type */ - public function add($child, string $type = null, array $options = []); + public function add(FormInterface|string $child, string $type = null, array $options = []); /** * Returns the child with the given name. @@ -113,7 +113,7 @@ public function getErrors(bool $deep = false, bool $flatten = true); * the form inherits data from its parent * @throws Exception\TransformationFailedException if the synchronization failed */ - public function setData($modelData); + public function setData(mixed $modelData); /** * Returns the model data in the format needed for the underlying object. @@ -284,11 +284,9 @@ public function initialize(); * {@link RequestHandlerInterface} instance, which determines whether to * submit the form or not. * - * @param mixed $request The request to handle - * * @return $this */ - public function handleRequest($request = null); + public function handleRequest(mixed $request = null); /** * Submits data to the form. @@ -303,7 +301,7 @@ public function handleRequest($request = null); * * @throws Exception\AlreadySubmittedException if the form has already been submitted */ - public function submit($submittedData, bool $clearMissing = true); + public function submit(string|array|null $submittedData, bool $clearMissing = true); /** * Returns the root of the form tree. diff --git a/FormRenderer.php b/FormRenderer.php index 2f8f351990..48f3841f24 100644 --- a/FormRenderer.php +++ b/FormRenderer.php @@ -48,7 +48,7 @@ public function getEngine() /** * {@inheritdoc} */ - public function setTheme(FormView $view, $themes, bool $useDefaultThemes = true) + public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true) { $this->engine->setTheme($view, $themes, $useDefaultThemes); } diff --git a/FormRendererEngineInterface.php b/FormRendererEngineInterface.php index 2dd2a2fc59..9009ba39b2 100644 --- a/FormRendererEngineInterface.php +++ b/FormRendererEngineInterface.php @@ -25,7 +25,7 @@ interface FormRendererEngineInterface * @param mixed $themes The theme(s). The type of these themes * is open to the implementation. */ - public function setTheme(FormView $view, $themes, bool $useDefaultThemes = true); + public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true); /** * Returns the resource for a block name. @@ -132,5 +132,5 @@ public function getResourceHierarchyLevel(FormView $view, array $blockNameHierar * * @return string The HTML markup */ - public function renderBlock(FormView $view, $resource, string $blockName, array $variables = []); + public function renderBlock(FormView $view, mixed $resource, string $blockName, array $variables = []); } diff --git a/FormRendererInterface.php b/FormRendererInterface.php index 16c29744ed..0d0ad72674 100644 --- a/FormRendererInterface.php +++ b/FormRendererInterface.php @@ -34,7 +34,7 @@ public function getEngine(); * @param bool $useDefaultThemes If true, will use default themes specified * in the renderer */ - public function setTheme(FormView $view, $themes, bool $useDefaultThemes = true); + public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true); /** * Renders a named block of the form theme. diff --git a/FormView.php b/FormView.php index 78656b3868..dbe0f61817 100644 --- a/FormView.php +++ b/FormView.php @@ -108,7 +108,7 @@ public function setMethodRendered() * * @return self The child view */ - public function offsetGet($name) + public function offsetGet(mixed $name) { return $this->children[$name]; } @@ -120,7 +120,7 @@ public function offsetGet($name) * * @return bool Whether the child view exists */ - public function offsetExists($name) + public function offsetExists(mixed $name) { return isset($this->children[$name]); } @@ -130,7 +130,7 @@ public function offsetExists($name) * * @throws BadMethodCallException always as setting a child by name is not allowed */ - public function offsetSet($name, $value) + public function offsetSet(mixed $name, mixed $value) { throw new BadMethodCallException('Not supported.'); } @@ -140,7 +140,7 @@ public function offsetSet($name, $value) * * @param string $name The child name */ - public function offsetUnset($name) + public function offsetUnset(mixed $name) { unset($this->children[$name]); } diff --git a/Guess/ValueGuess.php b/Guess/ValueGuess.php index fe19dfeb04..a316a0adad 100644 --- a/Guess/ValueGuess.php +++ b/Guess/ValueGuess.php @@ -21,11 +21,9 @@ class ValueGuess extends Guess private $value; /** - * @param string|int|bool|null $value The guessed value - * @param int $confidence The confidence that the guessed class name - * is correct + * @param int $confidence The confidence that the guessed class name is correct */ - public function __construct($value, int $confidence) + public function __construct(string|int|bool|null $value, int $confidence) { parent::__construct($confidence); diff --git a/NativeRequestHandler.php b/NativeRequestHandler.php index 6b18df44a1..0dba25c659 100644 --- a/NativeRequestHandler.php +++ b/NativeRequestHandler.php @@ -44,7 +44,7 @@ public function __construct(ServerParams $params = null) * * @throws Exception\UnexpectedTypeException If the $request is not null */ - public function handleRequest(FormInterface $form, $request = null) + public function handleRequest(FormInterface $form, mixed $request = null) { if (null !== $request) { throw new UnexpectedTypeException($request, 'null'); @@ -127,7 +127,7 @@ public function handleRequest(FormInterface $form, $request = null) /** * {@inheritdoc} */ - public function isFileUpload($data) + public function isFileUpload(mixed $data) { // POST data will always be strings or arrays of strings. Thus, we can be sure // that the submitted data is a file upload if the "error" value is an integer @@ -138,7 +138,7 @@ public function isFileUpload($data) /** * @return int|null */ - public function getUploadFileError($data) + public function getUploadFileError(mixed $data) { if (!\is_array($data)) { return null; @@ -192,7 +192,7 @@ private static function getRequestMethod(): string * * @return mixed */ - private static function fixPhpFilesArray($data) + private static function fixPhpFilesArray(mixed $data) { if (!\is_array($data)) { return $data; @@ -228,7 +228,7 @@ private static function fixPhpFilesArray($data) * * @return mixed Returns the stripped upload data */ - private static function stripEmptyFiles($data) + private static function stripEmptyFiles(mixed $data) { if (!\is_array($data)) { return $data; diff --git a/RequestHandlerInterface.php b/RequestHandlerInterface.php index 65d86e2246..2cb671df71 100644 --- a/RequestHandlerInterface.php +++ b/RequestHandlerInterface.php @@ -20,17 +20,13 @@ interface RequestHandlerInterface { /** * Submits a form if it was submitted. - * - * @param mixed $request The current request */ - public function handleRequest(FormInterface $form, $request = null); + public function handleRequest(FormInterface $form, mixed $request = null); /** * Returns true if the given data is a file upload. * - * @param mixed $data The form field data - * * @return bool */ - public function isFileUpload($data); + public function isFileUpload(mixed $data); } diff --git a/ReversedTransformer.php b/ReversedTransformer.php index 8089e47bf0..0591c4f3b0 100644 --- a/ReversedTransformer.php +++ b/ReversedTransformer.php @@ -31,7 +31,7 @@ public function __construct(DataTransformerInterface $reversedTransformer) /** * {@inheritdoc} */ - public function transform($value) + public function transform(mixed $value) { return $this->reversedTransformer->reverseTransform($value); } @@ -39,7 +39,7 @@ public function transform($value) /** * {@inheritdoc} */ - public function reverseTransform($value) + public function reverseTransform(mixed $value) { return $this->reversedTransformer->transform($value); } diff --git a/SubmitButton.php b/SubmitButton.php index 5e38b10987..0312e56bd6 100644 --- a/SubmitButton.php +++ b/SubmitButton.php @@ -31,14 +31,11 @@ public function isClicked() /** * Submits data to the button. * - * @param string|null $submittedData The data - * @param bool $clearMissing Not used - * * @return $this * * @throws Exception\AlreadySubmittedException if the form has already been submitted */ - public function submit($submittedData, bool $clearMissing = true) + public function submit(array|string|null $submittedData, bool $clearMissing = true) { if ($this->getConfig()->getDisabled()) { $this->clicked = false; diff --git a/Tests/FormBuilderTest.php b/Tests/FormBuilderTest.php index 69b71bcc77..c937f01954 100644 --- a/Tests/FormBuilderTest.php +++ b/Tests/FormBuilderTest.php @@ -54,12 +54,6 @@ public function testNoSetName() $this->assertFalse(method_exists($this->builder, 'setName')); } - public function testAddNameNoStringAndNoInteger() - { - $this->expectException(UnexpectedTypeException::class); - $this->builder->add(true); - } - public function testAddWithGuessFluent() { $this->builder = new FormBuilder('name', 'stdClass', $this->dispatcher, $this->factory); diff --git a/Tests/VersionAwareTest.php b/Tests/VersionAwareTest.php index c555b2499d..9ab4797b30 100644 --- a/Tests/VersionAwareTest.php +++ b/Tests/VersionAwareTest.php @@ -15,10 +15,7 @@ trait VersionAwareTest { protected static $supportedFeatureSetVersion = 404; - /** - * @param int $requiredFeatureSetVersion - */ - protected function requiresFeatureSet($requiredFeatureSetVersion) + protected function requiresFeatureSet(int $requiredFeatureSetVersion) { if ($requiredFeatureSetVersion > static::$supportedFeatureSetVersion) { $this->markTestSkipped(sprintf('Test requires features from symfony/form %.2f but only version %.2f is supported.', $requiredFeatureSetVersion / 100, static::$supportedFeatureSetVersion / 100)); diff --git a/Util/FormUtil.php b/Util/FormUtil.php index fed96de4fa..9dbbfc7bc7 100644 --- a/Util/FormUtil.php +++ b/Util/FormUtil.php @@ -30,11 +30,9 @@ private function __construct() * a form and needs to be consistent. PHP keyword `empty` cannot * be used as it also considers 0 and "0" to be empty. * - * @param mixed $data - * * @return bool */ - public static function isEmpty($data) + public static function isEmpty(mixed $data) { // Should not do a check for [] === $data!!! // This method is used in occurrences where arrays are diff --git a/Util/OptionsResolverWrapper.php b/Util/OptionsResolverWrapper.php index b5f29ac510..03a90cda7f 100644 --- a/Util/OptionsResolverWrapper.php +++ b/Util/OptionsResolverWrapper.php @@ -41,7 +41,7 @@ public function setNormalizer(string $option, \Closure $normalizer): self /** * @return $this */ - public function setAllowedValues(string $option, $allowedValues): self + public function setAllowedValues(string $option, mixed $allowedValues): self { try { parent::setAllowedValues($option, $allowedValues); @@ -55,7 +55,7 @@ public function setAllowedValues(string $option, $allowedValues): self /** * @return $this */ - public function addAllowedValues(string $option, $allowedValues): self + public function addAllowedValues(string $option, mixed $allowedValues): self { try { parent::addAllowedValues($option, $allowedValues); @@ -67,6 +67,8 @@ public function addAllowedValues(string $option, $allowedValues): self } /** + * @param string|array $allowedTypes + * * @return $this */ public function setAllowedTypes(string $option, $allowedTypes): self @@ -81,6 +83,8 @@ public function setAllowedTypes(string $option, $allowedTypes): self } /** + * @param string|array $allowedTypes + * * @return $this */ public function addAllowedTypes(string $option, $allowedTypes): self diff --git a/Util/OrderedHashMap.php b/Util/OrderedHashMap.php index 6d758ca91c..b8b1bf5e83 100644 --- a/Util/OrderedHashMap.php +++ b/Util/OrderedHashMap.php @@ -101,7 +101,7 @@ public function __construct(array $elements = []) /** * @return bool */ - public function offsetExists($key) + public function offsetExists(mixed $key) { return isset($this->elements[$key]); } @@ -109,7 +109,7 @@ public function offsetExists($key) /** * {@inheritdoc} */ - public function offsetGet($key) + public function offsetGet(mixed $key) { if (!isset($this->elements[$key])) { throw new \OutOfBoundsException(sprintf('The offset "%s" does not exist.', $key)); @@ -121,7 +121,7 @@ public function offsetGet($key) /** * {@inheritdoc} */ - public function offsetSet($key, $value) + public function offsetSet(mixed $key, mixed $value) { if (null === $key || !isset($this->elements[$key])) { if (null === $key) { @@ -142,7 +142,7 @@ public function offsetSet($key, $value) /** * {@inheritdoc} */ - public function offsetUnset($key) + public function offsetUnset(mixed $key) { if (false !== ($position = array_search((string) $key, $this->orderedKeys))) { array_splice($this->orderedKeys, $position, 1); From f90ea59905febc4d8bcfb1dff1eb9262a64d5d05 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 7 Jul 2021 15:44:05 +0200 Subject: [PATCH 013/208] Add some more union types --- Extension/Core/DataMapper/CheckboxListMapper.php | 2 +- Extension/Core/DataMapper/DataMapper.php | 2 +- Extension/Core/DataMapper/RadioListMapper.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Extension/Core/DataMapper/CheckboxListMapper.php b/Extension/Core/DataMapper/CheckboxListMapper.php index 64240151d4..9ded60e830 100644 --- a/Extension/Core/DataMapper/CheckboxListMapper.php +++ b/Extension/Core/DataMapper/CheckboxListMapper.php @@ -47,7 +47,7 @@ public function mapDataToForms(mixed $choices, \Traversable $checkboxes) /** * {@inheritdoc} */ - public function mapFormsToData(\Traversable $checkboxes, &$choices) + public function mapFormsToData(\Traversable $checkboxes, mixed &$choices) { if (!\is_array($choices)) { throw new UnexpectedTypeException($choices, 'array'); diff --git a/Extension/Core/DataMapper/DataMapper.php b/Extension/Core/DataMapper/DataMapper.php index 1665ab3d20..2b8f98f701 100644 --- a/Extension/Core/DataMapper/DataMapper.php +++ b/Extension/Core/DataMapper/DataMapper.php @@ -60,7 +60,7 @@ public function mapDataToForms(mixed $data, \Traversable $forms): void /** * {@inheritdoc} */ - public function mapFormsToData(\Traversable $forms, &$data): void + public function mapFormsToData(\Traversable $forms, mixed &$data): void { if (null === $data) { return; diff --git a/Extension/Core/DataMapper/RadioListMapper.php b/Extension/Core/DataMapper/RadioListMapper.php index afdacf6528..ebf761c4dd 100644 --- a/Extension/Core/DataMapper/RadioListMapper.php +++ b/Extension/Core/DataMapper/RadioListMapper.php @@ -43,7 +43,7 @@ public function mapDataToForms(mixed $choice, \Traversable $radios) /** * {@inheritdoc} */ - public function mapFormsToData(\Traversable $radios, &$choice) + public function mapFormsToData(\Traversable $radios, mixed &$choice) { if (null !== $choice && !\is_string($choice)) { throw new UnexpectedTypeException($choice, 'null or string'); From 225d1be4328e5a62284ad39409cf144c7320911d Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 12 Jul 2021 11:26:55 +0200 Subject: [PATCH 014/208] Add return types, round 1 --- .../Factory/Cache/AbstractStaticOption.php | 5 +---- ChoiceList/Factory/Cache/ChoiceLoader.php | 7 ++++--- ChoiceList/Loader/AbstractChoiceLoader.php | 3 ++- Form.php | 16 ++++------------ NativeRequestHandler.php | 14 ++------------ Tests/Fixtures/FixedDataTransformer.php | 4 ++-- Util/OrderedHashMapIterator.php | 2 +- 7 files changed, 16 insertions(+), 35 deletions(-) diff --git a/ChoiceList/Factory/Cache/AbstractStaticOption.php b/ChoiceList/Factory/Cache/AbstractStaticOption.php index e209cf1565..420f67ea1b 100644 --- a/ChoiceList/Factory/Cache/AbstractStaticOption.php +++ b/ChoiceList/Factory/Cache/AbstractStaticOption.php @@ -44,10 +44,7 @@ final public function __construct(FormTypeInterface|FormTypeExtensionInterface $ $this->option = self::$options[$hash] ?? self::$options[$hash] = $option; } - /** - * @return mixed - */ - final public function getOption() + final public function getOption(): mixed { return $this->option; } diff --git a/ChoiceList/Factory/Cache/ChoiceLoader.php b/ChoiceList/Factory/Cache/ChoiceLoader.php index f0e1067b90..83b2ca0aa2 100644 --- a/ChoiceList/Factory/Cache/ChoiceLoader.php +++ b/ChoiceList/Factory/Cache/ChoiceLoader.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\ChoiceList\Factory\Cache; +use Symfony\Component\Form\ChoiceList\ChoiceListInterface; use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface; use Symfony\Component\Form\FormTypeExtensionInterface; use Symfony\Component\Form\FormTypeInterface; @@ -28,7 +29,7 @@ final class ChoiceLoader extends AbstractStaticOption implements ChoiceLoaderInt /** * {@inheritdoc} */ - public function loadChoiceList(callable $value = null) + public function loadChoiceList(callable $value = null): ChoiceListInterface { return $this->getOption()->loadChoiceList($value); } @@ -36,7 +37,7 @@ public function loadChoiceList(callable $value = null) /** * {@inheritdoc} */ - public function loadChoicesForValues(array $values, callable $value = null) + public function loadChoicesForValues(array $values, callable $value = null): array { return $this->getOption()->loadChoicesForValues($values, $value); } @@ -44,7 +45,7 @@ public function loadChoicesForValues(array $values, callable $value = null) /** * {@inheritdoc} */ - public function loadValuesForChoices(array $choices, callable $value = null) + public function loadValuesForChoices(array $choices, callable $value = null): array { return $this->getOption()->loadValuesForChoices($choices, $value); } diff --git a/ChoiceList/Loader/AbstractChoiceLoader.php b/ChoiceList/Loader/AbstractChoiceLoader.php index ea736a52c6..16f8ddf85e 100644 --- a/ChoiceList/Loader/AbstractChoiceLoader.php +++ b/ChoiceList/Loader/AbstractChoiceLoader.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\ChoiceList\Loader; +use Symfony\Component\Form\ChoiceList\ChoiceListInterface; use Symfony\Component\Form\ChoiceList\ArrayChoiceList; /** @@ -30,7 +31,7 @@ abstract class AbstractChoiceLoader implements ChoiceLoaderInterface * * {@inheritdoc} */ - public function loadChoiceList(callable $value = null) + public function loadChoiceList(callable $value = null): ChoiceListInterface { return $this->choiceList ?? ($this->choiceList = new ArrayChoiceList($this->loadChoices(), $value)); } diff --git a/Form.php b/Form.php index 985b6a9174..60cc2032f8 100644 --- a/Form.php +++ b/Form.php @@ -1071,11 +1071,9 @@ private function sort(array &$children): void /** * Normalizes the underlying data if a model transformer is set. * - * @return mixed - * * @throws TransformationFailedException If the underlying data cannot be transformed to "normalized" format */ - private function modelToNorm(mixed $value) + private function modelToNorm(mixed $value): mixed { try { foreach ($this->config->getModelTransformers() as $transformer) { @@ -1091,11 +1089,9 @@ private function modelToNorm(mixed $value) /** * Reverse transforms a value if a model transformer is set. * - * @return mixed - * * @throws TransformationFailedException If the value cannot be transformed to "model" format */ - private function normToModel(mixed $value) + private function normToModel(mixed $value): mixed { try { $transformers = $this->config->getModelTransformers(); @@ -1113,11 +1109,9 @@ private function normToModel(mixed $value) /** * Transforms the value if a view transformer is set. * - * @return mixed - * * @throws TransformationFailedException If the normalized value cannot be transformed to "view" format */ - private function normToView(mixed $value) + private function normToView(mixed $value): mixed { // Scalar values should be converted to strings to // facilitate differentiation between empty ("") and zero (0). @@ -1142,11 +1136,9 @@ private function normToView(mixed $value) /** * Reverse transforms a value if a view transformer is set. * - * @return mixed - * * @throws TransformationFailedException If the submitted value cannot be transformed to "normalized" format */ - private function viewToNorm(mixed $value) + private function viewToNorm(mixed $value): mixed { if (!$transformers = $this->config->getViewTransformers()) { return '' === $value ? null : $value; diff --git a/NativeRequestHandler.php b/NativeRequestHandler.php index 0dba25c659..81a1f63b07 100644 --- a/NativeRequestHandler.php +++ b/NativeRequestHandler.php @@ -159,9 +159,6 @@ public function getUploadFileError(mixed $data) return $data['error']; } - /** - * Returns the method used to submit the request to the server. - */ private static function getRequestMethod(): string { $method = isset($_SERVER['REQUEST_METHOD']) @@ -189,10 +186,8 @@ private static function getRequestMethod(): string * * This method is identical to {@link \Symfony\Component\HttpFoundation\FileBag::fixPhpFilesArray} * and should be kept as such in order to port fixes quickly and easily. - * - * @return mixed */ - private static function fixPhpFilesArray(mixed $data) + private static function fixPhpFilesArray(mixed $data): mixed { if (!\is_array($data)) { return $data; @@ -223,12 +218,7 @@ private static function fixPhpFilesArray(mixed $data) return $files; } - /** - * Sets empty uploaded files to NULL in the given uploaded files array. - * - * @return mixed Returns the stripped upload data - */ - private static function stripEmptyFiles(mixed $data) + private static function stripEmptyFiles(mixed $data): mixed { if (!\is_array($data)) { return $data; diff --git a/Tests/Fixtures/FixedDataTransformer.php b/Tests/Fixtures/FixedDataTransformer.php index 2939116096..fc99419f55 100644 --- a/Tests/Fixtures/FixedDataTransformer.php +++ b/Tests/Fixtures/FixedDataTransformer.php @@ -23,7 +23,7 @@ public function __construct(array $mapping) $this->mapping = $mapping; } - public function transform($value) + public function transform($value): mixed { if (!\array_key_exists($value, $this->mapping)) { throw new TransformationFailedException(sprintf('No mapping for value "%s"', $value)); @@ -32,7 +32,7 @@ public function transform($value) return $this->mapping[$value]; } - public function reverseTransform($value) + public function reverseTransform($value): mixed { $result = array_search($value, $this->mapping, true); diff --git a/Util/OrderedHashMapIterator.php b/Util/OrderedHashMapIterator.php index d1e03e8292..32a233c4b1 100644 --- a/Util/OrderedHashMapIterator.php +++ b/Util/OrderedHashMapIterator.php @@ -76,7 +76,7 @@ public function __construct(array &$elements, array &$orderedKeys, array &$manag $this->managedCursors[$this->cursorId] = &$this->cursor; } - public function __sleep() + public function __sleep(): array { throw new \BadMethodCallException('Cannot serialize '.__CLASS__); } From 8baab99b11688c6c6837fbfd3788dc6aed1f2b37 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 13 Jul 2021 13:47:05 +0200 Subject: [PATCH 015/208] [Contracts] add return types and bump to v3 --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 97fc8f0e7b..2b9cbfdb52 100644 --- a/composer.json +++ b/composer.json @@ -17,14 +17,14 @@ ], "require": { "php": ">=8.0.2", - "symfony/deprecation-contracts": "^2.1", + "symfony/deprecation-contracts": "^2.1|^3.0", "symfony/event-dispatcher": "^5.4|^6.0", "symfony/options-resolver": "^5.4|^6.0", "symfony/polyfill-ctype": "~1.8", "symfony/polyfill-intl-icu": "^1.21", "symfony/polyfill-mbstring": "~1.0", "symfony/property-access": "^5.4|^6.0", - "symfony/service-contracts": "^1.1|^2" + "symfony/service-contracts": "^1.1|^2.0|^3.0" }, "require-dev": { "doctrine/collections": "~1.0", From 23ef2f76b2fdeaa190d288f0498604caf8f7c4f8 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 20 Jul 2021 15:07:23 +0200 Subject: [PATCH 016/208] Add return type unions to private/internal/final/test methods --- .../DataTransformer/PercentToLocalizedStringTransformer.php | 6 +----- Extension/Core/Type/FileType.php | 4 +--- Extension/Validator/Constraints/FormValidator.php | 2 +- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index 0d80ee2f92..134dc013e1 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -195,12 +195,8 @@ protected function getNumberFormatter() /** * Rounds a number according to the configured scale and rounding mode. - * - * @param int|float $number A number - * - * @return int|float The rounded number */ - private function round($number) + private function round(int|float $number): int|float { if (null !== $this->scale && null !== $this->roundingMode) { // shift number to maintain the correct scale during rounding diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index ab9413a563..60863d109c 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -172,10 +172,8 @@ private function getFileUploadError(int $errorCode) * Returns the maximum size of an uploaded file as configured in php.ini. * * This method should be kept in sync with Symfony\Component\HttpFoundation\File\UploadedFile::getMaxFilesize(). - * - * @return int|float The maximum size of an uploaded file in bytes (returns float if size > PHP_INT_MAX) */ - private static function getMaxFilesize() + private static function getMaxFilesize(): int|float { $iniMax = strtolower(ini_get('upload_max_filesize')); diff --git a/Extension/Validator/Constraints/FormValidator.php b/Extension/Validator/Constraints/FormValidator.php index c669d56b87..827a15232d 100644 --- a/Extension/Validator/Constraints/FormValidator.php +++ b/Extension/Validator/Constraints/FormValidator.php @@ -205,7 +205,7 @@ public function validate(mixed $form, Constraint $formConstraint) * * @return string|GroupSequence|array The validation groups */ - private function getValidationGroups(FormInterface $form) + private function getValidationGroups(FormInterface $form): string|GroupSequence|array { // Determine the clicked button of the complete form tree $clickedButton = null; From e1c48708a5aca4f0a052c908fbd6338597178520 Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Tue, 27 Jul 2021 20:58:54 +0200 Subject: [PATCH 017/208] Fix tests Signed-off-by: Alexander M. Turek --- Util/OrderedHashMapIterator.php | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/Util/OrderedHashMapIterator.php b/Util/OrderedHashMapIterator.php index fe3b3af44b..6099097771 100644 --- a/Util/OrderedHashMapIterator.php +++ b/Util/OrderedHashMapIterator.php @@ -99,20 +99,16 @@ public function __destruct() /** * {@inheritdoc} - * - * @return mixed */ - public function current() + public function current(): mixed { return $this->current; } /** * {@inheritdoc} - * - * @return void */ - public function next() + public function next(): void { ++$this->cursor; @@ -127,10 +123,8 @@ public function next() /** * {@inheritdoc} - * - * @return mixed */ - public function key() + public function key(): mixed { if (null === $this->key) { return null; @@ -151,10 +145,8 @@ public function valid(): bool /** * {@inheritdoc} - * - * @return void */ - public function rewind() + public function rewind(): void { $this->cursor = 0; From 58332ad3853ccace2056ae484ec2004beef6eee4 Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Wed, 14 Jul 2021 22:19:45 +0200 Subject: [PATCH 018/208] [Form] Add types to private properties Signed-off-by: Alexander M. Turek --- AbstractExtension.php | 20 ++-- AbstractRendererEngine.php | 2 +- Button.php | 17 +-- ButtonBuilder.php | 29 +---- CallbackTransformer.php | 12 +- .../Factory/Cache/AbstractStaticOption.php | 7 +- .../Factory/CachingFactoryDecorator.php | 6 +- .../Factory/PropertyAccessDecorator.php | 4 +- ChoiceList/LazyChoiceList.php | 8 +- ChoiceList/Loader/AbstractChoiceLoader.php | 10 +- ChoiceList/Loader/CallbackChoiceLoader.php | 4 +- .../Loader/FilterChoiceLoaderDecorator.php | 6 +- Command/DebugCommand.php | 12 +- Console/Descriptor/TextDescriptor.php | 2 +- Exception/TransformationFailedException.php | 4 +- Extension/Core/CoreExtension.php | 6 +- Extension/Core/DataAccessor/ChainAccessor.php | 2 +- .../DataAccessor/PropertyPathAccessor.php | 2 +- Extension/Core/DataMapper/DataMapper.php | 2 +- .../ArrayToPartsTransformer.php | 2 +- .../BooleanToStringTransformer.php | 4 +- .../ChoiceToValueTransformer.php | 2 +- .../ChoicesToValuesTransformer.php | 2 +- .../DateIntervalToArrayTransformer.php | 4 +- .../DateIntervalToStringTransformer.php | 2 +- .../DateTimeToArrayTransformer.php | 6 +- .../DateTimeToLocalizedStringTransformer.php | 8 +- .../DateTimeToStringTransformer.php | 8 +- .../DateTimeZoneToStringTransformer.php | 2 +- .../IntlTimeZoneToStringTransformer.php | 2 +- .../MoneyToLocalizedStringTransformer.php | 2 +- .../NumberToLocalizedStringTransformer.php | 4 +- .../PercentToLocalizedStringTransformer.php | 8 +- .../StringToFloatTransformer.php | 2 +- .../ValueToDuplicatesTransformer.php | 2 +- .../EventListener/FixUrlProtocolListener.php | 2 +- .../EventListener/MergeCollectionListener.php | 4 +- .../Core/EventListener/ResizeFormListener.php | 4 +- .../TransformationFailureListener.php | 2 +- Extension/Core/Type/ChoiceType.php | 4 +- Extension/Core/Type/ColorType.php | 2 +- Extension/Core/Type/FileType.php | 2 +- Extension/Core/Type/FormType.php | 2 +- .../Type/TransformationFailureExtension.php | 2 +- Extension/Csrf/CsrfExtension.php | 6 +- .../EventListener/CsrfValidationListener.php | 14 +-- Extension/Csrf/Type/FormTypeCsrfExtension.php | 12 +- .../DataCollector/DataCollectorExtension.php | 2 +- .../EventListener/DataCollectorListener.php | 2 +- Extension/DataCollector/FormDataCollector.php | 14 +-- .../Proxy/ResolvedTypeDataCollectorProxy.php | 4 +- .../ResolvedTypeFactoryDataCollectorProxy.php | 4 +- .../Type/DataCollectorTypeExtension.php | 5 +- .../DependencyInjectionExtension.php | 10 +- .../HttpFoundationRequestHandler.php | 2 +- .../Type/FormTypeHttpFoundationExtension.php | 2 +- .../Validator/Constraints/FormValidator.php | 2 +- .../EventListener/ValidationListener.php | 5 +- .../Type/FormTypeValidatorExtension.php | 6 +- .../Type/UploadValidatorExtension.php | 4 +- Extension/Validator/ValidatorExtension.php | 8 +- Extension/Validator/ValidatorTypeGuesser.php | 2 +- .../Validator/ViolationMapper/MappingRule.php | 6 +- .../ViolationMapper/RelativePath.php | 2 +- .../ViolationMapper/ViolationMapper.php | 6 +- .../ViolationMapper/ViolationPath.php | 29 +---- Form.php | 71 +++-------- FormBuilder.php | 6 +- FormConfigBuilder.php | 110 +++++------------- FormError.php | 8 +- FormErrorIterator.php | 4 +- FormEvent.php | 2 +- FormFactory.php | 2 +- FormFactoryBuilder.php | 15 +-- FormRegistry.php | 18 +-- FormRenderer.php | 10 +- FormTypeGuesserChain.php | 2 +- FormView.php | 6 +- Guess/Guess.php | 4 +- Guess/TypeGuess.php | 4 +- Guess/ValueGuess.php | 2 +- NativeRequestHandler.php | 2 +- PreloadedExtension.php | 6 +- ResolvedFormType.php | 16 +-- SubmitButton.php | 2 +- Util/OptionsResolverWrapper.php | 2 +- Util/OrderedHashMap.php | 12 +- Util/OrderedHashMapIterator.php | 41 ++----- Util/ServerParams.php | 2 +- 89 files changed, 255 insertions(+), 478 deletions(-) diff --git a/AbstractExtension.php b/AbstractExtension.php index 96cfb26679..d8857a7773 100644 --- a/AbstractExtension.php +++ b/AbstractExtension.php @@ -24,35 +24,31 @@ abstract class AbstractExtension implements FormExtensionInterface * * @var FormTypeInterface[] */ - private $types; + private array $types; /** * The type extensions provided by this extension. * * @var FormTypeExtensionInterface[][] */ - private $typeExtensions; + private array $typeExtensions; /** * The type guesser provided by this extension. - * - * @var FormTypeGuesserInterface|null */ - private $typeGuesser; + private ?FormTypeGuesserInterface $typeGuesser = null; /** * Whether the type guesser has been loaded. - * - * @var bool */ - private $typeGuesserLoaded = false; + private bool $typeGuesserLoaded = false; /** * {@inheritdoc} */ public function getType(string $name) { - if (null === $this->types) { + if (!isset($this->types)) { $this->initTypes(); } @@ -68,7 +64,7 @@ public function getType(string $name) */ public function hasType(string $name) { - if (null === $this->types) { + if (!isset($this->types)) { $this->initTypes(); } @@ -80,7 +76,7 @@ public function hasType(string $name) */ public function getTypeExtensions(string $name) { - if (null === $this->typeExtensions) { + if (!isset($this->typeExtensions)) { $this->initTypeExtensions(); } @@ -93,7 +89,7 @@ public function getTypeExtensions(string $name) */ public function hasTypeExtensions(string $name) { - if (null === $this->typeExtensions) { + if (!isset($this->typeExtensions)) { $this->initTypeExtensions(); } diff --git a/AbstractRendererEngine.php b/AbstractRendererEngine.php index 0b5c33680b..6263397605 100644 --- a/AbstractRendererEngine.php +++ b/AbstractRendererEngine.php @@ -46,7 +46,7 @@ abstract class AbstractRendererEngine implements FormRendererEngineInterface /** * @var array> */ - private $resourceHierarchyLevels = []; + private array $resourceHierarchyLevels = []; /** * Creates a new renderer engine. diff --git a/Button.php b/Button.php index c1a0badd9c..0e4f5bdcad 100644 --- a/Button.php +++ b/Button.php @@ -21,20 +21,9 @@ */ class Button implements \IteratorAggregate, FormInterface { - /** - * @var FormInterface|null - */ - private $parent; - - /** - * @var FormConfigInterface - */ - private $config; - - /** - * @var bool - */ - private $submitted = false; + private ?FormInterface $parent = null; + private FormConfigInterface $config; + private bool $submitted = false; /** * Creates a new button from a form configuration. diff --git a/ButtonBuilder.php b/ButtonBuilder.php index 8ae3fcdf35..57e21e3319 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -25,30 +25,11 @@ class ButtonBuilder implements \IteratorAggregate, FormBuilderInterface { protected $locked = false; - /** - * @var bool - */ - private $disabled = false; - - /** - * @var ResolvedFormTypeInterface - */ - private $type; - - /** - * @var string - */ - private $name; - - /** - * @var array - */ - private $attributes = []; - - /** - * @var array - */ - private $options; + private bool $disabled = false; + private ResolvedFormTypeInterface $type; + private string $name; + private array $attributes = []; + private array $options; /** * @throws InvalidArgumentException if the name is empty diff --git a/CallbackTransformer.php b/CallbackTransformer.php index 0f7422ae64..189a0fd5da 100644 --- a/CallbackTransformer.php +++ b/CallbackTransformer.php @@ -13,17 +13,13 @@ class CallbackTransformer implements DataTransformerInterface { - private $transform; - private $reverseTransform; + private \Closure $transform; + private \Closure $reverseTransform; - /** - * @param callable $transform The forward transform callback - * @param callable $reverseTransform The reverse transform callback - */ public function __construct(callable $transform, callable $reverseTransform) { - $this->transform = $transform; - $this->reverseTransform = $reverseTransform; + $this->transform = $transform instanceof \Closure ? $transform : \Closure::fromCallable($transform); + $this->reverseTransform = $reverseTransform instanceof \Closure ? $reverseTransform : \Closure::fromCallable($reverseTransform); } /** diff --git a/ChoiceList/Factory/Cache/AbstractStaticOption.php b/ChoiceList/Factory/Cache/AbstractStaticOption.php index 420f67ea1b..5ccdbdb22e 100644 --- a/ChoiceList/Factory/Cache/AbstractStaticOption.php +++ b/ChoiceList/Factory/Cache/AbstractStaticOption.php @@ -28,10 +28,9 @@ */ abstract class AbstractStaticOption { - private static $options = []; + private static array $options = []; - /** @var bool|callable|string|array|\Closure|ChoiceLoaderInterface */ - private $option; + private bool|string|array|\Closure|ChoiceLoaderInterface $option; /** * @param mixed $option Any pseudo callable, array, string or bool to define a choice list option @@ -41,7 +40,7 @@ final public function __construct(FormTypeInterface|FormTypeExtensionInterface $ { $hash = CachingFactoryDecorator::generateHash([static::class, $formType, $vary]); - $this->option = self::$options[$hash] ?? self::$options[$hash] = $option; + $this->option = self::$options[$hash] ??= $option instanceof \Closure || !\is_callable($option) ? $option : \Closure::fromCallable($option); } final public function getOption(): mixed diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index eec6b54672..84b68e7dd0 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -27,17 +27,17 @@ */ class CachingFactoryDecorator implements ChoiceListFactoryInterface, ResetInterface { - private $decoratedFactory; + private ChoiceListFactoryInterface $decoratedFactory; /** * @var ChoiceListInterface[] */ - private $lists = []; + private array $lists = []; /** * @var ChoiceListView[] */ - private $views = []; + private array $views = []; /** * Generates a SHA-256 hash for the given value. diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index 5bbed1f6ac..d0a32b3fae 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -38,8 +38,8 @@ */ class PropertyAccessDecorator implements ChoiceListFactoryInterface { - private $decoratedFactory; - private $propertyAccessor; + private ChoiceListFactoryInterface $decoratedFactory; + private PropertyAccessorInterface $propertyAccessor; public function __construct(ChoiceListFactoryInterface $decoratedFactory, PropertyAccessorInterface $propertyAccessor = null) { diff --git a/ChoiceList/LazyChoiceList.php b/ChoiceList/LazyChoiceList.php index ab4c103e84..2bc0aaae8a 100644 --- a/ChoiceList/LazyChoiceList.php +++ b/ChoiceList/LazyChoiceList.php @@ -27,16 +27,14 @@ */ class LazyChoiceList implements ChoiceListInterface { - private $loader; + private ChoiceLoaderInterface $loader; /** * The callable creating string values for each choice. * * If null, choices are cast to strings. - * - * @var callable|null */ - private $value; + private ?\Closure $value; /** * Creates a lazily-loaded list using the given loader. @@ -50,7 +48,7 @@ class LazyChoiceList implements ChoiceListInterface public function __construct(ChoiceLoaderInterface $loader, callable $value = null) { $this->loader = $loader; - $this->value = $value; + $this->value = null === $value || $value instanceof \Closure ? $value : \Closure::fromCallable($value); } /** diff --git a/ChoiceList/Loader/AbstractChoiceLoader.php b/ChoiceList/Loader/AbstractChoiceLoader.php index 16f8ddf85e..4b04629f1d 100644 --- a/ChoiceList/Loader/AbstractChoiceLoader.php +++ b/ChoiceList/Loader/AbstractChoiceLoader.php @@ -11,8 +11,8 @@ namespace Symfony\Component\Form\ChoiceList\Loader; -use Symfony\Component\Form\ChoiceList\ChoiceListInterface; use Symfony\Component\Form\ChoiceList\ArrayChoiceList; +use Symfony\Component\Form\ChoiceList\ChoiceListInterface; /** * @author Jules Pietri @@ -21,10 +21,8 @@ abstract class AbstractChoiceLoader implements ChoiceLoaderInterface { /** * The loaded choice list. - * - * @var ArrayChoiceList */ - private $choiceList; + private ArrayChoiceList $choiceList; /** * @final @@ -45,7 +43,7 @@ public function loadChoicesForValues(array $values, callable $value = null) return []; } - if ($this->choiceList) { + if (isset($this->choiceList)) { return $this->choiceList->getChoicesForValues($values); } @@ -66,7 +64,7 @@ public function loadValuesForChoices(array $choices, callable $value = null) return array_map($value, $choices); } - if ($this->choiceList) { + if (isset($this->choiceList)) { return $this->choiceList->getValuesForChoices($choices); } diff --git a/ChoiceList/Loader/CallbackChoiceLoader.php b/ChoiceList/Loader/CallbackChoiceLoader.php index 1811d434e8..991b13407e 100644 --- a/ChoiceList/Loader/CallbackChoiceLoader.php +++ b/ChoiceList/Loader/CallbackChoiceLoader.php @@ -18,14 +18,14 @@ */ class CallbackChoiceLoader extends AbstractChoiceLoader { - private $callback; + private \Closure $callback; /** * @param callable $callback The callable returning iterable choices */ public function __construct(callable $callback) { - $this->callback = $callback; + $this->callback = $callback instanceof \Closure ? $callback : \Closure::fromCallable($callback); } protected function loadChoices(): iterable diff --git a/ChoiceList/Loader/FilterChoiceLoaderDecorator.php b/ChoiceList/Loader/FilterChoiceLoaderDecorator.php index a52f3b82e4..12e6d0e2a1 100644 --- a/ChoiceList/Loader/FilterChoiceLoaderDecorator.php +++ b/ChoiceList/Loader/FilterChoiceLoaderDecorator.php @@ -18,13 +18,13 @@ */ class FilterChoiceLoaderDecorator extends AbstractChoiceLoader { - private $decoratedLoader; - private $filter; + private ChoiceLoaderInterface $decoratedLoader; + private \Closure $filter; public function __construct(ChoiceLoaderInterface $loader, callable $filter) { $this->decoratedLoader = $loader; - $this->filter = $filter; + $this->filter = $filter instanceof \Closure ? $filter : \Closure::fromCallable($filter); } protected function loadChoices(): iterable diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index 0d1b626e9f..ceb1efa6e6 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -34,12 +34,12 @@ class DebugCommand extends Command protected static $defaultName = 'debug:form'; protected static $defaultDescription = 'Display form type information'; - private $formRegistry; - private $namespaces; - private $types; - private $extensions; - private $guessers; - private $fileLinkFormatter; + private FormRegistryInterface $formRegistry; + private array $namespaces; + private array $types; + private array $extensions; + private array $guessers; + private ?FileLinkFormatter $fileLinkFormatter; public function __construct(FormRegistryInterface $formRegistry, array $namespaces = ['Symfony\Component\Form\Extension\Core\Type'], array $types = [], array $extensions = [], array $guessers = [], FileLinkFormatter $fileLinkFormatter = null) { diff --git a/Console/Descriptor/TextDescriptor.php b/Console/Descriptor/TextDescriptor.php index 4862a674c2..ba79d806ad 100644 --- a/Console/Descriptor/TextDescriptor.php +++ b/Console/Descriptor/TextDescriptor.php @@ -24,7 +24,7 @@ */ class TextDescriptor extends Descriptor { - private $fileLinkFormatter; + private ?FileLinkFormatter $fileLinkFormatter; public function __construct(FileLinkFormatter $fileLinkFormatter = null) { diff --git a/Exception/TransformationFailedException.php b/Exception/TransformationFailedException.php index 89eba088ed..e34a6e5ec7 100644 --- a/Exception/TransformationFailedException.php +++ b/Exception/TransformationFailedException.php @@ -18,8 +18,8 @@ */ class TransformationFailedException extends RuntimeException { - private $invalidMessage; - private $invalidMessageParameters; + private ?string $invalidMessage; + private array $invalidMessageParameters; public function __construct(string $message = '', int $code = 0, \Throwable $previous = null, string $invalidMessage = null, array $invalidMessageParameters = []) { diff --git a/Extension/Core/CoreExtension.php b/Extension/Core/CoreExtension.php index 9c19603df0..25d99b5c4e 100644 --- a/Extension/Core/CoreExtension.php +++ b/Extension/Core/CoreExtension.php @@ -28,9 +28,9 @@ */ class CoreExtension extends AbstractExtension { - private $propertyAccessor; - private $choiceListFactory; - private $translator; + private PropertyAccessorInterface $propertyAccessor; + private ChoiceListFactoryInterface $choiceListFactory; + private ?TranslatorInterface $translator; public function __construct(PropertyAccessorInterface $propertyAccessor = null, ChoiceListFactoryInterface $choiceListFactory = null, TranslatorInterface $translator = null) { diff --git a/Extension/Core/DataAccessor/ChainAccessor.php b/Extension/Core/DataAccessor/ChainAccessor.php index dfd7907c8e..a58d1724c9 100644 --- a/Extension/Core/DataAccessor/ChainAccessor.php +++ b/Extension/Core/DataAccessor/ChainAccessor.php @@ -20,7 +20,7 @@ */ class ChainAccessor implements DataAccessorInterface { - private $accessors; + private iterable $accessors; /** * @param DataAccessorInterface[]|iterable $accessors diff --git a/Extension/Core/DataAccessor/PropertyPathAccessor.php b/Extension/Core/DataAccessor/PropertyPathAccessor.php index e8ff3e0c08..2890ec9067 100644 --- a/Extension/Core/DataAccessor/PropertyPathAccessor.php +++ b/Extension/Core/DataAccessor/PropertyPathAccessor.php @@ -28,7 +28,7 @@ */ class PropertyPathAccessor implements DataAccessorInterface { - private $propertyAccessor; + private PropertyAccessorInterface $propertyAccessor; public function __construct(PropertyAccessorInterface $propertyAccessor = null) { diff --git a/Extension/Core/DataMapper/DataMapper.php b/Extension/Core/DataMapper/DataMapper.php index 2b8f98f701..58f6ff5e5a 100644 --- a/Extension/Core/DataMapper/DataMapper.php +++ b/Extension/Core/DataMapper/DataMapper.php @@ -25,7 +25,7 @@ */ class DataMapper implements DataMapperInterface { - private $dataAccessor; + private DataAccessorInterface $dataAccessor; public function __construct(DataAccessorInterface $dataAccessor = null) { diff --git a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php index 0d9aaf0564..1aa2ce67bf 100644 --- a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php +++ b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php @@ -19,7 +19,7 @@ */ class ArrayToPartsTransformer implements DataTransformerInterface { - private $partMapping; + private array $partMapping; public function __construct(array $partMapping) { diff --git a/Extension/Core/DataTransformer/BooleanToStringTransformer.php b/Extension/Core/DataTransformer/BooleanToStringTransformer.php index ec93fbe990..58a6c995c4 100644 --- a/Extension/Core/DataTransformer/BooleanToStringTransformer.php +++ b/Extension/Core/DataTransformer/BooleanToStringTransformer.php @@ -23,9 +23,9 @@ */ class BooleanToStringTransformer implements DataTransformerInterface { - private $trueValue; + private string $trueValue; - private $falseValues; + private array $falseValues; /** * @param string $trueValue The value emitted upon transform if the input is true diff --git a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php index f7e13ea6ff..a91688f3f3 100644 --- a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php +++ b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php @@ -20,7 +20,7 @@ */ class ChoiceToValueTransformer implements DataTransformerInterface { - private $choiceList; + private ChoiceListInterface $choiceList; public function __construct(ChoiceListInterface $choiceList) { diff --git a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php index 0b40a0fcd8..5347137176 100644 --- a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php +++ b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php @@ -20,7 +20,7 @@ */ class ChoicesToValuesTransformer implements DataTransformerInterface { - private $choiceList; + private ChoiceListInterface $choiceList; public function __construct(ChoiceListInterface $choiceList) { diff --git a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php index d7e22f7abd..26848fae9a 100644 --- a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php @@ -39,8 +39,8 @@ class DateIntervalToArrayTransformer implements DataTransformerInterface self::SECONDS => 's', self::INVERT => 'r', ]; - private $fields; - private $pad; + private array $fields; + private bool $pad; /** * @param string[]|null $fields The date fields diff --git a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php index 9c22416a2a..e9d58126d2 100644 --- a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php @@ -22,7 +22,7 @@ */ class DateIntervalToStringTransformer implements DataTransformerInterface { - private $format; + private string $format; /** * Transforms a \DateInterval instance to a string. diff --git a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php index ea1959637c..e841b654bc 100644 --- a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php @@ -21,9 +21,9 @@ */ class DateTimeToArrayTransformer extends BaseDateTimeTransformer { - private $pad; - private $fields; - private $referenceDate; + private bool $pad; + private array $fields; + private \DateTimeInterface $referenceDate; /** * @param string|null $inputTimezone The input timezone diff --git a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php index 5685f78716..93219c9252 100644 --- a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php @@ -22,10 +22,10 @@ */ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer { - private $dateFormat; - private $timeFormat; - private $pattern; - private $calendar; + private int $dateFormat; + private int $timeFormat; + private ?string $pattern; + private int $calendar; /** * @see BaseDateTimeTransformer::formats for available format options diff --git a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php index 137133a551..2da6c6b898 100644 --- a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php @@ -23,10 +23,8 @@ class DateTimeToStringTransformer extends BaseDateTimeTransformer { /** * Format used for generating strings. - * - * @var string */ - private $generateFormat; + private string $generateFormat; /** * Format used for parsing strings. @@ -34,10 +32,8 @@ class DateTimeToStringTransformer extends BaseDateTimeTransformer * Different than the {@link $generateFormat} because formats for parsing * support additional characters in PHP that are not supported for * generating strings. - * - * @var string */ - private $parseFormat; + private string $parseFormat; /** * Transforms a \DateTime instance to a string. diff --git a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php index 407c4aa4e2..62c6af0080 100644 --- a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php @@ -21,7 +21,7 @@ */ class DateTimeZoneToStringTransformer implements DataTransformerInterface { - private $multiple; + private bool $multiple; public function __construct(bool $multiple = false) { diff --git a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php index afc7e9d662..59dbec56d9 100644 --- a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php @@ -21,7 +21,7 @@ */ class IntlTimeZoneToStringTransformer implements DataTransformerInterface { - private $multiple; + private bool $multiple; public function __construct(bool $multiple = false) { diff --git a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php index 08adf3857f..1d5ca8ab14 100644 --- a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php @@ -21,7 +21,7 @@ */ class MoneyToLocalizedStringTransformer extends NumberToLocalizedStringTransformer { - private $divisor; + private int $divisor; public function __construct(?int $scale = 2, ?bool $grouping = true, ?int $roundingMode = \NumberFormatter::ROUND_HALFUP, ?int $divisor = 1, string $locale = null) { diff --git a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index 28d7433c45..492ba9c4ab 100644 --- a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -27,8 +27,8 @@ class NumberToLocalizedStringTransformer implements DataTransformerInterface protected $roundingMode; - private $scale; - private $locale; + private ?int $scale; + private ?string $locale; public function __construct(int $scale = null, ?bool $grouping = false, ?int $roundingMode = \NumberFormatter::ROUND_HALFUP, string $locale = null) { diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index 9e6624990c..bfaf7071db 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -31,10 +31,10 @@ class PercentToLocalizedStringTransformer implements DataTransformerInterface self::INTEGER, ]; - private $roundingMode; - private $type; - private $scale; - private $html5Format; + private int $roundingMode; + private string $type; + private int $scale; + private bool $html5Format; /** * @see self::$types for a list of supported types diff --git a/Extension/Core/DataTransformer/StringToFloatTransformer.php b/Extension/Core/DataTransformer/StringToFloatTransformer.php index da50887cc5..f1b89ab22a 100644 --- a/Extension/Core/DataTransformer/StringToFloatTransformer.php +++ b/Extension/Core/DataTransformer/StringToFloatTransformer.php @@ -16,7 +16,7 @@ class StringToFloatTransformer implements DataTransformerInterface { - private $scale; + private ?int $scale; public function __construct(int $scale = null) { diff --git a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php index 3bd7419c71..a7d1287861 100644 --- a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php +++ b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php @@ -19,7 +19,7 @@ */ class ValueToDuplicatesTransformer implements DataTransformerInterface { - private $keys; + private array $keys; public function __construct(array $keys) { diff --git a/Extension/Core/EventListener/FixUrlProtocolListener.php b/Extension/Core/EventListener/FixUrlProtocolListener.php index 53dd4ee871..c64d747d4e 100644 --- a/Extension/Core/EventListener/FixUrlProtocolListener.php +++ b/Extension/Core/EventListener/FixUrlProtocolListener.php @@ -22,7 +22,7 @@ */ class FixUrlProtocolListener implements EventSubscriberInterface { - private $defaultProtocol; + private ?string $defaultProtocol; /** * @param string|null $defaultProtocol The URL scheme to add when there is none or null to not modify the data diff --git a/Extension/Core/EventListener/MergeCollectionListener.php b/Extension/Core/EventListener/MergeCollectionListener.php index cd4a3b5430..43c9de57de 100644 --- a/Extension/Core/EventListener/MergeCollectionListener.php +++ b/Extension/Core/EventListener/MergeCollectionListener.php @@ -21,8 +21,8 @@ */ class MergeCollectionListener implements EventSubscriberInterface { - private $allowAdd; - private $allowDelete; + private bool $allowAdd; + private bool $allowDelete; /** * @param bool $allowAdd Whether values might be added to the collection diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index 940ce39203..45c3032a67 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -29,7 +29,7 @@ class ResizeFormListener implements EventSubscriberInterface protected $allowAdd; protected $allowDelete; - private $deleteEmpty; + private \Closure|bool $deleteEmpty; public function __construct(string $type, array $options = [], bool $allowAdd = false, bool $allowDelete = false, bool|callable $deleteEmpty = false) { @@ -37,7 +37,7 @@ public function __construct(string $type, array $options = [], bool $allowAdd = $this->allowAdd = $allowAdd; $this->allowDelete = $allowDelete; $this->options = $options; - $this->deleteEmpty = $deleteEmpty; + $this->deleteEmpty = $deleteEmpty instanceof \Closure || !\is_callable($deleteEmpty) ? $deleteEmpty : \Closure::fromCallable($deleteEmpty); } public static function getSubscribedEvents() diff --git a/Extension/Core/EventListener/TransformationFailureListener.php b/Extension/Core/EventListener/TransformationFailureListener.php index dd2a2f284c..6fb7a3e4aa 100644 --- a/Extension/Core/EventListener/TransformationFailureListener.php +++ b/Extension/Core/EventListener/TransformationFailureListener.php @@ -22,7 +22,7 @@ */ class TransformationFailureListener implements EventSubscriberInterface { - private $translator; + private ?TranslatorInterface $translator; public function __construct(TranslatorInterface $translator = null) { diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index d0b75475dd..0ef8d48580 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -49,8 +49,8 @@ class ChoiceType extends AbstractType { - private $choiceListFactory; - private $translator; + private ChoiceListFactoryInterface $choiceListFactory; + private ?TranslatorInterface $translator; public function __construct(ChoiceListFactoryInterface $choiceListFactory = null, TranslatorInterface $translator = null) { diff --git a/Extension/Core/Type/ColorType.php b/Extension/Core/Type/ColorType.php index 2f50f55a36..e2e5f06e92 100644 --- a/Extension/Core/Type/ColorType.php +++ b/Extension/Core/Type/ColorType.php @@ -26,7 +26,7 @@ class ColorType extends AbstractType */ private const HTML5_PATTERN = '/^#[0-9a-f]{6}$/i'; - private $translator; + private ?TranslatorInterface $translator; public function __construct(TranslatorInterface $translator = null) { diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index bdd348fb7e..501ad8d098 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -33,7 +33,7 @@ class FileType extends AbstractType self::MIB_BYTES => 'MiB', ]; - private $translator; + private ?TranslatorInterface $translator; public function __construct(TranslatorInterface $translator = null) { diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index 668b49c7b2..0ed88c1b0f 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -28,7 +28,7 @@ class FormType extends BaseType { - private $dataMapper; + private DataMapper $dataMapper; public function __construct(PropertyAccessorInterface $propertyAccessor = null) { diff --git a/Extension/Core/Type/TransformationFailureExtension.php b/Extension/Core/Type/TransformationFailureExtension.php index f766633c9b..c73bd29582 100644 --- a/Extension/Core/Type/TransformationFailureExtension.php +++ b/Extension/Core/Type/TransformationFailureExtension.php @@ -21,7 +21,7 @@ */ class TransformationFailureExtension extends AbstractTypeExtension { - private $translator; + private ?TranslatorInterface $translator; public function __construct(TranslatorInterface $translator = null) { diff --git a/Extension/Csrf/CsrfExtension.php b/Extension/Csrf/CsrfExtension.php index 609a371ea0..6f0686860b 100644 --- a/Extension/Csrf/CsrfExtension.php +++ b/Extension/Csrf/CsrfExtension.php @@ -22,9 +22,9 @@ */ class CsrfExtension extends AbstractExtension { - private $tokenManager; - private $translator; - private $translationDomain; + private CsrfTokenManagerInterface $tokenManager; + private ?TranslatorInterface $translator; + private ?string $translationDomain; public function __construct(CsrfTokenManagerInterface $tokenManager, TranslatorInterface $translator = null, string $translationDomain = null) { diff --git a/Extension/Csrf/EventListener/CsrfValidationListener.php b/Extension/Csrf/EventListener/CsrfValidationListener.php index 37548ef550..cf01cf3951 100644 --- a/Extension/Csrf/EventListener/CsrfValidationListener.php +++ b/Extension/Csrf/EventListener/CsrfValidationListener.php @@ -25,13 +25,13 @@ */ class CsrfValidationListener implements EventSubscriberInterface { - private $fieldName; - private $tokenManager; - private $tokenId; - private $errorMessage; - private $translator; - private $translationDomain; - private $serverParams; + private string $fieldName; + private CsrfTokenManagerInterface $tokenManager; + private string $tokenId; + private string $errorMessage; + private ?TranslatorInterface $translator; + private ?string $translationDomain; + private ServerParams $serverParams; public static function getSubscribedEvents() { diff --git a/Extension/Csrf/Type/FormTypeCsrfExtension.php b/Extension/Csrf/Type/FormTypeCsrfExtension.php index cd17b8e94a..ca3bf22dff 100644 --- a/Extension/Csrf/Type/FormTypeCsrfExtension.php +++ b/Extension/Csrf/Type/FormTypeCsrfExtension.php @@ -28,12 +28,12 @@ */ class FormTypeCsrfExtension extends AbstractTypeExtension { - private $defaultTokenManager; - private $defaultEnabled; - private $defaultFieldName; - private $translator; - private $translationDomain; - private $serverParams; + private CsrfTokenManagerInterface $defaultTokenManager; + private bool $defaultEnabled; + private string $defaultFieldName; + private ?TranslatorInterface $translator; + private ?string $translationDomain; + private ?ServerParams $serverParams; public function __construct(CsrfTokenManagerInterface $defaultTokenManager, bool $defaultEnabled = true, string $defaultFieldName = '_token', TranslatorInterface $translator = null, string $translationDomain = null, ServerParams $serverParams = null) { diff --git a/Extension/DataCollector/DataCollectorExtension.php b/Extension/DataCollector/DataCollectorExtension.php index 4b23513b7c..694fbb6e8e 100644 --- a/Extension/DataCollector/DataCollectorExtension.php +++ b/Extension/DataCollector/DataCollectorExtension.php @@ -21,7 +21,7 @@ */ class DataCollectorExtension extends AbstractExtension { - private $dataCollector; + private FormDataCollectorInterface $dataCollector; public function __construct(FormDataCollectorInterface $dataCollector) { diff --git a/Extension/DataCollector/EventListener/DataCollectorListener.php b/Extension/DataCollector/EventListener/DataCollectorListener.php index 77595ab38a..ae46652a73 100644 --- a/Extension/DataCollector/EventListener/DataCollectorListener.php +++ b/Extension/DataCollector/EventListener/DataCollectorListener.php @@ -24,7 +24,7 @@ */ class DataCollectorListener implements EventSubscriberInterface { - private $dataCollector; + private FormDataCollectorInterface $dataCollector; public function __construct(FormDataCollectorInterface $dataCollector) { diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index 2fe2fbed1a..82d2468cdc 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -32,7 +32,7 @@ */ class FormDataCollector extends DataCollector implements FormDataCollectorInterface { - private $dataExtractor; + private FormDataExtractorInterface $dataExtractor; /** * Stores the collected data per {@link FormInterface} instance. @@ -40,10 +40,8 @@ class FormDataCollector extends DataCollector implements FormDataCollectorInterf * Uses the hashes of the forms as keys. This is preferable over using * {@link \SplObjectStorage}, because in this way no references are kept * to the {@link FormInterface} instances. - * - * @var array */ - private $dataByForm; + private array $dataByForm; /** * Stores the collected data per {@link FormView} instance. @@ -51,10 +49,8 @@ class FormDataCollector extends DataCollector implements FormDataCollectorInterf * Uses the hashes of the views as keys. This is preferable over using * {@link \SplObjectStorage}, because in this way no references are kept * to the {@link FormView} instances. - * - * @var array */ - private $dataByView; + private array $dataByView; /** * Connects {@link FormView} with {@link FormInterface} instances. @@ -62,10 +58,8 @@ class FormDataCollector extends DataCollector implements FormDataCollectorInterf * Uses the hashes of the views as keys and the hashes of the forms as * values. This is preferable over storing the objects directly, because * this way they can safely be discarded by the GC. - * - * @var array */ - private $formsByView; + private array $formsByView; public function __construct(FormDataExtractorInterface $dataExtractor) { diff --git a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php index 54358d5d49..847a19fe3c 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php @@ -25,8 +25,8 @@ */ class ResolvedTypeDataCollectorProxy implements ResolvedFormTypeInterface { - private $proxiedType; - private $dataCollector; + private ResolvedFormTypeInterface $proxiedType; + private FormDataCollectorInterface $dataCollector; public function __construct(ResolvedFormTypeInterface $proxiedType, FormDataCollectorInterface $dataCollector) { diff --git a/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php index 068d5cc0bf..35c92e2d46 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php @@ -24,8 +24,8 @@ */ class ResolvedTypeFactoryDataCollectorProxy implements ResolvedFormTypeFactoryInterface { - private $proxiedFactory; - private $dataCollector; + private ResolvedFormTypeFactoryInterface $proxiedFactory; + private FormDataCollectorInterface $dataCollector; public function __construct(ResolvedFormTypeFactoryInterface $proxiedFactory, FormDataCollectorInterface $dataCollector) { diff --git a/Extension/DataCollector/Type/DataCollectorTypeExtension.php b/Extension/DataCollector/Type/DataCollectorTypeExtension.php index d25fd132c0..73f8a214fa 100644 --- a/Extension/DataCollector/Type/DataCollectorTypeExtension.php +++ b/Extension/DataCollector/Type/DataCollectorTypeExtension.php @@ -25,10 +25,7 @@ */ class DataCollectorTypeExtension extends AbstractTypeExtension { - /** - * @var DataCollectorListener - */ - private $listener; + private DataCollectorListener $listener; public function __construct(FormDataCollectorInterface $dataCollector) { diff --git a/Extension/DependencyInjection/DependencyInjectionExtension.php b/Extension/DependencyInjection/DependencyInjectionExtension.php index 5d61a0693a..e0de02baca 100644 --- a/Extension/DependencyInjection/DependencyInjectionExtension.php +++ b/Extension/DependencyInjection/DependencyInjectionExtension.php @@ -18,11 +18,11 @@ class DependencyInjectionExtension implements FormExtensionInterface { - private $guesser; - private $guesserLoaded = false; - private $typeContainer; - private $typeExtensionServices; - private $guesserServices; + private ?FormTypeGuesserChain $guesser = null; + private bool $guesserLoaded = false; + private ContainerInterface $typeContainer; + private array $typeExtensionServices; + private iterable $guesserServices; /** * @param iterable[] $typeExtensionServices diff --git a/Extension/HttpFoundation/HttpFoundationRequestHandler.php b/Extension/HttpFoundation/HttpFoundationRequestHandler.php index c62932cee5..dbb2ff4dc9 100644 --- a/Extension/HttpFoundation/HttpFoundationRequestHandler.php +++ b/Extension/HttpFoundation/HttpFoundationRequestHandler.php @@ -28,7 +28,7 @@ */ class HttpFoundationRequestHandler implements RequestHandlerInterface { - private $serverParams; + private ServerParams $serverParams; public function __construct(ServerParams $serverParams = null) { diff --git a/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php b/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php index 0d77f06ce3..3d283d0e4e 100644 --- a/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php +++ b/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php @@ -22,7 +22,7 @@ */ class FormTypeHttpFoundationExtension extends AbstractTypeExtension { - private $requestHandler; + private RequestHandlerInterface $requestHandler; public function __construct(RequestHandlerInterface $requestHandler = null) { diff --git a/Extension/Validator/Constraints/FormValidator.php b/Extension/Validator/Constraints/FormValidator.php index 827a15232d..4d08dce790 100644 --- a/Extension/Validator/Constraints/FormValidator.php +++ b/Extension/Validator/Constraints/FormValidator.php @@ -24,7 +24,7 @@ */ class FormValidator extends ConstraintValidator { - private $resolvedGroups; + private \SplObjectStorage $resolvedGroups; /** * {@inheritdoc} diff --git a/Extension/Validator/EventListener/ValidationListener.php b/Extension/Validator/EventListener/ValidationListener.php index 867a5768ae..6f3b456392 100644 --- a/Extension/Validator/EventListener/ValidationListener.php +++ b/Extension/Validator/EventListener/ValidationListener.php @@ -23,9 +23,8 @@ */ class ValidationListener implements EventSubscriberInterface { - private $validator; - - private $violationMapper; + private ValidatorInterface $validator; + private ViolationMapperInterface $violationMapper; /** * {@inheritdoc} diff --git a/Extension/Validator/Type/FormTypeValidatorExtension.php b/Extension/Validator/Type/FormTypeValidatorExtension.php index 0a27c1729f..cab3a7ae23 100644 --- a/Extension/Validator/Type/FormTypeValidatorExtension.php +++ b/Extension/Validator/Type/FormTypeValidatorExtension.php @@ -26,9 +26,9 @@ */ class FormTypeValidatorExtension extends BaseValidatorExtension { - private $validator; - private $violationMapper; - private $legacyErrorMessages; + private ValidatorInterface $validator; + private ViolationMapper $violationMapper; + private bool $legacyErrorMessages; public function __construct(ValidatorInterface $validator, bool $legacyErrorMessages = true, FormRendererInterface $formRenderer = null, TranslatorInterface $translator = null) { diff --git a/Extension/Validator/Type/UploadValidatorExtension.php b/Extension/Validator/Type/UploadValidatorExtension.php index 21e4fe20ea..b5ddecd99d 100644 --- a/Extension/Validator/Type/UploadValidatorExtension.php +++ b/Extension/Validator/Type/UploadValidatorExtension.php @@ -23,8 +23,8 @@ */ class UploadValidatorExtension extends AbstractTypeExtension { - private $translator; - private $translationDomain; + private TranslatorInterface $translator; + private ?string $translationDomain; public function __construct(TranslatorInterface $translator, string $translationDomain = null) { diff --git a/Extension/Validator/ValidatorExtension.php b/Extension/Validator/ValidatorExtension.php index 3a5728a827..d057565a18 100644 --- a/Extension/Validator/ValidatorExtension.php +++ b/Extension/Validator/ValidatorExtension.php @@ -26,10 +26,10 @@ */ class ValidatorExtension extends AbstractExtension { - private $validator; - private $formRenderer; - private $translator; - private $legacyErrorMessages; + private ValidatorInterface $validator; + private ?FormRendererInterface $formRenderer; + private ?TranslatorInterface $translator; + private bool $legacyErrorMessages; public function __construct(ValidatorInterface $validator, bool $legacyErrorMessages = true, FormRendererInterface $formRenderer = null, TranslatorInterface $translator = null) { diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index 72b98f5451..f887a599be 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -21,7 +21,7 @@ class ValidatorTypeGuesser implements FormTypeGuesserInterface { - private $metadataFactory; + private MetadataFactoryInterface $metadataFactory; public function __construct(MetadataFactoryInterface $metadataFactory) { diff --git a/Extension/Validator/ViolationMapper/MappingRule.php b/Extension/Validator/ViolationMapper/MappingRule.php index 095198928a..745171f02a 100644 --- a/Extension/Validator/ViolationMapper/MappingRule.php +++ b/Extension/Validator/ViolationMapper/MappingRule.php @@ -19,9 +19,9 @@ */ class MappingRule { - private $origin; - private $propertyPath; - private $targetPath; + private FormInterface $origin; + private string $propertyPath; + private string $targetPath; public function __construct(FormInterface $origin, string $propertyPath, string $targetPath) { diff --git a/Extension/Validator/ViolationMapper/RelativePath.php b/Extension/Validator/ViolationMapper/RelativePath.php index 0efd168e3d..eaee36ea79 100644 --- a/Extension/Validator/ViolationMapper/RelativePath.php +++ b/Extension/Validator/ViolationMapper/RelativePath.php @@ -19,7 +19,7 @@ */ class RelativePath extends PropertyPath { - private $root; + private FormInterface $root; public function __construct(FormInterface $root, string $propertyPath) { diff --git a/Extension/Validator/ViolationMapper/ViolationMapper.php b/Extension/Validator/ViolationMapper/ViolationMapper.php index 88dbf9b2b4..a9912a2906 100644 --- a/Extension/Validator/ViolationMapper/ViolationMapper.php +++ b/Extension/Validator/ViolationMapper/ViolationMapper.php @@ -28,9 +28,9 @@ */ class ViolationMapper implements ViolationMapperInterface { - private $formRenderer; - private $translator; - private $allowNonSynchronized = false; + private ?FormRendererInterface $formRenderer; + private ?TranslatorInterface $translator; + private bool $allowNonSynchronized = false; public function __construct(FormRendererInterface $formRenderer = null, TranslatorInterface $translator = null) { diff --git a/Extension/Validator/ViolationMapper/ViolationPath.php b/Extension/Validator/ViolationMapper/ViolationPath.php index 8481141691..6f8568eba1 100644 --- a/Extension/Validator/ViolationMapper/ViolationPath.php +++ b/Extension/Validator/ViolationMapper/ViolationPath.php @@ -20,30 +20,11 @@ */ class ViolationPath implements \IteratorAggregate, PropertyPathInterface { - /** - * @var array - */ - private $elements = []; - - /** - * @var array - */ - private $isIndex = []; - - /** - * @var array - */ - private $mapsForm = []; - - /** - * @var string - */ - private $pathAsString = ''; - - /** - * @var int - */ - private $length = 0; + private array $elements = []; + private array $isIndex = []; + private array $mapsForm = []; + private string $pathAsString = ''; + private int $length = 0; /** * Creates a new violation path from a string. diff --git a/Form.php b/Form.php index 1702fca9cf..58034c8e05 100644 --- a/Form.php +++ b/Form.php @@ -69,68 +69,41 @@ */ class Form implements \IteratorAggregate, FormInterface, ClearableErrorsInterface { - /** - * @var FormConfigInterface - */ - private $config; - - /** - * @var FormInterface|null - */ - private $parent; + private FormConfigInterface $config; + private ?FormInterface $parent = null; /** * A map of FormInterface instances. * * @var FormInterface[]|OrderedHashMap */ - private $children; + private OrderedHashMap $children; /** * @var FormError[] */ - private $errors = []; + private array $errors = []; - /** - * @var bool - */ - private $submitted = false; + private bool $submitted = false; /** * The button that was used to submit the form. - * - * @var FormInterface|ClickableInterface|null - */ - private $clickedButton; - - /** - * @var mixed */ - private $modelData; + private FormInterface|ClickableInterface|null $clickedButton = null; - /** - * @var mixed - */ - private $normData; - - /** - * @var mixed - */ - private $viewData; + private mixed $modelData = null; + private mixed $normData = null; + private mixed $viewData = null; /** * The submitted values that don't belong to any children. - * - * @var array */ - private $extraData = []; + private array $extraData = []; /** * The transformation failure generated during submission, if any. - * - * @var TransformationFailedException|null */ - private $transformationFailure; + private ?TransformationFailedException $transformationFailure = null; /** * Whether the form's data has been initialized. @@ -141,34 +114,22 @@ class Form implements \IteratorAggregate, FormInterface, ClearableErrorsInterfac * lazily in order to save performance when {@link setData()} is called * manually, making the initialization with the configured default value * superfluous. - * - * @var bool */ - private $defaultDataSet = false; + private bool $defaultDataSet = false; /** * Whether setData() is currently being called. - * - * @var bool */ - private $lockSetData = false; + private bool $lockSetData = false; - /** - * @var string - */ - private $name = ''; + private string $name = ''; /** * Whether the form inherits its underlying data from its parent. - * - * @var bool */ - private $inheritData; + private bool $inheritData; - /** - * @var PropertyPathInterface|null - */ - private $propertyPath; + private ?PropertyPathInterface $propertyPath = null; /** * @throws LogicException if a data mapper is not provided for a compound form diff --git a/FormBuilder.php b/FormBuilder.php index 1012751a5b..6ac054a8dc 100644 --- a/FormBuilder.php +++ b/FormBuilder.php @@ -29,14 +29,12 @@ class FormBuilder extends FormConfigBuilder implements \IteratorAggregate, FormB * * @var FormBuilderInterface[] */ - private $children = []; + private array $children = []; /** * The data of children who haven't been converted to form builders yet. - * - * @var array */ - private $unresolvedChildren = []; + private array $unresolvedChildren = []; public function __construct(?string $name, ?string $dataClass, EventDispatcherInterface $dispatcher, FormFactoryInterface $factory, array $options = []) { diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index caa5cc0789..bad5f350e0 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -28,81 +28,38 @@ class FormConfigBuilder implements FormConfigBuilderInterface { /** * Caches a globally unique {@link NativeRequestHandler} instance. - * - * @var NativeRequestHandler */ - private static $nativeRequestHandler; + private static NativeRequestHandler $nativeRequestHandler; + /** @var bool */ protected $locked = false; - private $dispatcher; - private $name; - - /** - * @var PropertyPathInterface|string|null - */ - private $propertyPath; - - private $mapped = true; - private $byReference = true; - private $inheritData = false; - private $compound = false; - - /** - * @var ResolvedFormTypeInterface - */ - private $type; - - private $viewTransformers = []; - private $modelTransformers = []; - - /** - * @var DataMapperInterface|null - */ - private $dataMapper; - - private $required = true; - private $disabled = false; - private $errorBubbling = false; - - /** - * @var mixed - */ - private $emptyData; - - private $attributes = []; - - /** - * @var mixed - */ - private $data; - - /** - * @var string|null - */ - private $dataClass; - - private $dataLocked = false; - - /** - * @var FormFactoryInterface|null - */ - private $formFactory; - /** - * @var string|null - */ - private $action; - - private $method = 'POST'; - - /** - * @var RequestHandlerInterface|null - */ - private $requestHandler; - - private $autoInitialize = false; - private $options; - private $isEmptyCallback; + private EventDispatcherInterface $dispatcher; + private string $name; + private ?PropertyPathInterface $propertyPath = null; + private bool $mapped = true; + private bool $byReference = true; + private bool $inheritData = false; + private bool $compound = false; + private ResolvedFormTypeInterface $type; + private array $viewTransformers = []; + private array $modelTransformers = []; + private ?DataMapperInterface $dataMapper = null; + private bool $required = true; + private bool $disabled = false; + private bool $errorBubbling = false; + private mixed $emptyData = null; + private array $attributes = []; + private mixed $data = null; + private ?string $dataClass; + private bool $dataLocked = false; + private ?FormFactoryInterface $formFactory = null; + private ?string $action = null; + private string $method = 'POST'; + private RequestHandlerInterface $requestHandler; + private bool $autoInitialize = false; + private array $options; + private ?\Closure $isEmptyCallback = null; /** * Creates an empty form configuration. @@ -420,14 +377,7 @@ public function getMethod() */ public function getRequestHandler() { - if (null === $this->requestHandler) { - if (null === self::$nativeRequestHandler) { - self::$nativeRequestHandler = new NativeRequestHandler(); - } - $this->requestHandler = self::$nativeRequestHandler; - } - - return $this->requestHandler; + return $this->requestHandler ??= self::$nativeRequestHandler ??= new NativeRequestHandler(); } /** @@ -775,7 +725,7 @@ public function getFormConfig() */ public function setIsEmptyCallback(?callable $isEmptyCallback): static { - $this->isEmptyCallback = $isEmptyCallback; + $this->isEmptyCallback = null === $isEmptyCallback || $isEmptyCallback instanceof \Closure ? $isEmptyCallback : \Closure::fromCallable($isEmptyCallback); return $this; } diff --git a/FormError.php b/FormError.php index 8d5c571bfc..a38b4346d5 100644 --- a/FormError.php +++ b/FormError.php @@ -24,15 +24,13 @@ class FormError protected $messageParameters; protected $messagePluralization; - private $message; - private $cause; + private string $message; + private mixed $cause; /** * The form that spawned this error. - * - * @var FormInterface */ - private $origin; + private ?FormInterface $origin = null; /** * Any array key in $messageParameters will be used as a placeholder in diff --git a/FormErrorIterator.php b/FormErrorIterator.php index f96632f445..8bfea27ff5 100644 --- a/FormErrorIterator.php +++ b/FormErrorIterator.php @@ -35,8 +35,8 @@ class FormErrorIterator implements \RecursiveIterator, \SeekableIterator, \Array */ public const INDENTATION = ' '; - private $form; - private $errors; + private FormInterface $form; + private array $errors; /** * @param FormError[]|self[] $errors An array of form errors and instances diff --git a/FormEvent.php b/FormEvent.php index b50e637b05..c7999e4b15 100644 --- a/FormEvent.php +++ b/FormEvent.php @@ -18,7 +18,7 @@ */ class FormEvent extends Event { - private $form; + private FormInterface $form; protected $data; public function __construct(FormInterface $form, mixed $data) diff --git a/FormFactory.php b/FormFactory.php index 01329a403b..4468183cea 100644 --- a/FormFactory.php +++ b/FormFactory.php @@ -16,7 +16,7 @@ class FormFactory implements FormFactoryInterface { - private $registry; + private FormRegistryInterface $registry; public function __construct(FormRegistryInterface $registry) { diff --git a/FormFactoryBuilder.php b/FormFactoryBuilder.php index 735a17e8e5..d541f6aa3a 100644 --- a/FormFactoryBuilder.php +++ b/FormFactoryBuilder.php @@ -20,32 +20,29 @@ */ class FormFactoryBuilder implements FormFactoryBuilderInterface { - private $forceCoreExtension; + private bool $forceCoreExtension; - /** - * @var ResolvedFormTypeFactoryInterface - */ - private $resolvedTypeFactory; + private ResolvedFormTypeFactoryInterface $resolvedTypeFactory; /** * @var FormExtensionInterface[] */ - private $extensions = []; + private array $extensions = []; /** * @var FormTypeInterface[] */ - private $types = []; + private array $types = []; /** * @var FormTypeExtensionInterface[][] */ - private $typeExtensions = []; + private array $typeExtensions = []; /** * @var FormTypeGuesserInterface[] */ - private $typeGuessers = []; + private array $typeGuessers = []; public function __construct(bool $forceCoreExtension = false) { diff --git a/FormRegistry.php b/FormRegistry.php index de1030a5ca..8461bbafe4 100644 --- a/FormRegistry.php +++ b/FormRegistry.php @@ -26,24 +26,16 @@ class FormRegistry implements FormRegistryInterface /** * @var FormExtensionInterface[] */ - private $extensions = []; + private array $extensions = []; /** * @var ResolvedFormTypeInterface[] */ - private $types = []; + private array $types = []; - /** - * @var FormTypeGuesserInterface|false|null - */ - private $guesser = false; - - /** - * @var ResolvedFormTypeFactoryInterface - */ - private $resolvedTypeFactory; - - private $checkedTypes = []; + private FormTypeGuesserInterface|null|false $guesser = false; + private ResolvedFormTypeFactoryInterface $resolvedTypeFactory; + private array $checkedTypes = []; /** * @param FormExtensionInterface[] $extensions diff --git a/FormRenderer.php b/FormRenderer.php index 48f3841f24..41f78c91e6 100644 --- a/FormRenderer.php +++ b/FormRenderer.php @@ -25,11 +25,11 @@ class FormRenderer implements FormRendererInterface { public const CACHE_KEY_VAR = 'unique_block_prefix'; - private $engine; - private $csrfTokenManager; - private $blockNameHierarchyMap = []; - private $hierarchyLevelMap = []; - private $variableStack = []; + private FormRendererEngineInterface $engine; + private ?CsrfTokenManagerInterface $csrfTokenManager; + private array $blockNameHierarchyMap = []; + private array $hierarchyLevelMap = []; + private array $variableStack = []; public function __construct(FormRendererEngineInterface $engine, CsrfTokenManagerInterface $csrfTokenManager = null) { diff --git a/FormTypeGuesserChain.php b/FormTypeGuesserChain.php index fc40d3aaaa..4d1923c3c6 100644 --- a/FormTypeGuesserChain.php +++ b/FormTypeGuesserChain.php @@ -16,7 +16,7 @@ class FormTypeGuesserChain implements FormTypeGuesserInterface { - private $guessers = []; + private array $guessers = []; /** * @param FormTypeGuesserInterface[] $guessers diff --git a/FormView.php b/FormView.php index 77582b4abb..0f904b887e 100644 --- a/FormView.php +++ b/FormView.php @@ -44,12 +44,10 @@ class FormView implements \ArrayAccess, \IteratorAggregate, \Countable * Rendering happens when either the widget or the row method was called. * Row implicitly includes widget, however certain rendering mechanisms * have to skip widget rendering when a row is rendered. - * - * @var bool */ - private $rendered = false; + private bool $rendered = false; - private $methodRendered = false; + private bool $methodRendered = false; public function __construct(self $parent = null) { diff --git a/Guess/Guess.php b/Guess/Guess.php index 935bbfea1c..57f1f63222 100644 --- a/Guess/Guess.php +++ b/Guess/Guess.php @@ -49,10 +49,8 @@ abstract class Guess * * One of VERY_HIGH_CONFIDENCE, HIGH_CONFIDENCE, MEDIUM_CONFIDENCE * and LOW_CONFIDENCE. - * - * @var int */ - private $confidence; + private int $confidence; /** * Returns the guess most likely to be correct from a list of guesses. diff --git a/Guess/TypeGuess.php b/Guess/TypeGuess.php index ff0c6a7498..9d82e83ce2 100644 --- a/Guess/TypeGuess.php +++ b/Guess/TypeGuess.php @@ -19,8 +19,8 @@ */ class TypeGuess extends Guess { - private $type; - private $options; + private string $type; + private array $options; /** * @param string $type The guessed field type diff --git a/Guess/ValueGuess.php b/Guess/ValueGuess.php index a316a0adad..2b01e389bc 100644 --- a/Guess/ValueGuess.php +++ b/Guess/ValueGuess.php @@ -18,7 +18,7 @@ */ class ValueGuess extends Guess { - private $value; + private string|int|bool|null $value; /** * @param int $confidence The confidence that the guessed class name is correct diff --git a/NativeRequestHandler.php b/NativeRequestHandler.php index 81a1f63b07..95318d49c4 100644 --- a/NativeRequestHandler.php +++ b/NativeRequestHandler.php @@ -21,7 +21,7 @@ */ class NativeRequestHandler implements RequestHandlerInterface { - private $serverParams; + private ServerParams $serverParams; /** * The allowed keys of the $_FILES array. diff --git a/PreloadedExtension.php b/PreloadedExtension.php index 52029bb61e..7c97cf89d1 100644 --- a/PreloadedExtension.php +++ b/PreloadedExtension.php @@ -20,9 +20,9 @@ */ class PreloadedExtension implements FormExtensionInterface { - private $types = []; - private $typeExtensions = []; - private $typeGuesser; + private array $types = []; + private array $typeExtensions = []; + private ?FormTypeGuesserInterface $typeGuesser; /** * Creates a new preloaded extension. diff --git a/ResolvedFormType.php b/ResolvedFormType.php index 7060f28eee..4556e54a24 100644 --- a/ResolvedFormType.php +++ b/ResolvedFormType.php @@ -23,25 +23,19 @@ */ class ResolvedFormType implements ResolvedFormTypeInterface { - /** - * @var FormTypeInterface - */ - private $innerType; + private FormTypeInterface $innerType; /** * @var FormTypeExtensionInterface[] */ - private $typeExtensions; + private array $typeExtensions; - /** - * @var ResolvedFormTypeInterface|null - */ - private $parent; + private ?ResolvedFormTypeInterface $parent; /** * @var OptionsResolver */ - private $optionsResolver; + private OptionsResolver $optionsResolver; /** * @param FormTypeExtensionInterface[] $typeExtensions @@ -173,7 +167,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) */ public function getOptionsResolver() { - if (null === $this->optionsResolver) { + if (!isset($this->optionsResolver)) { if (null !== $this->parent) { $this->optionsResolver = clone $this->parent->getOptionsResolver(); } else { diff --git a/SubmitButton.php b/SubmitButton.php index 0312e56bd6..e47eee8a85 100644 --- a/SubmitButton.php +++ b/SubmitButton.php @@ -18,7 +18,7 @@ */ class SubmitButton extends Button implements ClickableInterface { - private $clicked = false; + private bool $clicked = false; /** * {@inheritdoc} diff --git a/Util/OptionsResolverWrapper.php b/Util/OptionsResolverWrapper.php index 03a90cda7f..b983018fe9 100644 --- a/Util/OptionsResolverWrapper.php +++ b/Util/OptionsResolverWrapper.php @@ -22,7 +22,7 @@ */ class OptionsResolverWrapper extends OptionsResolver { - private $undefined = []; + private array $undefined = []; /** * @return $this diff --git a/Util/OrderedHashMap.php b/Util/OrderedHashMap.php index e863729314..ef3b911f25 100644 --- a/Util/OrderedHashMap.php +++ b/Util/OrderedHashMap.php @@ -68,24 +68,18 @@ class OrderedHashMap implements \ArrayAccess, \IteratorAggregate, \Countable { /** * The elements of the map, indexed by their keys. - * - * @var array */ - private $elements = []; + private array $elements = []; /** * The keys of the map in the order in which they were inserted or changed. - * - * @var array */ - private $orderedKeys = []; + private array $orderedKeys = []; /** * References to the cursors of all open iterators. - * - * @var array */ - private $managedCursors = []; + private array $managedCursors = []; /** * Creates a new map. diff --git a/Util/OrderedHashMapIterator.php b/Util/OrderedHashMapIterator.php index 6099097771..14008e649a 100644 --- a/Util/OrderedHashMapIterator.php +++ b/Util/OrderedHashMapIterator.php @@ -20,40 +20,13 @@ */ class OrderedHashMapIterator implements \Iterator { - /** - * @var array - */ - private $elements; - - /** - * @var array - */ - private $orderedKeys; - - /** - * @var int - */ - private $cursor; - - /** - * @var int - */ - private $cursorId; - - /** - * @var array - */ - private $managedCursors; - - /** - * @var string|int|null - */ - private $key; - - /** - * @var mixed - */ - private $current; + private array $elements; + private array $orderedKeys; + private int $cursor = 0; + private int $cursorId; + private array $managedCursors; + private string|int|null $key = null; + private mixed $current = null; /** * @param array $elements The elements of the map, indexed by their diff --git a/Util/ServerParams.php b/Util/ServerParams.php index b6ce9d1065..4076b7c49b 100644 --- a/Util/ServerParams.php +++ b/Util/ServerParams.php @@ -18,7 +18,7 @@ */ class ServerParams { - private $requestStack; + private ?RequestStack $requestStack; public function __construct(RequestStack $requestStack = null) { From 685588cf23c8a71d1305182af8a54fc5f6019d2d Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 9 Aug 2021 14:20:27 +0200 Subject: [PATCH 019/208] Fix merge --- Tests/Fixtures/CustomArrayObject.php | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/Tests/Fixtures/CustomArrayObject.php b/Tests/Fixtures/CustomArrayObject.php index e43c809f05..009b79568a 100644 --- a/Tests/Fixtures/CustomArrayObject.php +++ b/Tests/Fixtures/CustomArrayObject.php @@ -29,13 +29,7 @@ public function offsetExists($offset): bool return \array_key_exists($offset, $this->array); } - /** - * @param mixed $offset - * - * @return mixed - */ - #[\ReturnTypeWillChange] - public function offsetGet($offset) + public function offsetGet($offset): mixed { return $this->array[$offset]; } From 9132d60f2cd9898c18bdc47dcd9a905d12c40180 Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Thu, 5 Aug 2021 00:33:39 +0200 Subject: [PATCH 020/208] Remove ReturnTypeWillChange Signed-off-by: Alexander M. Turek --- Button.php | 24 ++------ ButtonBuilder.php | 6 +- ChoiceList/View/ChoiceGroupView.php | 3 +- .../ViolationMapper/ViolationPath.php | 5 +- Form.php | 28 +++------ FormBuilder.php | 11 +--- FormErrorIterator.php | 59 ++++--------------- FormView.php | 31 ++-------- Util/InheritDataAwareIterator.php | 14 +---- Util/OrderedHashMap.php | 42 ++----------- Util/OrderedHashMapIterator.php | 2 - 11 files changed, 47 insertions(+), 178 deletions(-) diff --git a/Button.php b/Button.php index cf7238d5b8..117d817fb0 100644 --- a/Button.php +++ b/Button.php @@ -38,8 +38,7 @@ public function __construct(FormConfigInterface $config) * * @return bool Always returns false */ - #[\ReturnTypeWillChange] - public function offsetExists(mixed $offset) + public function offsetExists(mixed $offset): bool { return false; } @@ -49,12 +48,9 @@ public function offsetExists(mixed $offset) * * This method should not be invoked. * - * @return mixed - * * @throws BadMethodCallException */ - #[\ReturnTypeWillChange] - public function offsetGet(mixed $offset) + public function offsetGet(mixed $offset): mixed { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -64,12 +60,9 @@ public function offsetGet(mixed $offset) * * This method should not be invoked. * - * @return void - * * @throws BadMethodCallException */ - #[\ReturnTypeWillChange] - public function offsetSet(mixed $offset, mixed $value) + public function offsetSet(mixed $offset, mixed $value): void { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -79,12 +72,9 @@ public function offsetSet(mixed $offset, mixed $value) * * This method should not be invoked. * - * @return void - * * @throws BadMethodCallException */ - #[\ReturnTypeWillChange] - public function offsetUnset(mixed $offset) + public function offsetUnset(mixed $offset): void { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -407,8 +397,7 @@ public function createView(FormView $parent = null) * * @return int Always returns 0 */ - #[\ReturnTypeWillChange] - public function count() + public function count(): int { return 0; } @@ -418,8 +407,7 @@ public function count() * * @return \EmptyIterator Always returns an empty iterator */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): \EmptyIterator { return new \EmptyIterator(); } diff --git a/ButtonBuilder.php b/ButtonBuilder.php index b74a32ca24..8cefe3794e 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -693,8 +693,7 @@ public function getIsEmptyCallback(): ?callable * * @return int Always returns 0 */ - #[\ReturnTypeWillChange] - public function count() + public function count(): int { return 0; } @@ -704,8 +703,7 @@ public function count() * * @return \EmptyIterator Always returns an empty iterator */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): \EmptyIterator { return new \EmptyIterator(); } diff --git a/ChoiceList/View/ChoiceGroupView.php b/ChoiceList/View/ChoiceGroupView.php index 5ad89c6b1f..185e54ae78 100644 --- a/ChoiceList/View/ChoiceGroupView.php +++ b/ChoiceList/View/ChoiceGroupView.php @@ -37,8 +37,7 @@ public function __construct(string $label, array $choices = []) * * @return \Traversable */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): \Traversable { return new \ArrayIterator($this->choices); } diff --git a/Extension/Validator/ViolationMapper/ViolationPath.php b/Extension/Validator/ViolationMapper/ViolationPath.php index 87adc8a8ba..337fcacfee 100644 --- a/Extension/Validator/ViolationMapper/ViolationPath.php +++ b/Extension/Validator/ViolationMapper/ViolationPath.php @@ -196,11 +196,8 @@ public function mapsForm(int $index) /** * Returns a new iterator for this path. - * - * @return ViolationPathIterator */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): ViolationPathIterator { return new ViolationPathIterator($this); } diff --git a/Form.php b/Form.php index 018fb13165..722545163b 100644 --- a/Form.php +++ b/Form.php @@ -915,11 +915,8 @@ public function get(string $name) * Returns whether a child with the given name exists (implements the \ArrayAccess interface). * * @param string $name The name of the child - * - * @return bool */ - #[\ReturnTypeWillChange] - public function offsetExists(mixed $name) + public function offsetExists(mixed $name): bool { return $this->has($name); } @@ -929,12 +926,9 @@ public function offsetExists(mixed $name) * * @param string $name The name of the child * - * @return FormInterface The child form - * * @throws OutOfBoundsException if the named child does not exist */ - #[\ReturnTypeWillChange] - public function offsetGet(mixed $name) + public function offsetGet(mixed $name): FormInterface { return $this->get($name); } @@ -945,15 +939,12 @@ public function offsetGet(mixed $name) * @param string $name Ignored. The name of the child is used * @param FormInterface $child The child to be added * - * @return void - * * @throws AlreadySubmittedException if the form has already been submitted * @throws LogicException when trying to add a child to a non-compound form * * @see self::add() */ - #[\ReturnTypeWillChange] - public function offsetSet(mixed $name, mixed $child) + public function offsetSet(mixed $name, mixed $child): void { $this->add($child); } @@ -963,12 +954,9 @@ public function offsetSet(mixed $name, mixed $child) * * @param string $name The name of the child to remove * - * @return void - * * @throws AlreadySubmittedException if the form has already been submitted */ - #[\ReturnTypeWillChange] - public function offsetUnset(mixed $name) + public function offsetUnset(mixed $name): void { $this->remove($name); } @@ -976,10 +964,9 @@ public function offsetUnset(mixed $name) /** * Returns the iterator for this group. * - * @return \Traversable + * @return \Traversable */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): \Traversable { return $this->children; } @@ -989,8 +976,7 @@ public function getIterator() * * @return int The number of embedded form children */ - #[\ReturnTypeWillChange] - public function count() + public function count(): int { return \count($this->children); } diff --git a/FormBuilder.php b/FormBuilder.php index 7c88ddf977..66762cbbff 100644 --- a/FormBuilder.php +++ b/FormBuilder.php @@ -156,11 +156,7 @@ public function all() return $this->children; } - /** - * @return int - */ - #[\ReturnTypeWillChange] - public function count() + public function count(): int { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -212,10 +208,9 @@ public function getForm() /** * {@inheritdoc} * - * @return FormBuilderInterface[]|\Traversable + * @return \Traversable */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): \Traversable { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); diff --git a/FormErrorIterator.php b/FormErrorIterator.php index d1df25ebb1..43b8940759 100644 --- a/FormErrorIterator.php +++ b/FormErrorIterator.php @@ -88,11 +88,8 @@ public function getForm() /** * Returns the current element of the iterator. - * - * @return FormError|self An error or an iterator containing nested errors */ - #[\ReturnTypeWillChange] - public function current() + public function current(): FormError|self { return current($this->errors); } @@ -100,8 +97,7 @@ public function current() /** * Advances the iterator to the next position. */ - #[\ReturnTypeWillChange] - public function next() + public function next(): void { next($this->errors); } @@ -111,19 +107,15 @@ public function next() * * @return int The 0-indexed position */ - #[\ReturnTypeWillChange] - public function key() + public function key(): int { return key($this->errors); } /** * Returns whether the iterator's position is valid. - * - * @return bool Whether the iterator is valid */ - #[\ReturnTypeWillChange] - public function valid() + public function valid(): bool { return null !== key($this->errors); } @@ -134,8 +126,7 @@ public function valid() * This method detects if errors have been added to the form since the * construction of the iterator. */ - #[\ReturnTypeWillChange] - public function rewind() + public function rewind(): void { reset($this->errors); } @@ -144,11 +135,8 @@ public function rewind() * Returns whether a position exists in the iterator. * * @param int $position The position - * - * @return bool Whether that position exists */ - #[\ReturnTypeWillChange] - public function offsetExists(mixed $position) + public function offsetExists(mixed $position): bool { return isset($this->errors[$position]); } @@ -158,12 +146,9 @@ public function offsetExists(mixed $position) * * @param int $position The position * - * @return FormError|FormErrorIterator The element at the given position - * * @throws OutOfBoundsException If the given position does not exist */ - #[\ReturnTypeWillChange] - public function offsetGet(mixed $position) + public function offsetGet(mixed $position): FormError|self { if (!isset($this->errors[$position])) { throw new OutOfBoundsException('The offset '.$position.' does not exist.'); @@ -175,12 +160,9 @@ public function offsetGet(mixed $position) /** * Unsupported method. * - * @return void - * * @throws BadMethodCallException */ - #[\ReturnTypeWillChange] - public function offsetSet(mixed $position, mixed $value) + public function offsetSet(mixed $position, mixed $value): void { throw new BadMethodCallException('The iterator doesn\'t support modification of elements.'); } @@ -188,12 +170,9 @@ public function offsetSet(mixed $position, mixed $value) /** * Unsupported method. * - * @return void - * * @throws BadMethodCallException */ - #[\ReturnTypeWillChange] - public function offsetUnset(mixed $position) + public function offsetUnset(mixed $position): void { throw new BadMethodCallException('The iterator doesn\'t support modification of elements.'); } @@ -201,22 +180,16 @@ public function offsetUnset(mixed $position) /** * Returns whether the current element of the iterator can be recursed * into. - * - * @return bool Whether the current element is an instance of this class */ - #[\ReturnTypeWillChange] - public function hasChildren() + public function hasChildren(): bool { return current($this->errors) instanceof self; } /** * Alias of {@link current()}. - * - * @return self */ - #[\ReturnTypeWillChange] - public function getChildren() + public function getChildren(): self { return current($this->errors); } @@ -235,11 +208,8 @@ public function getChildren() * Alternatively, set the constructor argument $flatten to true as well. * * $count = count($form->getErrors(true, true)); - * - * @return int The number of iterated elements */ - #[\ReturnTypeWillChange] - public function count() + public function count(): int { return \count($this->errors); } @@ -247,12 +217,9 @@ public function count() /** * Sets the position of the iterator. * - * @return void - * * @throws OutOfBoundsException If the position is invalid */ - #[\ReturnTypeWillChange] - public function seek(int $position) + public function seek(int $position): void { if (!isset($this->errors[$position])) { throw new OutOfBoundsException('The offset '.$position.' does not exist.'); diff --git a/FormView.php b/FormView.php index b22ac50428..651d64af38 100644 --- a/FormView.php +++ b/FormView.php @@ -103,11 +103,8 @@ public function setMethodRendered() * Returns a child by name (implements \ArrayAccess). * * @param string $name The child name - * - * @return self The child view */ - #[\ReturnTypeWillChange] - public function offsetGet(mixed $name) + public function offsetGet(mixed $name): self { return $this->children[$name]; } @@ -116,11 +113,8 @@ public function offsetGet(mixed $name) * Returns whether the given child exists (implements \ArrayAccess). * * @param string $name The child name - * - * @return bool Whether the child view exists */ - #[\ReturnTypeWillChange] - public function offsetExists(mixed $name) + public function offsetExists(mixed $name): bool { return isset($this->children[$name]); } @@ -128,12 +122,9 @@ public function offsetExists(mixed $name) /** * Implements \ArrayAccess. * - * @return void - * * @throws BadMethodCallException always as setting a child by name is not allowed */ - #[\ReturnTypeWillChange] - public function offsetSet(mixed $name, mixed $value) + public function offsetSet(mixed $name, mixed $value): void { throw new BadMethodCallException('Not supported.'); } @@ -142,11 +133,8 @@ public function offsetSet(mixed $name, mixed $value) * Removes a child (implements \ArrayAccess). * * @param string $name The child name - * - * @return void */ - #[\ReturnTypeWillChange] - public function offsetUnset(mixed $name) + public function offsetUnset(mixed $name): void { unset($this->children[$name]); } @@ -156,19 +144,12 @@ public function offsetUnset(mixed $name) * * @return \ArrayIterator The iterator */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): \ArrayIterator { return new \ArrayIterator($this->children); } - /** - * Implements \Countable. - * - * @return int The number of children views - */ - #[\ReturnTypeWillChange] - public function count() + public function count(): int { return \count($this->children); } diff --git a/Util/InheritDataAwareIterator.php b/Util/InheritDataAwareIterator.php index 7cba17dbeb..26a2135223 100644 --- a/Util/InheritDataAwareIterator.php +++ b/Util/InheritDataAwareIterator.php @@ -25,22 +25,12 @@ */ class InheritDataAwareIterator extends \IteratorIterator implements \RecursiveIterator { - /** - * {@inheritdoc} - * - * @return static - */ - #[\ReturnTypeWillChange] - public function getChildren() + public function getChildren(): static { return new static($this->current()); } - /** - * @return bool - */ - #[\ReturnTypeWillChange] - public function hasChildren() + public function hasChildren(): bool { return (bool) $this->current()->getConfig()->getInheritData(); } diff --git a/Util/OrderedHashMap.php b/Util/OrderedHashMap.php index de9ddde220..eb13695668 100644 --- a/Util/OrderedHashMap.php +++ b/Util/OrderedHashMap.php @@ -92,22 +92,12 @@ public function __construct(array $elements = []) $this->orderedKeys = array_keys($elements); } - /** - * @return bool - */ - #[\ReturnTypeWillChange] - public function offsetExists(mixed $key) + public function offsetExists(mixed $key): bool { return isset($this->elements[$key]); } - /** - * {@inheritdoc} - * - * @return mixed - */ - #[\ReturnTypeWillChange] - public function offsetGet(mixed $key) + public function offsetGet(mixed $key): mixed { if (!isset($this->elements[$key])) { throw new \OutOfBoundsException(sprintf('The offset "%s" does not exist.', $key)); @@ -116,13 +106,7 @@ public function offsetGet(mixed $key) return $this->elements[$key]; } - /** - * {@inheritdoc} - * - * @return void - */ - #[\ReturnTypeWillChange] - public function offsetSet(mixed $key, mixed $value) + public function offsetSet(mixed $key, mixed $value): void { if (null === $key || !isset($this->elements[$key])) { if (null === $key) { @@ -140,13 +124,7 @@ public function offsetSet(mixed $key, mixed $value) $this->elements[$key] = $value; } - /** - * {@inheritdoc} - * - * @return void - */ - #[\ReturnTypeWillChange] - public function offsetUnset(mixed $key) + public function offsetUnset(mixed $key): void { if (false !== ($position = array_search((string) $key, $this->orderedKeys))) { array_splice($this->orderedKeys, $position, 1); @@ -160,20 +138,12 @@ public function offsetUnset(mixed $key) } } - /** - * @return \Traversable - */ - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): \Traversable { return new OrderedHashMapIterator($this->elements, $this->orderedKeys, $this->managedCursors); } - /** - * @return int - */ - #[\ReturnTypeWillChange] - public function count() + public function count(): int { return \count($this->elements); } diff --git a/Util/OrderedHashMapIterator.php b/Util/OrderedHashMapIterator.php index b7ee3a5da8..14008e649a 100644 --- a/Util/OrderedHashMapIterator.php +++ b/Util/OrderedHashMapIterator.php @@ -73,7 +73,6 @@ public function __destruct() /** * {@inheritdoc} */ - #[\ReturnTypeWillChange] public function current(): mixed { return $this->current; @@ -98,7 +97,6 @@ public function next(): void /** * {@inheritdoc} */ - #[\ReturnTypeWillChange] public function key(): mixed { if (null === $this->key) { From 543d9a9edbab363c885b71cfb50bf9c5d44c3f3e Mon Sep 17 00:00:00 2001 From: Tobias Schultze Date: Mon, 16 Aug 2021 16:32:57 +0200 Subject: [PATCH 021/208] fix merge --- FormConfigBuilder.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 479d70c45c..d871eaa61d 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -53,8 +53,8 @@ class FormConfigBuilder implements FormConfigBuilderInterface private mixed $data = null; private ?string $dataClass; private bool $dataLocked = false; - private ?FormFactoryInterface $formFactory = null; - private string $action; + private FormFactoryInterface $formFactory; + private string $action = ''; private string $method = 'POST'; private RequestHandlerInterface $requestHandler; private bool $autoInitialize = false; From 00aeda6dd3003d186dc5ff1df9979b67022c099a Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 12 Aug 2021 18:48:48 +0200 Subject: [PATCH 022/208] Add return types - batch 6/n --- AbstractExtension.php | 12 +- AbstractRendererEngine.php | 6 +- Button.php | 64 ++++----- ButtonBuilder.php | 127 +++++++++--------- CallbackTransformer.php | 4 +- ChoiceList/ArrayChoiceList.php | 12 +- ChoiceList/ChoiceListInterface.php | 12 +- .../Factory/CachingFactoryDecorator.php | 8 +- .../Factory/ChoiceListFactoryInterface.php | 6 +- .../Factory/DefaultChoiceListFactory.php | 6 +- .../Factory/PropertyAccessDecorator.php | 14 +- ChoiceList/LazyChoiceList.php | 12 +- ChoiceList/Loader/AbstractChoiceLoader.php | 4 +- ChoiceList/Loader/ChoiceLoaderInterface.php | 6 +- .../Loader/IntlCallbackChoiceLoader.php | 4 +- ChoiceList/View/ChoiceListView.php | 4 +- ClickableInterface.php | 2 +- Command/DebugCommand.php | 2 +- DataAccessorInterface.php | 2 +- Extension/Core/CoreExtension.php | 4 +- .../Core/DataAccessor/CallbackAccessor.php | 2 +- Extension/Core/DataAccessor/ChainAccessor.php | 2 +- .../DataAccessor/PropertyPathAccessor.php | 2 +- .../ArrayToPartsTransformer.php | 4 +- .../BooleanToStringTransformer.php | 4 +- .../ChoiceToValueTransformer.php | 4 +- .../ChoicesToValuesTransformer.php | 8 +- .../DataTransformer/DataTransformerChain.php | 6 +- .../DateIntervalToArrayTransformer.php | 4 +- .../DateIntervalToStringTransformer.php | 6 +- .../DateTimeToArrayTransformer.php | 4 +- ...ateTimeToHtml5LocalDateTimeTransformer.php | 4 +- .../DateTimeToLocalizedStringTransformer.php | 12 +- .../DateTimeToRfc3339Transformer.php | 4 +- .../DateTimeToStringTransformer.php | 6 +- .../DateTimeToTimestampTransformer.php | 4 +- .../DateTimeZoneToStringTransformer.php | 4 +- .../IntegerToLocalizedStringTransformer.php | 2 +- .../IntlTimeZoneToStringTransformer.php | 6 +- .../MoneyToLocalizedStringTransformer.php | 4 +- .../NumberToLocalizedStringTransformer.php | 8 +- .../PercentToLocalizedStringTransformer.php | 10 +- .../StringToFloatTransformer.php | 14 +- .../UlidToStringTransformer.php | 6 +- .../UuidToStringTransformer.php | 6 +- .../ValueToDuplicatesTransformer.php | 4 +- .../WeekToArrayTransformer.php | 4 +- .../EventListener/FixUrlProtocolListener.php | 2 +- .../EventListener/MergeCollectionListener.php | 2 +- .../Core/EventListener/ResizeFormListener.php | 2 +- .../TransformationFailureListener.php | 2 +- Extension/Core/EventListener/TrimListener.php | 2 +- Extension/Core/Type/BirthdayType.php | 4 +- Extension/Core/Type/ButtonType.php | 4 +- Extension/Core/Type/CheckboxType.php | 2 +- Extension/Core/Type/ChoiceType.php | 2 +- Extension/Core/Type/CollectionType.php | 2 +- Extension/Core/Type/ColorType.php | 4 +- Extension/Core/Type/CountryType.php | 4 +- Extension/Core/Type/CurrencyType.php | 4 +- Extension/Core/Type/DateIntervalType.php | 2 +- Extension/Core/Type/DateTimeType.php | 2 +- Extension/Core/Type/DateType.php | 2 +- Extension/Core/Type/EmailType.php | 4 +- Extension/Core/Type/FileType.php | 2 +- Extension/Core/Type/FormType.php | 4 +- Extension/Core/Type/HiddenType.php | 2 +- Extension/Core/Type/IntegerType.php | 2 +- Extension/Core/Type/LanguageType.php | 4 +- Extension/Core/Type/LocaleType.php | 4 +- Extension/Core/Type/MoneyType.php | 2 +- Extension/Core/Type/NumberType.php | 2 +- Extension/Core/Type/PasswordType.php | 4 +- Extension/Core/Type/PercentType.php | 2 +- Extension/Core/Type/RadioType.php | 4 +- Extension/Core/Type/RangeType.php | 4 +- Extension/Core/Type/RepeatedType.php | 2 +- Extension/Core/Type/ResetType.php | 4 +- Extension/Core/Type/SearchType.php | 4 +- Extension/Core/Type/SubmitType.php | 4 +- Extension/Core/Type/TelType.php | 5 +- Extension/Core/Type/TextType.php | 6 +- Extension/Core/Type/TextareaType.php | 4 +- Extension/Core/Type/TimeType.php | 2 +- Extension/Core/Type/TimezoneType.php | 4 +- Extension/Core/Type/UlidType.php | 1 - Extension/Core/Type/UrlType.php | 5 +- Extension/Core/Type/UuidType.php | 1 - Extension/Core/Type/WeekType.php | 2 +- Extension/Csrf/CsrfExtension.php | 2 +- .../EventListener/CsrfValidationListener.php | 2 +- .../DataCollector/DataCollectorExtension.php | 2 +- .../EventListener/DataCollectorListener.php | 2 +- Extension/DataCollector/FormDataCollector.php | 3 +- .../FormDataCollectorInterface.php | 2 +- Extension/DataCollector/FormDataExtractor.php | 8 +- .../FormDataExtractorInterface.php | 8 +- .../Proxy/ResolvedTypeDataCollectorProxy.php | 16 ++- .../ResolvedTypeFactoryDataCollectorProxy.php | 2 +- .../DependencyInjectionExtension.php | 12 +- .../HttpFoundationExtension.php | 2 +- .../HttpFoundationRequestHandler.php | 7 +- Extension/Validator/Constraints/Form.php | 2 +- .../EventListener/ValidationListener.php | 2 +- Extension/Validator/ValidatorExtension.php | 5 +- Extension/Validator/ValidatorTypeGuesser.php | 18 +-- .../Validator/ViolationMapper/MappingRule.php | 13 +- .../ViolationMapper/RelativePath.php | 5 +- .../ViolationMapper/ViolationPath.php | 14 +- Form.php | 64 ++++----- FormBuilder.php | 16 +-- FormBuilderInterface.php | 24 +--- FormConfigBuilder.php | 110 +++++++-------- FormConfigBuilderInterface.php | 54 ++++---- FormConfigInterface.php | 58 ++++---- FormError.php | 20 +-- FormErrorIterator.php | 6 +- FormEvent.php | 8 +- FormExtensionInterface.php | 10 +- FormFactory.php | 12 +- FormFactoryBuilder.php | 20 +-- FormFactoryBuilderInterface.php | 20 +-- FormFactoryInterface.php | 12 +- FormInterface.php | 80 +++++------ FormRegistry.php | 8 +- FormRegistryInterface.php | 10 +- FormRenderer.php | 10 +- FormRendererEngineInterface.php | 6 +- FormRendererInterface.php | 10 +- FormTypeGuesserChain.php | 10 +- FormView.php | 9 +- Guess/Guess.php | 6 +- Guess/TypeGuess.php | 8 +- Guess/ValueGuess.php | 2 +- NativeRequestHandler.php | 7 +- PreloadedExtension.php | 10 +- RequestHandlerInterface.php | 4 +- ResolvedFormType.php | 25 ++-- ResolvedFormTypeFactory.php | 2 +- ResolvedFormTypeFactoryInterface.php | 4 +- ResolvedFormTypeInterface.php | 14 +- ReversedTransformer.php | 4 +- SubmitButton.php | 4 +- SubmitButtonBuilder.php | 2 +- Test/FormPerformanceTestCase.php | 5 +- Tests/FormBuilderTest.php | 1 - Util/FormUtil.php | 4 +- Util/OptionsResolverWrapper.php | 10 +- Util/ServerParams.php | 14 +- Util/StringUtil.php | 6 +- 150 files changed, 642 insertions(+), 775 deletions(-) diff --git a/AbstractExtension.php b/AbstractExtension.php index 8d8d6f7e64..7aff58e574 100644 --- a/AbstractExtension.php +++ b/AbstractExtension.php @@ -46,7 +46,7 @@ abstract class AbstractExtension implements FormExtensionInterface /** * {@inheritdoc} */ - public function getType(string $name) + public function getType(string $name): FormTypeInterface { if (!isset($this->types)) { $this->initTypes(); @@ -62,7 +62,7 @@ public function getType(string $name) /** * {@inheritdoc} */ - public function hasType(string $name) + public function hasType(string $name): bool { if (!isset($this->types)) { $this->initTypes(); @@ -74,7 +74,7 @@ public function hasType(string $name) /** * {@inheritdoc} */ - public function getTypeExtensions(string $name) + public function getTypeExtensions(string $name): array { if (!isset($this->typeExtensions)) { $this->initTypeExtensions(); @@ -87,7 +87,7 @@ public function getTypeExtensions(string $name) /** * {@inheritdoc} */ - public function hasTypeExtensions(string $name) + public function hasTypeExtensions(string $name): bool { if (!isset($this->typeExtensions)) { $this->initTypeExtensions(); @@ -99,7 +99,7 @@ public function hasTypeExtensions(string $name) /** * {@inheritdoc} */ - public function getTypeGuesser() + public function getTypeGuesser(): ?FormTypeGuesserInterface { if (!$this->typeGuesserLoaded) { $this->initTypeGuesser(); @@ -123,7 +123,7 @@ protected function loadTypes() * * @return FormTypeExtensionInterface[] */ - protected function loadTypeExtensions() + protected function loadTypeExtensions(): array { return []; } diff --git a/AbstractRendererEngine.php b/AbstractRendererEngine.php index 6263397605..5ba525fe8a 100644 --- a/AbstractRendererEngine.php +++ b/AbstractRendererEngine.php @@ -79,7 +79,7 @@ public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = /** * {@inheritdoc} */ - public function getResourceForBlockName(FormView $view, string $blockName) + public function getResourceForBlockName(FormView $view, string $blockName): mixed { $cacheKey = $view->vars[self::CACHE_KEY_VAR]; @@ -93,7 +93,7 @@ public function getResourceForBlockName(FormView $view, string $blockName) /** * {@inheritdoc} */ - public function getResourceForBlockNameHierarchy(FormView $view, array $blockNameHierarchy, int $hierarchyLevel) + public function getResourceForBlockNameHierarchy(FormView $view, array $blockNameHierarchy, int $hierarchyLevel): mixed { $cacheKey = $view->vars[self::CACHE_KEY_VAR]; $blockName = $blockNameHierarchy[$hierarchyLevel]; @@ -108,7 +108,7 @@ public function getResourceForBlockNameHierarchy(FormView $view, array $blockNam /** * {@inheritdoc} */ - public function getResourceHierarchyLevel(FormView $view, array $blockNameHierarchy, int $hierarchyLevel) + public function getResourceHierarchyLevel(FormView $view, array $blockNameHierarchy, int $hierarchyLevel): int|bool { $cacheKey = $view->vars[self::CACHE_KEY_VAR]; $blockName = $blockNameHierarchy[$hierarchyLevel]; diff --git a/Button.php b/Button.php index 76cb6dd1e6..0cd90bc08b 100644 --- a/Button.php +++ b/Button.php @@ -13,6 +13,8 @@ use Symfony\Component\Form\Exception\AlreadySubmittedException; use Symfony\Component\Form\Exception\BadMethodCallException; +use Symfony\Component\Form\Exception\TransformationFailedException; +use Symfony\Component\PropertyAccess\PropertyPathInterface; /** * A form button. @@ -82,7 +84,7 @@ public function offsetUnset(mixed $offset): void /** * {@inheritdoc} */ - public function setParent(FormInterface $parent = null) + public function setParent(FormInterface $parent = null): static { if ($this->submitted) { throw new AlreadySubmittedException('You cannot set the parent of a submitted button.'); @@ -96,7 +98,7 @@ public function setParent(FormInterface $parent = null) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?FormInterface { return $this->parent; } @@ -108,7 +110,7 @@ public function getParent() * * @throws BadMethodCallException */ - public function add(string|FormInterface $child, string $type = null, array $options = []) + public function add(string|FormInterface $child, string $type = null, array $options = []): static { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -120,7 +122,7 @@ public function add(string|FormInterface $child, string $type = null, array $opt * * @throws BadMethodCallException */ - public function get(string $name) + public function get(string $name): FormInterface { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -130,7 +132,7 @@ public function get(string $name) * * @return bool Always returns false */ - public function has(string $name) + public function has(string $name): bool { return false; } @@ -142,7 +144,7 @@ public function has(string $name) * * @throws BadMethodCallException */ - public function remove(string $name) + public function remove(string $name): static { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -150,7 +152,7 @@ public function remove(string $name) /** * {@inheritdoc} */ - public function all() + public function all(): array { return []; } @@ -158,7 +160,7 @@ public function all() /** * {@inheritdoc} */ - public function getErrors(bool $deep = false, bool $flatten = true) + public function getErrors(bool $deep = false, bool $flatten = true): FormErrorIterator { return new FormErrorIterator($this, []); } @@ -170,7 +172,7 @@ public function getErrors(bool $deep = false, bool $flatten = true) * * @return $this */ - public function setData(mixed $modelData) + public function setData(mixed $modelData): static { // no-op, called during initialization of the form tree return $this; @@ -179,7 +181,7 @@ public function setData(mixed $modelData) /** * Unsupported method. */ - public function getData() + public function getData(): mixed { return null; } @@ -187,7 +189,7 @@ public function getData() /** * Unsupported method. */ - public function getNormData() + public function getNormData(): mixed { return null; } @@ -195,7 +197,7 @@ public function getNormData() /** * Unsupported method. */ - public function getViewData() + public function getViewData(): mixed { return null; } @@ -205,17 +207,15 @@ public function getViewData() * * @return array Always returns an empty array */ - public function getExtraData() + public function getExtraData(): array { return []; } /** * Returns the button's configuration. - * - * @return FormConfigInterface */ - public function getConfig() + public function getConfig(): FormConfigInterface { return $this->config; } @@ -225,7 +225,7 @@ public function getConfig() * * @return bool true if the button was submitted */ - public function isSubmitted() + public function isSubmitted(): bool { return $this->submitted; } @@ -235,7 +235,7 @@ public function isSubmitted() * * @return string The name of the button */ - public function getName() + public function getName(): string { return $this->config->getName(); } @@ -243,7 +243,7 @@ public function getName() /** * Unsupported method. */ - public function getPropertyPath() + public function getPropertyPath(): ?PropertyPathInterface { return null; } @@ -253,7 +253,7 @@ public function getPropertyPath() * * @throws BadMethodCallException */ - public function addError(FormError $error) + public function addError(FormError $error): static { throw new BadMethodCallException('Buttons cannot have errors.'); } @@ -263,7 +263,7 @@ public function addError(FormError $error) * * @return bool Always returns true */ - public function isValid() + public function isValid(): bool { return true; } @@ -273,7 +273,7 @@ public function isValid() * * @return bool Always returns false */ - public function isRequired() + public function isRequired(): bool { return false; } @@ -281,7 +281,7 @@ public function isRequired() /** * {@inheritdoc} */ - public function isDisabled() + public function isDisabled(): bool { if ($this->parent && $this->parent->isDisabled()) { return true; @@ -295,7 +295,7 @@ public function isDisabled() * * @return bool Always returns true */ - public function isEmpty() + public function isEmpty(): bool { return true; } @@ -305,7 +305,7 @@ public function isEmpty() * * @return bool Always returns true */ - public function isSynchronized() + public function isSynchronized(): bool { return true; } @@ -313,7 +313,7 @@ public function isSynchronized() /** * Unsupported method. */ - public function getTransformationFailure() + public function getTransformationFailure(): ?TransformationFailedException { return null; } @@ -323,7 +323,7 @@ public function getTransformationFailure() * * @throws BadMethodCallException */ - public function initialize() + public function initialize(): static { throw new BadMethodCallException('Buttons cannot be initialized. Call initialize() on the root form instead.'); } @@ -333,7 +333,7 @@ public function initialize() * * @throws BadMethodCallException */ - public function handleRequest(mixed $request = null) + public function handleRequest(mixed $request = null): static { throw new BadMethodCallException('Buttons cannot handle requests. Call handleRequest() on the root form instead.'); } @@ -345,7 +345,7 @@ public function handleRequest(mixed $request = null) * * @throws Exception\AlreadySubmittedException if the button has already been submitted */ - public function submit(array|string|null $submittedData, bool $clearMissing = true) + public function submit(array|string|null $submittedData, bool $clearMissing = true): static { if ($this->submitted) { throw new AlreadySubmittedException('A form can only be submitted once.'); @@ -359,7 +359,7 @@ public function submit(array|string|null $submittedData, bool $clearMissing = tr /** * {@inheritdoc} */ - public function getRoot() + public function getRoot(): FormInterface { return $this->parent ? $this->parent->getRoot() : $this; } @@ -367,7 +367,7 @@ public function getRoot() /** * {@inheritdoc} */ - public function isRoot() + public function isRoot(): bool { return null === $this->parent; } @@ -375,7 +375,7 @@ public function isRoot() /** * {@inheritdoc} */ - public function createView(FormView $parent = null) + public function createView(FormView $parent = null): FormView { if (null === $parent && $this->parent) { $parent = $this->parent->createView(); diff --git a/ButtonBuilder.php b/ButtonBuilder.php index b6a2b60538..61b5ea9675 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Form\Exception\BadMethodCallException; use Symfony\Component\Form\Exception\InvalidArgumentException; @@ -51,7 +52,7 @@ public function __construct(?string $name, array $options = []) * * @throws BadMethodCallException */ - public function add(string|FormBuilderInterface $child, string $type = null, array $options = []) + public function add(string|FormBuilderInterface $child, string $type = null, array $options = []): static { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -61,7 +62,7 @@ public function add(string|FormBuilderInterface $child, string $type = null, arr * * @throws BadMethodCallException */ - public function create(string $name, string $type = null, array $options = []) + public function create(string $name, string $type = null, array $options = []): FormBuilderInterface { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -71,7 +72,7 @@ public function create(string $name, string $type = null, array $options = []) * * @throws BadMethodCallException */ - public function get(string $name) + public function get(string $name): FormBuilderInterface { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -81,7 +82,7 @@ public function get(string $name) * * @throws BadMethodCallException */ - public function remove(string $name) + public function remove(string $name): static { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -91,7 +92,7 @@ public function remove(string $name) * * @return bool Always returns false */ - public function has(string $name) + public function has(string $name): bool { return false; } @@ -101,7 +102,7 @@ public function has(string $name) * * @return array Always returns an empty array */ - public function all() + public function all(): array { return []; } @@ -111,7 +112,7 @@ public function all() * * @return Button The button */ - public function getForm() + public function getForm(): Button { return new Button($this->getFormConfig()); } @@ -121,7 +122,7 @@ public function getForm() * * @throws BadMethodCallException */ - public function addEventListener(string $eventName, callable $listener, int $priority = 0) + public function addEventListener(string $eventName, callable $listener, int $priority = 0): static { throw new BadMethodCallException('Buttons do not support event listeners.'); } @@ -131,7 +132,7 @@ public function addEventListener(string $eventName, callable $listener, int $pri * * @throws BadMethodCallException */ - public function addEventSubscriber(EventSubscriberInterface $subscriber) + public function addEventSubscriber(EventSubscriberInterface $subscriber): static { throw new BadMethodCallException('Buttons do not support event subscribers.'); } @@ -141,7 +142,7 @@ public function addEventSubscriber(EventSubscriberInterface $subscriber) * * @throws BadMethodCallException */ - public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false) + public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false): static { throw new BadMethodCallException('Buttons do not support data transformers.'); } @@ -151,7 +152,7 @@ public function addViewTransformer(DataTransformerInterface $viewTransformer, bo * * @throws BadMethodCallException */ - public function resetViewTransformers() + public function resetViewTransformers(): static { throw new BadMethodCallException('Buttons do not support data transformers.'); } @@ -161,7 +162,7 @@ public function resetViewTransformers() * * @throws BadMethodCallException */ - public function addModelTransformer(DataTransformerInterface $modelTransformer, bool $forceAppend = false) + public function addModelTransformer(DataTransformerInterface $modelTransformer, bool $forceAppend = false): static { throw new BadMethodCallException('Buttons do not support data transformers.'); } @@ -171,7 +172,7 @@ public function addModelTransformer(DataTransformerInterface $modelTransformer, * * @throws BadMethodCallException */ - public function resetModelTransformers() + public function resetModelTransformers(): static { throw new BadMethodCallException('Buttons do not support data transformers.'); } @@ -179,7 +180,7 @@ public function resetModelTransformers() /** * {@inheritdoc} */ - public function setAttribute(string $name, mixed $value) + public function setAttribute(string $name, mixed $value): static { $this->attributes[$name] = $value; @@ -189,7 +190,7 @@ public function setAttribute(string $name, mixed $value) /** * {@inheritdoc} */ - public function setAttributes(array $attributes) + public function setAttributes(array $attributes): static { $this->attributes = $attributes; @@ -201,7 +202,7 @@ public function setAttributes(array $attributes) * * @throws BadMethodCallException */ - public function setDataMapper(DataMapperInterface $dataMapper = null) + public function setDataMapper(DataMapperInterface $dataMapper = null): static { throw new BadMethodCallException('Buttons do not support data mappers.'); } @@ -211,7 +212,7 @@ public function setDataMapper(DataMapperInterface $dataMapper = null) * * @return $this */ - public function setDisabled(bool $disabled) + public function setDisabled(bool $disabled): static { $this->disabled = $disabled; @@ -223,7 +224,7 @@ public function setDisabled(bool $disabled) * * @throws BadMethodCallException */ - public function setEmptyData(mixed $emptyData) + public function setEmptyData(mixed $emptyData): static { throw new BadMethodCallException('Buttons do not support empty data.'); } @@ -233,7 +234,7 @@ public function setEmptyData(mixed $emptyData) * * @throws BadMethodCallException */ - public function setErrorBubbling(bool $errorBubbling) + public function setErrorBubbling(bool $errorBubbling): static { throw new BadMethodCallException('Buttons do not support error bubbling.'); } @@ -243,7 +244,7 @@ public function setErrorBubbling(bool $errorBubbling) * * @throws BadMethodCallException */ - public function setRequired(bool $required) + public function setRequired(bool $required): static { throw new BadMethodCallException('Buttons cannot be required.'); } @@ -253,7 +254,7 @@ public function setRequired(bool $required) * * @throws BadMethodCallException */ - public function setPropertyPath(string|PropertyPathInterface|null $propertyPath) + public function setPropertyPath(string|PropertyPathInterface|null $propertyPath): static { throw new BadMethodCallException('Buttons do not support property paths.'); } @@ -263,7 +264,7 @@ public function setPropertyPath(string|PropertyPathInterface|null $propertyPath) * * @throws BadMethodCallException */ - public function setMapped(bool $mapped) + public function setMapped(bool $mapped): static { throw new BadMethodCallException('Buttons do not support data mapping.'); } @@ -273,7 +274,7 @@ public function setMapped(bool $mapped) * * @throws BadMethodCallException */ - public function setByReference(bool $byReference) + public function setByReference(bool $byReference): static { throw new BadMethodCallException('Buttons do not support data mapping.'); } @@ -283,7 +284,7 @@ public function setByReference(bool $byReference) * * @throws BadMethodCallException */ - public function setCompound(bool $compound) + public function setCompound(bool $compound): static { throw new BadMethodCallException('Buttons cannot be compound.'); } @@ -293,7 +294,7 @@ public function setCompound(bool $compound) * * @return $this */ - public function setType(ResolvedFormTypeInterface $type) + public function setType(ResolvedFormTypeInterface $type): static { $this->type = $type; @@ -305,7 +306,7 @@ public function setType(ResolvedFormTypeInterface $type) * * @throws BadMethodCallException */ - public function setData(mixed $data) + public function setData(mixed $data): static { throw new BadMethodCallException('Buttons do not support data.'); } @@ -315,7 +316,7 @@ public function setData(mixed $data) * * @throws BadMethodCallException */ - public function setDataLocked(bool $locked) + public function setDataLocked(bool $locked): static { throw new BadMethodCallException('Buttons do not support data locking.'); } @@ -335,7 +336,7 @@ public function setFormFactory(FormFactoryInterface $formFactory) * * @throws BadMethodCallException */ - public function setAction(string $action) + public function setAction(string $action): static { throw new BadMethodCallException('Buttons do not support actions.'); } @@ -345,7 +346,7 @@ public function setAction(string $action) * * @throws BadMethodCallException */ - public function setMethod(string $method) + public function setMethod(string $method): static { throw new BadMethodCallException('Buttons do not support methods.'); } @@ -355,7 +356,7 @@ public function setMethod(string $method) * * @throws BadMethodCallException */ - public function setRequestHandler(RequestHandlerInterface $requestHandler) + public function setRequestHandler(RequestHandlerInterface $requestHandler): static { throw new BadMethodCallException('Buttons do not support request handlers.'); } @@ -367,7 +368,7 @@ public function setRequestHandler(RequestHandlerInterface $requestHandler) * * @throws BadMethodCallException */ - public function setAutoInitialize(bool $initialize) + public function setAutoInitialize(bool $initialize): static { if (true === $initialize) { throw new BadMethodCallException('Buttons do not support automatic initialization.'); @@ -381,17 +382,15 @@ public function setAutoInitialize(bool $initialize) * * @throws BadMethodCallException */ - public function setInheritData(bool $inheritData) + public function setInheritData(bool $inheritData): static { throw new BadMethodCallException('Buttons do not support data inheritance.'); } /** * Builds and returns the button configuration. - * - * @return FormConfigInterface */ - public function getFormConfig() + public function getFormConfig(): FormConfigInterface { // This method should be idempotent, so clone the builder $config = clone $this; @@ -415,7 +414,7 @@ public function setIsEmptyCallback(?callable $isEmptyCallback): static * * @throws BadMethodCallException */ - public function getEventDispatcher() + public function getEventDispatcher(): EventDispatcherInterface { throw new BadMethodCallException('Buttons do not support event dispatching.'); } @@ -423,7 +422,7 @@ public function getEventDispatcher() /** * {@inheritdoc} */ - public function getName() + public function getName(): string { return $this->name; } @@ -431,7 +430,7 @@ public function getName() /** * Unsupported method. */ - public function getPropertyPath() + public function getPropertyPath(): ?PropertyPathInterface { return null; } @@ -441,7 +440,7 @@ public function getPropertyPath() * * @return bool Always returns false */ - public function getMapped() + public function getMapped(): bool { return false; } @@ -451,7 +450,7 @@ public function getMapped() * * @return bool Always returns false */ - public function getByReference() + public function getByReference(): bool { return false; } @@ -461,7 +460,7 @@ public function getByReference() * * @return bool Always returns false */ - public function getCompound() + public function getCompound(): bool { return false; } @@ -471,7 +470,7 @@ public function getCompound() * * @return ResolvedFormTypeInterface The button's type */ - public function getType() + public function getType(): ResolvedFormTypeInterface { return $this->type; } @@ -481,7 +480,7 @@ public function getType() * * @return array Always returns an empty array */ - public function getViewTransformers() + public function getViewTransformers(): array { return []; } @@ -491,7 +490,7 @@ public function getViewTransformers() * * @return array Always returns an empty array */ - public function getModelTransformers() + public function getModelTransformers(): array { return []; } @@ -499,7 +498,7 @@ public function getModelTransformers() /** * Unsupported method. */ - public function getDataMapper() + public function getDataMapper(): ?DataMapperInterface { return null; } @@ -509,7 +508,7 @@ public function getDataMapper() * * @return bool Always returns false */ - public function getRequired() + public function getRequired(): bool { return false; } @@ -519,7 +518,7 @@ public function getRequired() * * @return bool Whether the button is disabled */ - public function getDisabled() + public function getDisabled(): bool { return $this->disabled; } @@ -529,7 +528,7 @@ public function getDisabled() * * @return bool Always returns false */ - public function getErrorBubbling() + public function getErrorBubbling(): bool { return false; } @@ -537,7 +536,7 @@ public function getErrorBubbling() /** * Unsupported method. */ - public function getEmptyData() + public function getEmptyData(): mixed { return null; } @@ -547,7 +546,7 @@ public function getEmptyData() * * @return array An array of key-value combinations */ - public function getAttributes() + public function getAttributes(): array { return $this->attributes; } @@ -557,7 +556,7 @@ public function getAttributes() * * @return bool Whether the attribute exists */ - public function hasAttribute(string $name) + public function hasAttribute(string $name): bool { return \array_key_exists($name, $this->attributes); } @@ -567,7 +566,7 @@ public function hasAttribute(string $name) * * @return mixed The attribute value */ - public function getAttribute(string $name, mixed $default = null) + public function getAttribute(string $name, mixed $default = null): mixed { return \array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; } @@ -575,7 +574,7 @@ public function getAttribute(string $name, mixed $default = null) /** * Unsupported method. */ - public function getData() + public function getData(): mixed { return null; } @@ -583,7 +582,7 @@ public function getData() /** * Unsupported method. */ - public function getDataClass() + public function getDataClass(): ?string { return null; } @@ -593,7 +592,7 @@ public function getDataClass() * * @return bool Always returns false */ - public function getDataLocked() + public function getDataLocked(): bool { return false; } @@ -601,7 +600,7 @@ public function getDataLocked() /** * Unsupported method. */ - public function getFormFactory() + public function getFormFactory(): FormFactoryInterface { throw new BadMethodCallException('Buttons do not support adding children.'); } @@ -611,7 +610,7 @@ public function getFormFactory() * * @throws BadMethodCallException */ - public function getAction() + public function getAction(): string { throw new BadMethodCallException('Buttons do not support actions.'); } @@ -621,7 +620,7 @@ public function getAction() * * @throws BadMethodCallException */ - public function getMethod() + public function getMethod(): string { throw new BadMethodCallException('Buttons do not support methods.'); } @@ -631,7 +630,7 @@ public function getMethod() * * @throws BadMethodCallException */ - public function getRequestHandler() + public function getRequestHandler(): RequestHandlerInterface { throw new BadMethodCallException('Buttons do not support request handlers.'); } @@ -641,7 +640,7 @@ public function getRequestHandler() * * @return bool Always returns false */ - public function getAutoInitialize() + public function getAutoInitialize(): bool { return false; } @@ -651,7 +650,7 @@ public function getAutoInitialize() * * @return bool Always returns false */ - public function getInheritData() + public function getInheritData(): bool { return false; } @@ -661,7 +660,7 @@ public function getInheritData() * * @return array The passed options */ - public function getOptions() + public function getOptions(): array { return $this->options; } @@ -671,7 +670,7 @@ public function getOptions() * * @return bool Whether the option exists */ - public function hasOption(string $name) + public function hasOption(string $name): bool { return \array_key_exists($name, $this->options); } @@ -681,7 +680,7 @@ public function hasOption(string $name) * * @return mixed The option value */ - public function getOption(string $name, mixed $default = null) + public function getOption(string $name, mixed $default = null): mixed { return \array_key_exists($name, $this->options) ? $this->options[$name] : $default; } diff --git a/CallbackTransformer.php b/CallbackTransformer.php index 189a0fd5da..c5ec2a1050 100644 --- a/CallbackTransformer.php +++ b/CallbackTransformer.php @@ -25,7 +25,7 @@ public function __construct(callable $transform, callable $reverseTransform) /** * {@inheritdoc} */ - public function transform(mixed $data) + public function transform(mixed $data): mixed { return ($this->transform)($data); } @@ -33,7 +33,7 @@ public function transform(mixed $data) /** * {@inheritdoc} */ - public function reverseTransform(mixed $data) + public function reverseTransform(mixed $data): mixed { return ($this->reverseTransform)($data); } diff --git a/ChoiceList/ArrayChoiceList.php b/ChoiceList/ArrayChoiceList.php index 49b991a465..49bce1837c 100644 --- a/ChoiceList/ArrayChoiceList.php +++ b/ChoiceList/ArrayChoiceList.php @@ -93,7 +93,7 @@ public function __construct(iterable $choices, callable $value = null) /** * {@inheritdoc} */ - public function getChoices() + public function getChoices(): array { return $this->choices; } @@ -101,7 +101,7 @@ public function getChoices() /** * {@inheritdoc} */ - public function getValues() + public function getValues(): array { return array_map('strval', array_keys($this->choices)); } @@ -109,7 +109,7 @@ public function getValues() /** * {@inheritdoc} */ - public function getStructuredValues() + public function getStructuredValues(): array { return $this->structuredValues; } @@ -117,7 +117,7 @@ public function getStructuredValues() /** * {@inheritdoc} */ - public function getOriginalKeys() + public function getOriginalKeys(): array { return $this->originalKeys; } @@ -125,7 +125,7 @@ public function getOriginalKeys() /** * {@inheritdoc} */ - public function getChoicesForValues(array $values) + public function getChoicesForValues(array $values): array { $choices = []; @@ -141,7 +141,7 @@ public function getChoicesForValues(array $values) /** * {@inheritdoc} */ - public function getValuesForChoices(array $choices) + public function getValuesForChoices(array $choices): array { $values = []; diff --git a/ChoiceList/ChoiceListInterface.php b/ChoiceList/ChoiceListInterface.php index 9435309dd5..1742ca608e 100644 --- a/ChoiceList/ChoiceListInterface.php +++ b/ChoiceList/ChoiceListInterface.php @@ -30,7 +30,7 @@ interface ChoiceListInterface * * @return array The selectable choices indexed by the corresponding values */ - public function getChoices(); + public function getChoices(): array; /** * Returns the values for the choices. @@ -57,7 +57,7 @@ public function getChoices(); * * @return string[] The choice values */ - public function getValues(); + public function getValues(): array; /** * Returns the values in the structure originally passed to the list. @@ -88,7 +88,7 @@ public function getValues(); * * @return string[] The choice values */ - public function getStructuredValues(); + public function getStructuredValues(): array; /** * Returns the original keys of the choices. @@ -110,7 +110,7 @@ public function getStructuredValues(); * @return int[]|string[] The original choice keys indexed by the * corresponding choice values */ - public function getOriginalKeys(); + public function getOriginalKeys(): array; /** * Returns the choices corresponding to the given values. @@ -123,7 +123,7 @@ public function getOriginalKeys(); * * @return array An array of choices */ - public function getChoicesForValues(array $values); + public function getChoicesForValues(array $values): array; /** * Returns the values corresponding to the given choices. @@ -136,5 +136,5 @@ public function getChoicesForValues(array $values); * * @return string[] An array of choice values */ - public function getValuesForChoices(array $choices); + public function getValuesForChoices(array $choices): array; } diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index 84b68e7dd0..488dd0be55 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -74,7 +74,7 @@ public function __construct(ChoiceListFactoryInterface $decoratedFactory) * * @return ChoiceListFactoryInterface The decorated factory */ - public function getDecoratedFactory() + public function getDecoratedFactory(): ChoiceListFactoryInterface { return $this->decoratedFactory; } @@ -82,7 +82,7 @@ public function getDecoratedFactory() /** * {@inheritdoc} */ - public function createListFromChoices(iterable $choices, mixed $value = null, mixed $filter = null) + public function createListFromChoices(iterable $choices, mixed $value = null, mixed $filter = null): ChoiceListInterface { if ($choices instanceof \Traversable) { $choices = iterator_to_array($choices); @@ -118,7 +118,7 @@ public function createListFromChoices(iterable $choices, mixed $value = null, mi /** * {@inheritdoc} */ - public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value = null, mixed $filter = null) + public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value = null, mixed $filter = null): ChoiceListInterface { $cache = true; @@ -156,7 +156,7 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value /** * {@inheritdoc} */ - public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []) + public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []): ChoiceListView { $cache = true; diff --git a/ChoiceList/Factory/ChoiceListFactoryInterface.php b/ChoiceList/Factory/ChoiceListFactoryInterface.php index 91aad19865..bf58aa0baa 100644 --- a/ChoiceList/Factory/ChoiceListFactoryInterface.php +++ b/ChoiceList/Factory/ChoiceListFactoryInterface.php @@ -35,7 +35,7 @@ interface ChoiceListFactoryInterface * * @return ChoiceListInterface The choice list */ - public function createListFromChoices(iterable $choices, callable $value = null, callable $filter = null); + public function createListFromChoices(iterable $choices, callable $value = null, callable $filter = null): ChoiceListInterface; /** * Creates a choice list that is loaded with the given loader. @@ -48,7 +48,7 @@ public function createListFromChoices(iterable $choices, callable $value = null, * * @return ChoiceListInterface The choice list */ - public function createListFromLoader(ChoiceLoaderInterface $loader, callable $value = null, callable $filter = null); + public function createListFromLoader(ChoiceLoaderInterface $loader, callable $value = null, callable $filter = null): ChoiceListInterface; /** * Creates a view for the given choice list. @@ -84,5 +84,5 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $va * * @return ChoiceListView The choice list view */ - public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []); + public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []): ChoiceListView; } diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index 13c7a96dc0..e22e81f235 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -33,7 +33,7 @@ class DefaultChoiceListFactory implements ChoiceListFactoryInterface /** * {@inheritdoc} */ - public function createListFromChoices(iterable $choices, callable $value = null, callable $filter = null) + public function createListFromChoices(iterable $choices, callable $value = null, callable $filter = null): ChoiceListInterface { if ($filter) { // filter the choice list lazily @@ -50,7 +50,7 @@ public function createListFromChoices(iterable $choices, callable $value = null, /** * {@inheritdoc} */ - public function createListFromLoader(ChoiceLoaderInterface $loader, callable $value = null, callable $filter = null) + public function createListFromLoader(ChoiceLoaderInterface $loader, callable $value = null, callable $filter = null): ChoiceListInterface { if ($filter) { $loader = new FilterChoiceLoaderDecorator($loader, $filter); @@ -62,7 +62,7 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $va /** * {@inheritdoc} */ - public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []) + public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []): ChoiceListView { $preferredViews = []; $preferredViewsOrder = []; diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index d0a32b3fae..84b02f494d 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -52,17 +52,15 @@ public function __construct(ChoiceListFactoryInterface $decoratedFactory, Proper * * @return ChoiceListFactoryInterface The decorated factory */ - public function getDecoratedFactory() + public function getDecoratedFactory(): ChoiceListFactoryInterface { return $this->decoratedFactory; } /** * {@inheritdoc} - * - * @return ChoiceListInterface */ - public function createListFromChoices(iterable $choices, mixed $value = null, mixed $filter = null) + public function createListFromChoices(iterable $choices, mixed $value = null, mixed $filter = null): ChoiceListInterface { if (\is_string($value)) { $value = new PropertyPath($value); @@ -95,10 +93,8 @@ public function createListFromChoices(iterable $choices, mixed $value = null, mi /** * {@inheritdoc} - * - * @return ChoiceListInterface */ - public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value = null, mixed $filter = null) + public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value = null, mixed $filter = null): ChoiceListInterface { if (\is_string($value)) { $value = new PropertyPath($value); @@ -131,10 +127,8 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value /** * {@inheritdoc} - * - * @return ChoiceListView */ - public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []) + public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []): ChoiceListView { $accessor = $this->propertyAccessor; diff --git a/ChoiceList/LazyChoiceList.php b/ChoiceList/LazyChoiceList.php index 2bc0aaae8a..e339bcd249 100644 --- a/ChoiceList/LazyChoiceList.php +++ b/ChoiceList/LazyChoiceList.php @@ -54,7 +54,7 @@ public function __construct(ChoiceLoaderInterface $loader, callable $value = nul /** * {@inheritdoc} */ - public function getChoices() + public function getChoices(): array { return $this->loader->loadChoiceList($this->value)->getChoices(); } @@ -62,7 +62,7 @@ public function getChoices() /** * {@inheritdoc} */ - public function getValues() + public function getValues(): array { return $this->loader->loadChoiceList($this->value)->getValues(); } @@ -70,7 +70,7 @@ public function getValues() /** * {@inheritdoc} */ - public function getStructuredValues() + public function getStructuredValues(): array { return $this->loader->loadChoiceList($this->value)->getStructuredValues(); } @@ -78,7 +78,7 @@ public function getStructuredValues() /** * {@inheritdoc} */ - public function getOriginalKeys() + public function getOriginalKeys(): array { return $this->loader->loadChoiceList($this->value)->getOriginalKeys(); } @@ -86,7 +86,7 @@ public function getOriginalKeys() /** * {@inheritdoc} */ - public function getChoicesForValues(array $values) + public function getChoicesForValues(array $values): array { return $this->loader->loadChoicesForValues($values, $this->value); } @@ -94,7 +94,7 @@ public function getChoicesForValues(array $values) /** * {@inheritdoc} */ - public function getValuesForChoices(array $choices) + public function getValuesForChoices(array $choices): array { return $this->loader->loadValuesForChoices($choices, $this->value); } diff --git a/ChoiceList/Loader/AbstractChoiceLoader.php b/ChoiceList/Loader/AbstractChoiceLoader.php index 4b04629f1d..def29c80de 100644 --- a/ChoiceList/Loader/AbstractChoiceLoader.php +++ b/ChoiceList/Loader/AbstractChoiceLoader.php @@ -37,7 +37,7 @@ public function loadChoiceList(callable $value = null): ChoiceListInterface /** * {@inheritdoc} */ - public function loadChoicesForValues(array $values, callable $value = null) + public function loadChoicesForValues(array $values, callable $value = null): array { if (!$values) { return []; @@ -53,7 +53,7 @@ public function loadChoicesForValues(array $values, callable $value = null) /** * {@inheritdoc} */ - public function loadValuesForChoices(array $choices, callable $value = null) + public function loadValuesForChoices(array $choices, callable $value = null): array { if (!$choices) { return []; diff --git a/ChoiceList/Loader/ChoiceLoaderInterface.php b/ChoiceList/Loader/ChoiceLoaderInterface.php index 507735d1b3..b78a5ff714 100644 --- a/ChoiceList/Loader/ChoiceLoaderInterface.php +++ b/ChoiceList/Loader/ChoiceLoaderInterface.php @@ -36,7 +36,7 @@ interface ChoiceLoaderInterface * * @return ChoiceListInterface The loaded choice list */ - public function loadChoiceList(callable $value = null); + public function loadChoiceList(callable $value = null): ChoiceListInterface; /** * Loads the choices corresponding to the given values. @@ -54,7 +54,7 @@ public function loadChoiceList(callable $value = null); * * @return array An array of choices */ - public function loadChoicesForValues(array $values, callable $value = null); + public function loadChoicesForValues(array $values, callable $value = null): array; /** * Loads the values corresponding to the given choices. @@ -72,5 +72,5 @@ public function loadChoicesForValues(array $values, callable $value = null); * * @return string[] An array of choice values */ - public function loadValuesForChoices(array $choices, callable $value = null); + public function loadValuesForChoices(array $choices, callable $value = null): array; } diff --git a/ChoiceList/Loader/IntlCallbackChoiceLoader.php b/ChoiceList/Loader/IntlCallbackChoiceLoader.php index 546937b900..a96b03ad34 100644 --- a/ChoiceList/Loader/IntlCallbackChoiceLoader.php +++ b/ChoiceList/Loader/IntlCallbackChoiceLoader.php @@ -22,7 +22,7 @@ class IntlCallbackChoiceLoader extends CallbackChoiceLoader /** * {@inheritdoc} */ - public function loadChoicesForValues(array $values, callable $value = null) + public function loadChoicesForValues(array $values, callable $value = null): array { return parent::loadChoicesForValues(array_filter($values), $value); } @@ -30,7 +30,7 @@ public function loadChoicesForValues(array $values, callable $value = null) /** * {@inheritdoc} */ - public function loadValuesForChoices(array $choices, callable $value = null) + public function loadValuesForChoices(array $choices, callable $value = null): array { $choices = array_filter($choices); diff --git a/ChoiceList/View/ChoiceListView.php b/ChoiceList/View/ChoiceListView.php index 586269b516..8f7a245916 100644 --- a/ChoiceList/View/ChoiceListView.php +++ b/ChoiceList/View/ChoiceListView.php @@ -41,10 +41,8 @@ public function __construct(array $choices = [], array $preferredChoices = []) * Returns whether a placeholder is in the choices. * * A placeholder must be the first child element, not be in a group and have an empty value. - * - * @return bool */ - public function hasPlaceholder() + public function hasPlaceholder(): bool { if ($this->preferredChoices) { $firstChoice = reset($this->preferredChoices); diff --git a/ClickableInterface.php b/ClickableInterface.php index 541ef879d6..eb97d928d7 100644 --- a/ClickableInterface.php +++ b/ClickableInterface.php @@ -23,5 +23,5 @@ interface ClickableInterface * * @return bool Whether this element was clicked */ - public function isClicked(); + public function isClicked(): bool; } diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index ceb1efa6e6..245ebb4772 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -101,7 +101,7 @@ protected function configure() /** * {@inheritdoc} */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); diff --git a/DataAccessorInterface.php b/DataAccessorInterface.php index 9a27cfc39a..a6b215a55a 100644 --- a/DataAccessorInterface.php +++ b/DataAccessorInterface.php @@ -25,7 +25,7 @@ interface DataAccessorInterface * * @throws Exception\AccessException If unable to read from the given form data */ - public function getValue(object|array $viewData, FormInterface $form); + public function getValue(object|array $viewData, FormInterface $form): mixed; /** * Sets the value at the end of the property of the object graph. diff --git a/Extension/Core/CoreExtension.php b/Extension/Core/CoreExtension.php index 25d99b5c4e..10ac6e4c06 100644 --- a/Extension/Core/CoreExtension.php +++ b/Extension/Core/CoreExtension.php @@ -39,7 +39,7 @@ public function __construct(PropertyAccessorInterface $propertyAccessor = null, $this->translator = $translator; } - protected function loadTypes() + protected function loadTypes(): array { return [ new Type\FormType($this->propertyAccessor), @@ -80,7 +80,7 @@ protected function loadTypes() ]; } - protected function loadTypeExtensions() + protected function loadTypeExtensions(): array { return [ new TransformationFailureExtension($this->translator), diff --git a/Extension/Core/DataAccessor/CallbackAccessor.php b/Extension/Core/DataAccessor/CallbackAccessor.php index 5dccf0a0fe..617f7d692f 100644 --- a/Extension/Core/DataAccessor/CallbackAccessor.php +++ b/Extension/Core/DataAccessor/CallbackAccessor.php @@ -25,7 +25,7 @@ class CallbackAccessor implements DataAccessorInterface /** * {@inheritdoc} */ - public function getValue(object|array $data, FormInterface $form) + public function getValue(object|array $data, FormInterface $form): mixed { if (null === $getter = $form->getConfig()->getOption('getter')) { throw new AccessException('Unable to read from the given form data as no getter is defined.'); diff --git a/Extension/Core/DataAccessor/ChainAccessor.php b/Extension/Core/DataAccessor/ChainAccessor.php index a58d1724c9..46709b29ad 100644 --- a/Extension/Core/DataAccessor/ChainAccessor.php +++ b/Extension/Core/DataAccessor/ChainAccessor.php @@ -33,7 +33,7 @@ public function __construct(iterable $accessors) /** * {@inheritdoc} */ - public function getValue(object|array $data, FormInterface $form) + public function getValue(object|array $data, FormInterface $form): mixed { foreach ($this->accessors as $accessor) { if ($accessor->isReadable($data, $form)) { diff --git a/Extension/Core/DataAccessor/PropertyPathAccessor.php b/Extension/Core/DataAccessor/PropertyPathAccessor.php index 2890ec9067..aab95f3741 100644 --- a/Extension/Core/DataAccessor/PropertyPathAccessor.php +++ b/Extension/Core/DataAccessor/PropertyPathAccessor.php @@ -38,7 +38,7 @@ public function __construct(PropertyAccessorInterface $propertyAccessor = null) /** * {@inheritdoc} */ - public function getValue(object|array $data, FormInterface $form) + public function getValue(object|array $data, FormInterface $form): mixed { if (null === $propertyPath = $form->getPropertyPath()) { throw new AccessException('Unable to read from the given form data as no property path is defined.'); diff --git a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php index 1aa2ce67bf..4dbb8272a8 100644 --- a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php +++ b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php @@ -26,7 +26,7 @@ public function __construct(array $partMapping) $this->partMapping = $partMapping; } - public function transform(mixed $array) + public function transform(mixed $array): mixed { if (null === $array) { $array = []; @@ -49,7 +49,7 @@ public function transform(mixed $array) return $result; } - public function reverseTransform(mixed $array) + public function reverseTransform(mixed $array): mixed { if (!\is_array($array)) { throw new TransformationFailedException('Expected an array.'); diff --git a/Extension/Core/DataTransformer/BooleanToStringTransformer.php b/Extension/Core/DataTransformer/BooleanToStringTransformer.php index 58a6c995c4..b5926ac399 100644 --- a/Extension/Core/DataTransformer/BooleanToStringTransformer.php +++ b/Extension/Core/DataTransformer/BooleanToStringTransformer.php @@ -48,7 +48,7 @@ public function __construct(string $trueValue, array $falseValues = [null]) * * @throws TransformationFailedException if the given value is not a Boolean */ - public function transform(mixed $value) + public function transform(mixed $value): ?string { if (null === $value) { return null; @@ -70,7 +70,7 @@ public function transform(mixed $value) * * @throws TransformationFailedException if the given value is not a string */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): bool { if (\in_array($value, $this->falseValues, true)) { return false; diff --git a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php index a91688f3f3..f7b0798224 100644 --- a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php +++ b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php @@ -27,12 +27,12 @@ public function __construct(ChoiceListInterface $choiceList) $this->choiceList = $choiceList; } - public function transform(mixed $choice) + public function transform(mixed $choice): mixed { return (string) current($this->choiceList->getValuesForChoices([$choice])); } - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): mixed { if (null !== $value && !\is_string($value)) { throw new TransformationFailedException('Expected a string or null.'); diff --git a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php index 5347137176..e2f1f2f22d 100644 --- a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php +++ b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php @@ -28,11 +28,9 @@ public function __construct(ChoiceListInterface $choiceList) } /** - * @return array - * * @throws TransformationFailedException if the given value is not an array */ - public function transform(mixed $array) + public function transform(mixed $array): array { if (null === $array) { return []; @@ -46,13 +44,11 @@ public function transform(mixed $array) } /** - * @return array - * * @throws TransformationFailedException if the given value is not an array * or if no matching choice could be * found for some given value */ - public function reverseTransform(mixed $array) + public function reverseTransform(mixed $array): array { if (null === $array) { return []; diff --git a/Extension/Core/DataTransformer/DataTransformerChain.php b/Extension/Core/DataTransformer/DataTransformerChain.php index 55de5bdb56..4f899b6c22 100644 --- a/Extension/Core/DataTransformer/DataTransformerChain.php +++ b/Extension/Core/DataTransformer/DataTransformerChain.php @@ -47,7 +47,7 @@ public function __construct(array $transformers) * * @throws TransformationFailedException */ - public function transform(mixed $value) + public function transform(mixed $value): mixed { foreach ($this->transformers as $transformer) { $value = $transformer->transform($value); @@ -71,7 +71,7 @@ public function transform(mixed $value) * * @throws TransformationFailedException */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): mixed { for ($i = \count($this->transformers) - 1; $i >= 0; --$i) { $value = $this->transformers[$i]->reverseTransform($value); @@ -83,7 +83,7 @@ public function reverseTransform(mixed $value) /** * @return DataTransformerInterface[] */ - public function getTransformers() + public function getTransformers(): array { return $this->transformers; } diff --git a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php index 26848fae9a..8a17d16f61 100644 --- a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php @@ -61,7 +61,7 @@ public function __construct(array $fields = null, bool $pad = false) * * @throws UnexpectedTypeException if the given value is not a \DateInterval instance */ - public function transform(mixed $dateInterval) + public function transform(mixed $dateInterval): array { if (null === $dateInterval) { return array_intersect_key( @@ -108,7 +108,7 @@ public function transform(mixed $dateInterval) * @throws UnexpectedTypeException if the given value is not an array * @throws TransformationFailedException if the value could not be transformed */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): ?\DateInterval { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php index af0d44928f..a8c22ebcbd 100644 --- a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php @@ -45,7 +45,7 @@ public function __construct(string $format = 'P%yY%mM%dDT%hH%iM%sS') * * @throws UnexpectedTypeException if the given value is not a \DateInterval instance */ - public function transform(mixed $value) + public function transform(mixed $value): string { if (null === $value) { return ''; @@ -62,12 +62,10 @@ public function transform(mixed $value) * * @param string $value An ISO 8601 or date string like date interval presentation * - * @return \DateInterval|null - * * @throws UnexpectedTypeException if the given value is not a string * @throws TransformationFailedException if the date interval could not be parsed */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): ?\DateInterval { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php index e841b654bc..f1dc0a1f99 100644 --- a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php @@ -49,7 +49,7 @@ public function __construct(string $inputTimezone = null, string $outputTimezone * * @throws TransformationFailedException If the given value is not a \DateTimeInterface */ - public function transform(mixed $dateTime) + public function transform(mixed $dateTime): array { if (null === $dateTime) { return array_intersect_key([ @@ -105,7 +105,7 @@ public function transform(mixed $dateTime) * @throws TransformationFailedException If the given value is not an array, * if the value could not be transformed */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): ?\DateTime { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php index 1c2d1313cb..3551947b36 100644 --- a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php @@ -36,7 +36,7 @@ class DateTimeToHtml5LocalDateTimeTransformer extends BaseDateTimeTransformer * @throws TransformationFailedException If the given value is not an * instance of \DateTime or \DateTimeInterface */ - public function transform(mixed $dateTime) + public function transform(mixed $dateTime): string { if (null === $dateTime) { return ''; @@ -71,7 +71,7 @@ public function transform(mixed $dateTime) * @throws TransformationFailedException If the given value is not a string, * if the value could not be transformed */ - public function reverseTransform(mixed $dateTimeLocal) + public function reverseTransform(mixed $dateTimeLocal): ?\DateTime { if (!\is_string($dateTimeLocal)) { throw new TransformationFailedException('Expected a string.'); diff --git a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php index 93219c9252..ff5ced0da7 100644 --- a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php @@ -75,7 +75,7 @@ public function __construct(string $inputTimezone = null, string $outputTimezone * @throws TransformationFailedException if the given value is not a \DateTimeInterface * or if the date could not be transformed */ - public function transform(mixed $dateTime) + public function transform(mixed $dateTime): string { if (null === $dateTime) { return ''; @@ -104,7 +104,7 @@ public function transform(mixed $dateTime) * @throws TransformationFailedException if the given value is not a string, * if the date could not be parsed */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): ?\DateTime { if (!\is_string($value)) { throw new TransformationFailedException('Expected a string.'); @@ -163,11 +163,9 @@ public function reverseTransform(mixed $value) * * @param bool $ignoreTimezone Use UTC regardless of the configured timezone * - * @return \IntlDateFormatter - * * @throws TransformationFailedException in case the date formatter can not be constructed */ - protected function getIntlDateFormatter(bool $ignoreTimezone = false) + protected function getIntlDateFormatter(bool $ignoreTimezone = false): \IntlDateFormatter { $dateFormat = $this->dateFormat; $timeFormat = $this->timeFormat; @@ -190,10 +188,8 @@ protected function getIntlDateFormatter(bool $ignoreTimezone = false) /** * Checks if the pattern contains only a date. - * - * @return bool */ - protected function isPatternDateOnly() + protected function isPatternDateOnly(): bool { if (null === $this->pattern) { return false; diff --git a/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php b/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php index a35d06aac5..773d8ed773 100644 --- a/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php +++ b/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php @@ -27,7 +27,7 @@ class DateTimeToRfc3339Transformer extends BaseDateTimeTransformer * * @throws TransformationFailedException If the given value is not a \DateTimeInterface */ - public function transform(mixed $dateTime) + public function transform(mixed $dateTime): string { if (null === $dateTime) { return ''; @@ -58,7 +58,7 @@ public function transform(mixed $dateTime) * @throws TransformationFailedException If the given value is not a string, * if the value could not be transformed */ - public function reverseTransform(mixed $rfc3339) + public function reverseTransform(mixed $rfc3339): ?\DateTime { if (!\is_string($rfc3339)) { throw new TransformationFailedException('Expected a string.'); diff --git a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php index e551e159c6..ed3cd0dc2b 100644 --- a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php @@ -73,7 +73,7 @@ public function __construct(string $inputTimezone = null, string $outputTimezone * * @throws TransformationFailedException If the given value is not a \DateTimeInterface */ - public function transform(mixed $dateTime) + public function transform(mixed $dateTime): string { if (null === $dateTime) { return ''; @@ -97,12 +97,10 @@ public function transform(mixed $dateTime) * * @param string $value A value as produced by PHP's date() function * - * @return \DateTime|null - * * @throws TransformationFailedException If the given value is not a string, * or could not be transformed */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): ?\DateTime { if (empty($value)) { return null; diff --git a/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php b/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php index 11ba01abb7..cdf634517b 100644 --- a/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php @@ -30,7 +30,7 @@ class DateTimeToTimestampTransformer extends BaseDateTimeTransformer * * @throws TransformationFailedException If the given value is not a \DateTimeInterface */ - public function transform(mixed $dateTime) + public function transform(mixed $dateTime): ?int { if (null === $dateTime) { return null; @@ -53,7 +53,7 @@ public function transform(mixed $dateTime) * @throws TransformationFailedException If the given value is not a timestamp * or if the given timestamp is invalid */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): ?\DateTime { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php index 62c6af0080..645237363c 100644 --- a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php @@ -31,7 +31,7 @@ public function __construct(bool $multiple = false) /** * {@inheritdoc} */ - public function transform(mixed $dateTimeZone) + public function transform(mixed $dateTimeZone): mixed { if (null === $dateTimeZone) { return null; @@ -55,7 +55,7 @@ public function transform(mixed $dateTimeZone) /** * {@inheritdoc} */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): mixed { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php index 0ac2904f90..ccf4701b90 100644 --- a/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php @@ -36,7 +36,7 @@ public function __construct(?bool $grouping = false, ?int $roundingMode = \Numbe /** * {@inheritdoc} */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): int|float|null { $decimalSeparator = $this->getNumberFormatter()->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL); diff --git a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php index 59dbec56d9..f158ecba2d 100644 --- a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php @@ -31,7 +31,7 @@ public function __construct(bool $multiple = false) /** * {@inheritdoc} */ - public function transform(mixed $intlTimeZone) + public function transform(mixed $intlTimeZone): mixed { if (null === $intlTimeZone) { return null; @@ -55,10 +55,10 @@ public function transform(mixed $intlTimeZone) /** * {@inheritdoc} */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): mixed { if (null === $value) { - return; + return null; } if ($this->multiple) { diff --git a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php index 1d5ca8ab14..40501e6f1c 100644 --- a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php @@ -40,7 +40,7 @@ public function __construct(?int $scale = 2, ?bool $grouping = true, ?int $round * @throws TransformationFailedException if the given value is not numeric or * if the value can not be transformed */ - public function transform(mixed $value) + public function transform(mixed $value): string { if (null !== $value && 1 !== $this->divisor) { if (!is_numeric($value)) { @@ -62,7 +62,7 @@ public function transform(mixed $value) * @throws TransformationFailedException if the given value is not a string * or if the value can not be transformed */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): int|float|null { $value = parent::reverseTransform($value); if (null !== $value && 1 !== $this->divisor) { diff --git a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index 492ba9c4ab..6a24c43005 100644 --- a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -48,7 +48,7 @@ public function __construct(int $scale = null, ?bool $grouping = false, ?int $ro * @throws TransformationFailedException if the given value is not numeric * or if the value can not be transformed */ - public function transform(mixed $value) + public function transform(mixed $value): string { if (null === $value) { return ''; @@ -81,7 +81,7 @@ public function transform(mixed $value) * @throws TransformationFailedException if the given value is not a string * or if the value can not be transformed */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): int|float|null { if (null !== $value && !\is_string($value)) { throw new TransformationFailedException('Expected a string.'); @@ -154,10 +154,8 @@ public function reverseTransform(mixed $value) /** * Returns a preconfigured \NumberFormatter instance. - * - * @return \NumberFormatter */ - protected function getNumberFormatter() + protected function getNumberFormatter(): \NumberFormatter { $formatter = new \NumberFormatter($this->locale ?? \Locale::getDefault(), \NumberFormatter::DECIMAL); diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index 2f64e04218..ce157dafb5 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -70,7 +70,7 @@ public function __construct(int $scale = null, string $type = null, int $roundin * @throws TransformationFailedException if the given value is not numeric or * if the value could not be transformed */ - public function transform(mixed $value) + public function transform(mixed $value): string { if (null === $value) { return ''; @@ -100,12 +100,10 @@ public function transform(mixed $value) * * @param string $value Percentage value * - * @return int|float|null - * * @throws TransformationFailedException if the given value is not a string or * if the value could not be transformed */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): int|float|null { if (!\is_string($value)) { throw new TransformationFailedException('Expected a string.'); @@ -171,10 +169,8 @@ public function reverseTransform(mixed $value) /** * Returns a preconfigured \NumberFormatter instance. - * - * @return \NumberFormatter */ - protected function getNumberFormatter() + protected function getNumberFormatter(): \NumberFormatter { // Values used in HTML5 number inputs should be formatted as in "1234.5", ie. 'en' format without grouping, // according to https://www.w3.org/TR/html51/sec-forms.html#date-time-and-number-formats diff --git a/Extension/Core/DataTransformer/StringToFloatTransformer.php b/Extension/Core/DataTransformer/StringToFloatTransformer.php index f1b89ab22a..4e04ab6d9e 100644 --- a/Extension/Core/DataTransformer/StringToFloatTransformer.php +++ b/Extension/Core/DataTransformer/StringToFloatTransformer.php @@ -23,12 +23,7 @@ public function __construct(int $scale = null) $this->scale = $scale; } - /** - * @param mixed $value - * - * @return float|null - */ - public function transform(mixed $value) + public function transform(mixed $value): ?float { if (null === $value) { return null; @@ -41,12 +36,7 @@ public function transform(mixed $value) return (float) $value; } - /** - * @param mixed $value - * - * @return string|null - */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): ?string { if (null === $value) { return null; diff --git a/Extension/Core/DataTransformer/UlidToStringTransformer.php b/Extension/Core/DataTransformer/UlidToStringTransformer.php index 66c6354b40..7924a057ca 100644 --- a/Extension/Core/DataTransformer/UlidToStringTransformer.php +++ b/Extension/Core/DataTransformer/UlidToStringTransformer.php @@ -31,7 +31,7 @@ class UlidToStringTransformer implements DataTransformerInterface * * @throws TransformationFailedException If the given value is not a Ulid object */ - public function transform(mixed $value) + public function transform(mixed $value): ?string { if (null === $value) { return null; @@ -49,12 +49,10 @@ public function transform(mixed $value) * * @param string $value A ULID string * - * @return Ulid|null - * * @throws TransformationFailedException If the given value is not a string, * or could not be transformed */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): ?Ulid { if (null === $value || '' === $value) { return null; diff --git a/Extension/Core/DataTransformer/UuidToStringTransformer.php b/Extension/Core/DataTransformer/UuidToStringTransformer.php index d8f1a0e50e..c4ca5867c3 100644 --- a/Extension/Core/DataTransformer/UuidToStringTransformer.php +++ b/Extension/Core/DataTransformer/UuidToStringTransformer.php @@ -31,7 +31,7 @@ class UuidToStringTransformer implements DataTransformerInterface * * @throws TransformationFailedException If the given value is not a Uuid object */ - public function transform(mixed $value) + public function transform(mixed $value): ?string { if (null === $value) { return null; @@ -49,12 +49,10 @@ public function transform(mixed $value) * * @param string $value A UUID string * - * @return Uuid|null - * * @throws TransformationFailedException If the given value is not a string, * or could not be transformed */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): ?Uuid { if (null === $value || '' === $value) { return null; diff --git a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php index a7d1287861..1397e2cc09 100644 --- a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php +++ b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php @@ -31,7 +31,7 @@ public function __construct(array $keys) * * @return array The array */ - public function transform(mixed $value) + public function transform(mixed $value): array { $result = []; @@ -48,7 +48,7 @@ public function transform(mixed $value) * @throws TransformationFailedException if the given value is not an array or * if the given array can not be transformed */ - public function reverseTransform(mixed $array) + public function reverseTransform(mixed $array): mixed { if (!\is_array($array)) { throw new TransformationFailedException('Expected an array.'); diff --git a/Extension/Core/DataTransformer/WeekToArrayTransformer.php b/Extension/Core/DataTransformer/WeekToArrayTransformer.php index 3c4d480721..e893588e2e 100644 --- a/Extension/Core/DataTransformer/WeekToArrayTransformer.php +++ b/Extension/Core/DataTransformer/WeekToArrayTransformer.php @@ -31,7 +31,7 @@ class WeekToArrayTransformer implements DataTransformerInterface * @throws TransformationFailedException If the given value is not a string, * or if the given value does not follow the right format */ - public function transform(mixed $value) + public function transform(mixed $value): array { if (null === $value) { return ['year' => null, 'week' => null]; @@ -61,7 +61,7 @@ public function transform(mixed $value) * @throws TransformationFailedException If the given value can not be merged in a valid week date string, * or if the obtained week date does not exists */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): ?string { if (null === $value || [] === $value) { return null; diff --git a/Extension/Core/EventListener/FixUrlProtocolListener.php b/Extension/Core/EventListener/FixUrlProtocolListener.php index c64d747d4e..825276fe16 100644 --- a/Extension/Core/EventListener/FixUrlProtocolListener.php +++ b/Extension/Core/EventListener/FixUrlProtocolListener.php @@ -41,7 +41,7 @@ public function onSubmit(FormEvent $event) } } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [FormEvents::SUBMIT => 'onSubmit']; } diff --git a/Extension/Core/EventListener/MergeCollectionListener.php b/Extension/Core/EventListener/MergeCollectionListener.php index 43c9de57de..37046e9b69 100644 --- a/Extension/Core/EventListener/MergeCollectionListener.php +++ b/Extension/Core/EventListener/MergeCollectionListener.php @@ -34,7 +34,7 @@ public function __construct(bool $allowAdd = false, bool $allowDelete = false) $this->allowDelete = $allowDelete; } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ FormEvents::SUBMIT => 'onSubmit', diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index 45c3032a67..8cbfa8b36b 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -40,7 +40,7 @@ public function __construct(string $type, array $options = [], bool $allowAdd = $this->deleteEmpty = $deleteEmpty instanceof \Closure || !\is_callable($deleteEmpty) ? $deleteEmpty : \Closure::fromCallable($deleteEmpty); } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ FormEvents::PRE_SET_DATA => 'preSetData', diff --git a/Extension/Core/EventListener/TransformationFailureListener.php b/Extension/Core/EventListener/TransformationFailureListener.php index 6fb7a3e4aa..ae705fc57a 100644 --- a/Extension/Core/EventListener/TransformationFailureListener.php +++ b/Extension/Core/EventListener/TransformationFailureListener.php @@ -29,7 +29,7 @@ public function __construct(TranslatorInterface $translator = null) $this->translator = $translator; } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ FormEvents::POST_SUBMIT => ['convertTransformationFailureToFormError', -1024], diff --git a/Extension/Core/EventListener/TrimListener.php b/Extension/Core/EventListener/TrimListener.php index be8c38a854..be763c78d2 100644 --- a/Extension/Core/EventListener/TrimListener.php +++ b/Extension/Core/EventListener/TrimListener.php @@ -34,7 +34,7 @@ public function preSubmit(FormEvent $event) $event->setData(StringUtil::trim($data)); } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [FormEvents::PRE_SUBMIT => 'preSubmit']; } diff --git a/Extension/Core/Type/BirthdayType.php b/Extension/Core/Type/BirthdayType.php index c5d096db11..2a78e1d77c 100644 --- a/Extension/Core/Type/BirthdayType.php +++ b/Extension/Core/Type/BirthdayType.php @@ -32,7 +32,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return DateType::class; } @@ -40,7 +40,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'birthday'; } diff --git a/Extension/Core/Type/ButtonType.php b/Extension/Core/Type/ButtonType.php index ba2f8dfe0e..2fb77f9eda 100644 --- a/Extension/Core/Type/ButtonType.php +++ b/Extension/Core/Type/ButtonType.php @@ -24,7 +24,7 @@ class ButtonType extends BaseType implements ButtonTypeInterface /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return null; } @@ -32,7 +32,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'button'; } diff --git a/Extension/Core/Type/CheckboxType.php b/Extension/Core/Type/CheckboxType.php index eb82e574f2..96c557d0a3 100644 --- a/Extension/Core/Type/CheckboxType.php +++ b/Extension/Core/Type/CheckboxType.php @@ -72,7 +72,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'checkbox'; } diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 0ef8d48580..3980d579fa 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -394,7 +394,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'choice'; } diff --git a/Extension/Core/Type/CollectionType.php b/Extension/Core/Type/CollectionType.php index 946c6c3d18..480d31dc94 100644 --- a/Extension/Core/Type/CollectionType.php +++ b/Extension/Core/Type/CollectionType.php @@ -131,7 +131,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'collection'; } diff --git a/Extension/Core/Type/ColorType.php b/Extension/Core/Type/ColorType.php index e2e5f06e92..cca92e6e26 100644 --- a/Extension/Core/Type/ColorType.php +++ b/Extension/Core/Type/ColorType.php @@ -78,7 +78,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return TextType::class; } @@ -86,7 +86,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'color'; } diff --git a/Extension/Core/Type/CountryType.php b/Extension/Core/Type/CountryType.php index d978973cb0..8d5c6487d2 100644 --- a/Extension/Core/Type/CountryType.php +++ b/Extension/Core/Type/CountryType.php @@ -53,7 +53,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return ChoiceType::class; } @@ -61,7 +61,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'country'; } diff --git a/Extension/Core/Type/CurrencyType.php b/Extension/Core/Type/CurrencyType.php index 12c4e65777..fe7842fd26 100644 --- a/Extension/Core/Type/CurrencyType.php +++ b/Extension/Core/Type/CurrencyType.php @@ -50,7 +50,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return ChoiceType::class; } @@ -58,7 +58,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'currency'; } diff --git a/Extension/Core/Type/DateIntervalType.php b/Extension/Core/Type/DateIntervalType.php index aa7e14536f..a7080e03c9 100644 --- a/Extension/Core/Type/DateIntervalType.php +++ b/Extension/Core/Type/DateIntervalType.php @@ -280,7 +280,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'dateinterval'; } diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index bcfd25b179..dc1549a521 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -351,7 +351,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'datetime'; } diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index bfedb74332..1360ed450f 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -336,7 +336,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'date'; } diff --git a/Extension/Core/Type/EmailType.php b/Extension/Core/Type/EmailType.php index 925054e4f8..4284db1869 100644 --- a/Extension/Core/Type/EmailType.php +++ b/Extension/Core/Type/EmailType.php @@ -29,7 +29,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return TextType::class; } @@ -37,7 +37,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'email'; } diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index 501ad8d098..89f70bcde8 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -137,7 +137,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'file'; } diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index 0ed88c1b0f..b2ad206236 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -235,7 +235,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return null; } @@ -243,7 +243,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'form'; } diff --git a/Extension/Core/Type/HiddenType.php b/Extension/Core/Type/HiddenType.php index 4292bb3b96..b54ea01ca1 100644 --- a/Extension/Core/Type/HiddenType.php +++ b/Extension/Core/Type/HiddenType.php @@ -34,7 +34,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'hidden'; } diff --git a/Extension/Core/Type/IntegerType.php b/Extension/Core/Type/IntegerType.php index fbb6128fb6..3d69448e34 100644 --- a/Extension/Core/Type/IntegerType.php +++ b/Extension/Core/Type/IntegerType.php @@ -65,7 +65,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'integer'; } diff --git a/Extension/Core/Type/LanguageType.php b/Extension/Core/Type/LanguageType.php index 871a293705..ef6486f06e 100644 --- a/Extension/Core/Type/LanguageType.php +++ b/Extension/Core/Type/LanguageType.php @@ -77,7 +77,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return ChoiceType::class; } @@ -85,7 +85,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'language'; } diff --git a/Extension/Core/Type/LocaleType.php b/Extension/Core/Type/LocaleType.php index 3e3a55bdb4..b0cb9a8e00 100644 --- a/Extension/Core/Type/LocaleType.php +++ b/Extension/Core/Type/LocaleType.php @@ -50,7 +50,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return ChoiceType::class; } @@ -58,7 +58,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'locale'; } diff --git a/Extension/Core/Type/MoneyType.php b/Extension/Core/Type/MoneyType.php index 19417cf16c..cf6246acc8 100644 --- a/Extension/Core/Type/MoneyType.php +++ b/Extension/Core/Type/MoneyType.php @@ -96,7 +96,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'money'; } diff --git a/Extension/Core/Type/NumberType.php b/Extension/Core/Type/NumberType.php index 6e7c76f259..1437369fba 100644 --- a/Extension/Core/Type/NumberType.php +++ b/Extension/Core/Type/NumberType.php @@ -91,7 +91,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'number'; } diff --git a/Extension/Core/Type/PasswordType.php b/Extension/Core/Type/PasswordType.php index c31d4b4341..cbb0d97787 100644 --- a/Extension/Core/Type/PasswordType.php +++ b/Extension/Core/Type/PasswordType.php @@ -43,7 +43,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return TextType::class; } @@ -51,7 +51,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'password'; } diff --git a/Extension/Core/Type/PercentType.php b/Extension/Core/Type/PercentType.php index 41f3476365..9b98f9b089 100644 --- a/Extension/Core/Type/PercentType.php +++ b/Extension/Core/Type/PercentType.php @@ -81,7 +81,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'percent'; } diff --git a/Extension/Core/Type/RadioType.php b/Extension/Core/Type/RadioType.php index 81a5e58aaf..c668420c2c 100644 --- a/Extension/Core/Type/RadioType.php +++ b/Extension/Core/Type/RadioType.php @@ -29,7 +29,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return CheckboxType::class; } @@ -37,7 +37,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'radio'; } diff --git a/Extension/Core/Type/RangeType.php b/Extension/Core/Type/RangeType.php index c52a6e8221..e150323b10 100644 --- a/Extension/Core/Type/RangeType.php +++ b/Extension/Core/Type/RangeType.php @@ -29,7 +29,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return TextType::class; } @@ -37,7 +37,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'range'; } diff --git a/Extension/Core/Type/RepeatedType.php b/Extension/Core/Type/RepeatedType.php index f2a6f577b4..a511cf070e 100644 --- a/Extension/Core/Type/RepeatedType.php +++ b/Extension/Core/Type/RepeatedType.php @@ -68,7 +68,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'repeated'; } diff --git a/Extension/Core/Type/ResetType.php b/Extension/Core/Type/ResetType.php index ce8013d1b0..40801c0d09 100644 --- a/Extension/Core/Type/ResetType.php +++ b/Extension/Core/Type/ResetType.php @@ -24,7 +24,7 @@ class ResetType extends AbstractType implements ButtonTypeInterface /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return ButtonType::class; } @@ -32,7 +32,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'reset'; } diff --git a/Extension/Core/Type/SearchType.php b/Extension/Core/Type/SearchType.php index 0a8c1d723b..e29ca152b3 100644 --- a/Extension/Core/Type/SearchType.php +++ b/Extension/Core/Type/SearchType.php @@ -29,7 +29,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return TextType::class; } @@ -37,7 +37,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'search'; } diff --git a/Extension/Core/Type/SubmitType.php b/Extension/Core/Type/SubmitType.php index 945156efc6..7f423668b1 100644 --- a/Extension/Core/Type/SubmitType.php +++ b/Extension/Core/Type/SubmitType.php @@ -45,7 +45,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return ButtonType::class; } @@ -53,7 +53,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'submit'; } diff --git a/Extension/Core/Type/TelType.php b/Extension/Core/Type/TelType.php index 4076f81e00..36ec764001 100644 --- a/Extension/Core/Type/TelType.php +++ b/Extension/Core/Type/TelType.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class TelType extends AbstractType @@ -30,7 +29,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return TextType::class; } @@ -38,7 +37,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'tel'; } diff --git a/Extension/Core/Type/TextType.php b/Extension/Core/Type/TextType.php index bfc1db341a..4bbd89efe7 100644 --- a/Extension/Core/Type/TextType.php +++ b/Extension/Core/Type/TextType.php @@ -43,7 +43,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'text'; } @@ -51,7 +51,7 @@ public function getBlockPrefix() /** * {@inheritdoc} */ - public function transform(mixed $data) + public function transform(mixed $data): mixed { // Model data should not be transformed return $data; @@ -60,7 +60,7 @@ public function transform(mixed $data) /** * {@inheritdoc} */ - public function reverseTransform(mixed $data) + public function reverseTransform(mixed $data): mixed { return $data ?? ''; } diff --git a/Extension/Core/Type/TextareaType.php b/Extension/Core/Type/TextareaType.php index 173b7ef53c..5aca850386 100644 --- a/Extension/Core/Type/TextareaType.php +++ b/Extension/Core/Type/TextareaType.php @@ -29,7 +29,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return TextType::class; } @@ -37,7 +37,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'textarea'; } diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 6dba2b50d8..d20968657b 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -375,7 +375,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'time'; } diff --git a/Extension/Core/Type/TimezoneType.php b/Extension/Core/Type/TimezoneType.php index 0c472b6055..d9ef804fd7 100644 --- a/Extension/Core/Type/TimezoneType.php +++ b/Extension/Core/Type/TimezoneType.php @@ -94,7 +94,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return ChoiceType::class; } @@ -102,7 +102,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'timezone'; } diff --git a/Extension/Core/Type/UlidType.php b/Extension/Core/Type/UlidType.php index 08e65801a8..abda5fd0b7 100644 --- a/Extension/Core/Type/UlidType.php +++ b/Extension/Core/Type/UlidType.php @@ -14,7 +14,6 @@ use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\DataTransformer\UlidToStringTransformer; use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; /** diff --git a/Extension/Core/Type/UrlType.php b/Extension/Core/Type/UrlType.php index 2dde5d1625..36aee7699f 100644 --- a/Extension/Core/Type/UrlType.php +++ b/Extension/Core/Type/UrlType.php @@ -16,7 +16,6 @@ use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class UrlType extends AbstractType @@ -58,7 +57,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?string { return TextType::class; } @@ -66,7 +65,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'url'; } diff --git a/Extension/Core/Type/UuidType.php b/Extension/Core/Type/UuidType.php index c292b4bd1b..f551d639a2 100644 --- a/Extension/Core/Type/UuidType.php +++ b/Extension/Core/Type/UuidType.php @@ -14,7 +14,6 @@ use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\DataTransformer\UuidToStringTransformer; use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; /** diff --git a/Extension/Core/Type/WeekType.php b/Extension/Core/Type/WeekType.php index 40b08c8af8..71f3146b7d 100644 --- a/Extension/Core/Type/WeekType.php +++ b/Extension/Core/Type/WeekType.php @@ -186,7 +186,7 @@ public function configureOptions(OptionsResolver $resolver) /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return 'week'; } diff --git a/Extension/Csrf/CsrfExtension.php b/Extension/Csrf/CsrfExtension.php index 6f0686860b..97228f56c9 100644 --- a/Extension/Csrf/CsrfExtension.php +++ b/Extension/Csrf/CsrfExtension.php @@ -36,7 +36,7 @@ public function __construct(CsrfTokenManagerInterface $tokenManager, TranslatorI /** * {@inheritdoc} */ - protected function loadTypeExtensions() + protected function loadTypeExtensions(): array { return [ new Type\FormTypeCsrfExtension($this->tokenManager, true, '_token', $this->translator, $this->translationDomain), diff --git a/Extension/Csrf/EventListener/CsrfValidationListener.php b/Extension/Csrf/EventListener/CsrfValidationListener.php index cf01cf3951..732b036de1 100644 --- a/Extension/Csrf/EventListener/CsrfValidationListener.php +++ b/Extension/Csrf/EventListener/CsrfValidationListener.php @@ -33,7 +33,7 @@ class CsrfValidationListener implements EventSubscriberInterface private ?string $translationDomain; private ServerParams $serverParams; - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ FormEvents::PRE_SUBMIT => 'preSubmit', diff --git a/Extension/DataCollector/DataCollectorExtension.php b/Extension/DataCollector/DataCollectorExtension.php index 694fbb6e8e..cafd0ffc66 100644 --- a/Extension/DataCollector/DataCollectorExtension.php +++ b/Extension/DataCollector/DataCollectorExtension.php @@ -31,7 +31,7 @@ public function __construct(FormDataCollectorInterface $dataCollector) /** * {@inheritdoc} */ - protected function loadTypeExtensions() + protected function loadTypeExtensions(): array { return [ new Type\DataCollectorTypeExtension($this->dataCollector), diff --git a/Extension/DataCollector/EventListener/DataCollectorListener.php b/Extension/DataCollector/EventListener/DataCollectorListener.php index ae46652a73..dbc36123c7 100644 --- a/Extension/DataCollector/EventListener/DataCollectorListener.php +++ b/Extension/DataCollector/EventListener/DataCollectorListener.php @@ -34,7 +34,7 @@ public function __construct(FormDataCollectorInterface $dataCollector) /** * {@inheritdoc} */ - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ // High priority in order to be called as soon as possible diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index 82d2468cdc..023a63fe17 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -20,6 +20,7 @@ use Symfony\Component\VarDumper\Caster\Caster; use Symfony\Component\VarDumper\Caster\ClassStub; use Symfony\Component\VarDumper\Caster\StubCaster; +use Symfony\Component\VarDumper\Cloner\Data; use Symfony\Component\VarDumper\Cloner\Stub; /** @@ -221,7 +222,7 @@ public function getName(): string /** * {@inheritdoc} */ - public function getData() + public function getData(): array|Data { return $this->data; } diff --git a/Extension/DataCollector/FormDataCollectorInterface.php b/Extension/DataCollector/FormDataCollectorInterface.php index 64b8f83c4b..f51773e405 100644 --- a/Extension/DataCollector/FormDataCollectorInterface.php +++ b/Extension/DataCollector/FormDataCollectorInterface.php @@ -81,5 +81,5 @@ public function buildFinalFormTree(FormInterface $form, FormView $view); * * @return array|Data */ - public function getData(); + public function getData(): array|Data; } diff --git a/Extension/DataCollector/FormDataExtractor.php b/Extension/DataCollector/FormDataExtractor.php index 9cecc720e3..e9a54df8fe 100644 --- a/Extension/DataCollector/FormDataExtractor.php +++ b/Extension/DataCollector/FormDataExtractor.php @@ -25,7 +25,7 @@ class FormDataExtractor implements FormDataExtractorInterface /** * {@inheritdoc} */ - public function extractConfiguration(FormInterface $form) + public function extractConfiguration(FormInterface $form): array { $data = [ 'id' => $this->buildId($form), @@ -53,7 +53,7 @@ public function extractConfiguration(FormInterface $form) /** * {@inheritdoc} */ - public function extractDefaultData(FormInterface $form) + public function extractDefaultData(FormInterface $form): array { $data = [ 'default_data' => [ @@ -76,7 +76,7 @@ public function extractDefaultData(FormInterface $form) /** * {@inheritdoc} */ - public function extractSubmittedData(FormInterface $form) + public function extractSubmittedData(FormInterface $form): array { $data = [ 'submitted_data' => [ @@ -135,7 +135,7 @@ public function extractSubmittedData(FormInterface $form) /** * {@inheritdoc} */ - public function extractViewVariables(FormView $view) + public function extractViewVariables(FormView $view): array { $data = [ 'id' => $view->vars['id'] ?? null, diff --git a/Extension/DataCollector/FormDataExtractorInterface.php b/Extension/DataCollector/FormDataExtractorInterface.php index 5fd345fec0..821296be1e 100644 --- a/Extension/DataCollector/FormDataExtractorInterface.php +++ b/Extension/DataCollector/FormDataExtractorInterface.php @@ -26,26 +26,26 @@ interface FormDataExtractorInterface * * @return array Information about the form's configuration */ - public function extractConfiguration(FormInterface $form); + public function extractConfiguration(FormInterface $form): array; /** * Extracts the default data of a form. * * @return array Information about the form's default data */ - public function extractDefaultData(FormInterface $form); + public function extractDefaultData(FormInterface $form): array; /** * Extracts the submitted data of a form. * * @return array Information about the form's submitted data */ - public function extractSubmittedData(FormInterface $form); + public function extractSubmittedData(FormInterface $form): array; /** * Extracts the view variables of a form. * * @return array Information about the view's variables */ - public function extractViewVariables(FormView $view); + public function extractViewVariables(FormView $view): array; } diff --git a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php index 847a19fe3c..7563e778e8 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php @@ -15,8 +15,10 @@ use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\FormInterface; +use Symfony\Component\Form\FormTypeInterface; use Symfony\Component\Form\FormView; use Symfony\Component\Form\ResolvedFormTypeInterface; +use Symfony\Component\OptionsResolver\OptionsResolver; /** * Proxy that invokes a data collector when creating a form and its view. @@ -37,7 +39,7 @@ public function __construct(ResolvedFormTypeInterface $proxiedType, FormDataColl /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return $this->proxiedType->getBlockPrefix(); } @@ -45,7 +47,7 @@ public function getBlockPrefix() /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?ResolvedFormTypeInterface { return $this->proxiedType->getParent(); } @@ -53,7 +55,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getInnerType() + public function getInnerType(): FormTypeInterface { return $this->proxiedType->getInnerType(); } @@ -61,7 +63,7 @@ public function getInnerType() /** * {@inheritdoc} */ - public function getTypeExtensions() + public function getTypeExtensions(): array { return $this->proxiedType->getTypeExtensions(); } @@ -69,7 +71,7 @@ public function getTypeExtensions() /** * {@inheritdoc} */ - public function createBuilder(FormFactoryInterface $factory, string $name, array $options = []) + public function createBuilder(FormFactoryInterface $factory, string $name, array $options = []): FormBuilderInterface { $builder = $this->proxiedType->createBuilder($factory, $name, $options); @@ -82,7 +84,7 @@ public function createBuilder(FormFactoryInterface $factory, string $name, array /** * {@inheritdoc} */ - public function createView(FormInterface $form, FormView $parent = null) + public function createView(FormInterface $form, FormView $parent = null): FormView { return $this->proxiedType->createView($form, $parent); } @@ -133,7 +135,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) /** * {@inheritdoc} */ - public function getOptionsResolver() + public function getOptionsResolver(): OptionsResolver { return $this->proxiedType->getOptionsResolver(); } diff --git a/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php index 35c92e2d46..835a7e879a 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php @@ -36,7 +36,7 @@ public function __construct(ResolvedFormTypeFactoryInterface $proxiedFactory, Fo /** * {@inheritdoc} */ - public function createResolvedType(FormTypeInterface $type, array $typeExtensions, ResolvedFormTypeInterface $parent = null) + public function createResolvedType(FormTypeInterface $type, array $typeExtensions, ResolvedFormTypeInterface $parent = null): ResolvedFormTypeInterface { return new ResolvedTypeDataCollectorProxy( $this->proxiedFactory->createResolvedType($type, $typeExtensions, $parent), diff --git a/Extension/DependencyInjection/DependencyInjectionExtension.php b/Extension/DependencyInjection/DependencyInjectionExtension.php index e0de02baca..5fe0371df7 100644 --- a/Extension/DependencyInjection/DependencyInjectionExtension.php +++ b/Extension/DependencyInjection/DependencyInjectionExtension.php @@ -15,6 +15,8 @@ use Symfony\Component\Form\Exception\InvalidArgumentException; use Symfony\Component\Form\FormExtensionInterface; use Symfony\Component\Form\FormTypeGuesserChain; +use Symfony\Component\Form\FormTypeGuesserInterface; +use Symfony\Component\Form\FormTypeInterface; class DependencyInjectionExtension implements FormExtensionInterface { @@ -37,7 +39,7 @@ public function __construct(ContainerInterface $typeContainer, array $typeExtens /** * {@inheritdoc} */ - public function getType(string $name) + public function getType(string $name): FormTypeInterface { if (!$this->typeContainer->has($name)) { throw new InvalidArgumentException(sprintf('The field type "%s" is not registered in the service container.', $name)); @@ -49,7 +51,7 @@ public function getType(string $name) /** * {@inheritdoc} */ - public function hasType(string $name) + public function hasType(string $name): bool { return $this->typeContainer->has($name); } @@ -57,7 +59,7 @@ public function hasType(string $name) /** * {@inheritdoc} */ - public function getTypeExtensions(string $name) + public function getTypeExtensions(string $name): array { $extensions = []; @@ -83,7 +85,7 @@ public function getTypeExtensions(string $name) /** * {@inheritdoc} */ - public function hasTypeExtensions(string $name) + public function hasTypeExtensions(string $name): bool { return isset($this->typeExtensionServices[$name]); } @@ -91,7 +93,7 @@ public function hasTypeExtensions(string $name) /** * {@inheritdoc} */ - public function getTypeGuesser() + public function getTypeGuesser(): ?FormTypeGuesserInterface { if (!$this->guesserLoaded) { $this->guesserLoaded = true; diff --git a/Extension/HttpFoundation/HttpFoundationExtension.php b/Extension/HttpFoundation/HttpFoundationExtension.php index 27305ada41..85bc4f4720 100644 --- a/Extension/HttpFoundation/HttpFoundationExtension.php +++ b/Extension/HttpFoundation/HttpFoundationExtension.php @@ -20,7 +20,7 @@ */ class HttpFoundationExtension extends AbstractExtension { - protected function loadTypeExtensions() + protected function loadTypeExtensions(): array { return [ new Type\FormTypeHttpFoundationExtension(), diff --git a/Extension/HttpFoundation/HttpFoundationRequestHandler.php b/Extension/HttpFoundation/HttpFoundationRequestHandler.php index dbb2ff4dc9..7180bafd81 100644 --- a/Extension/HttpFoundation/HttpFoundationRequestHandler.php +++ b/Extension/HttpFoundation/HttpFoundationRequestHandler.php @@ -112,15 +112,12 @@ public function handleRequest(FormInterface $form, mixed $request = null) /** * {@inheritdoc} */ - public function isFileUpload(mixed $data) + public function isFileUpload(mixed $data): bool { return $data instanceof File; } - /** - * @return int|null - */ - public function getUploadFileError(mixed $data) + public function getUploadFileError(mixed $data): ?int { if (!$data instanceof UploadedFile || $data->isValid()) { return null; diff --git a/Extension/Validator/Constraints/Form.php b/Extension/Validator/Constraints/Form.php index 49291e6718..714ef312dc 100644 --- a/Extension/Validator/Constraints/Form.php +++ b/Extension/Validator/Constraints/Form.php @@ -29,7 +29,7 @@ class Form extends Constraint /** * {@inheritdoc} */ - public function getTargets() + public function getTargets(): string|array { return self::CLASS_CONSTRAINT; } diff --git a/Extension/Validator/EventListener/ValidationListener.php b/Extension/Validator/EventListener/ValidationListener.php index 6f3b456392..3d010b77c5 100644 --- a/Extension/Validator/EventListener/ValidationListener.php +++ b/Extension/Validator/EventListener/ValidationListener.php @@ -29,7 +29,7 @@ class ValidationListener implements EventSubscriberInterface /** * {@inheritdoc} */ - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [FormEvents::POST_SUBMIT => 'validateForm']; } diff --git a/Extension/Validator/ValidatorExtension.php b/Extension/Validator/ValidatorExtension.php index d057565a18..3a0ec662a1 100644 --- a/Extension/Validator/ValidatorExtension.php +++ b/Extension/Validator/ValidatorExtension.php @@ -14,6 +14,7 @@ use Symfony\Component\Form\AbstractExtension; use Symfony\Component\Form\Extension\Validator\Constraints\Form; use Symfony\Component\Form\FormRendererInterface; +use Symfony\Component\Form\FormTypeGuesserInterface; use Symfony\Component\Validator\Constraints\Traverse; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Validator\ValidatorInterface; @@ -51,12 +52,12 @@ public function __construct(ValidatorInterface $validator, bool $legacyErrorMess $this->translator = $translator; } - public function loadTypeGuesser() + public function loadTypeGuesser(): ?FormTypeGuesserInterface { return new ValidatorTypeGuesser($this->validator); } - protected function loadTypeExtensions() + protected function loadTypeExtensions(): array { return [ new Type\FormTypeValidatorExtension($this->validator, $this->legacyErrorMessages, $this->formRenderer, $this->translator), diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index f887a599be..d18edc6f8e 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -31,7 +31,7 @@ public function __construct(MetadataFactoryInterface $metadataFactory) /** * {@inheritdoc} */ - public function guessType(string $class, string $property) + public function guessType(string $class, string $property): ?TypeGuess { return $this->guess($class, $property, function (Constraint $constraint) { return $this->guessTypeForConstraint($constraint); @@ -41,7 +41,7 @@ public function guessType(string $class, string $property) /** * {@inheritdoc} */ - public function guessRequired(string $class, string $property) + public function guessRequired(string $class, string $property): ?ValueGuess { return $this->guess($class, $property, function (Constraint $constraint) { return $this->guessRequiredForConstraint($constraint); @@ -53,7 +53,7 @@ public function guessRequired(string $class, string $property) /** * {@inheritdoc} */ - public function guessMaxLength(string $class, string $property) + public function guessMaxLength(string $class, string $property): ?ValueGuess { return $this->guess($class, $property, function (Constraint $constraint) { return $this->guessMaxLengthForConstraint($constraint); @@ -63,7 +63,7 @@ public function guessMaxLength(string $class, string $property) /** * {@inheritdoc} */ - public function guessPattern(string $class, string $property) + public function guessPattern(string $class, string $property): ?ValueGuess { return $this->guess($class, $property, function (Constraint $constraint) { return $this->guessPatternForConstraint($constraint); @@ -75,7 +75,7 @@ public function guessPattern(string $class, string $property) * * @return TypeGuess|null The guessed field class and options */ - public function guessTypeForConstraint(Constraint $constraint) + public function guessTypeForConstraint(Constraint $constraint): ?TypeGuess { switch (\get_class($constraint)) { case 'Symfony\Component\Validator\Constraints\Type': @@ -168,7 +168,7 @@ public function guessTypeForConstraint(Constraint $constraint) * * @return ValueGuess|null The guess whether the field is required */ - public function guessRequiredForConstraint(Constraint $constraint) + public function guessRequiredForConstraint(Constraint $constraint): ?ValueGuess { switch (\get_class($constraint)) { case 'Symfony\Component\Validator\Constraints\NotNull': @@ -185,7 +185,7 @@ public function guessRequiredForConstraint(Constraint $constraint) * * @return ValueGuess|null The guess for the maximum length */ - public function guessMaxLengthForConstraint(Constraint $constraint) + public function guessMaxLengthForConstraint(Constraint $constraint): ?ValueGuess { switch (\get_class($constraint)) { case 'Symfony\Component\Validator\Constraints\Length': @@ -215,7 +215,7 @@ public function guessMaxLengthForConstraint(Constraint $constraint) * * @return ValueGuess|null The guess for the pattern */ - public function guessPatternForConstraint(Constraint $constraint) + public function guessPatternForConstraint(Constraint $constraint): ?ValueGuess { switch (\get_class($constraint)) { case 'Symfony\Component\Validator\Constraints\Length': @@ -259,7 +259,7 @@ public function guessPatternForConstraint(Constraint $constraint) * * @return Guess|null The guessed value with the highest confidence */ - protected function guess(string $class, string $property, \Closure $closure, mixed $defaultValue = null) + protected function guess(string $class, string $property, \Closure $closure, mixed $defaultValue = null): ?Guess { $guesses = []; $classMetadata = $this->metadataFactory->getMetadataFor($class); diff --git a/Extension/Validator/ViolationMapper/MappingRule.php b/Extension/Validator/ViolationMapper/MappingRule.php index 745171f02a..6f078cfa23 100644 --- a/Extension/Validator/ViolationMapper/MappingRule.php +++ b/Extension/Validator/ViolationMapper/MappingRule.php @@ -30,10 +30,7 @@ public function __construct(FormInterface $origin, string $propertyPath, string $this->targetPath = $targetPath; } - /** - * @return FormInterface - */ - public function getOrigin() + public function getOrigin(): FormInterface { return $this->origin; } @@ -46,7 +43,7 @@ public function getOrigin() * * @return FormInterface|null The mapped form or null */ - public function match(string $propertyPath) + public function match(string $propertyPath): ?FormInterface { return $propertyPath === $this->propertyPath ? $this->getTarget() : null; } @@ -56,7 +53,7 @@ public function match(string $propertyPath) * * @return bool Whether the property path is a prefix of the rule or not */ - public function isPrefix(string $propertyPath) + public function isPrefix(string $propertyPath): bool { $length = \strlen($propertyPath); $prefix = substr($this->propertyPath, 0, $length); @@ -66,11 +63,9 @@ public function isPrefix(string $propertyPath) } /** - * @return FormInterface - * * @throws ErrorMappingException */ - public function getTarget() + public function getTarget(): FormInterface { $childNames = explode('.', $this->targetPath); $target = $this->origin; diff --git a/Extension/Validator/ViolationMapper/RelativePath.php b/Extension/Validator/ViolationMapper/RelativePath.php index eaee36ea79..0384edb444 100644 --- a/Extension/Validator/ViolationMapper/RelativePath.php +++ b/Extension/Validator/ViolationMapper/RelativePath.php @@ -28,10 +28,7 @@ public function __construct(FormInterface $root, string $propertyPath) $this->root = $root; } - /** - * @return FormInterface - */ - public function getRoot() + public function getRoot(): FormInterface { return $this->root; } diff --git a/Extension/Validator/ViolationMapper/ViolationPath.php b/Extension/Validator/ViolationMapper/ViolationPath.php index 337fcacfee..5e237c0d4a 100644 --- a/Extension/Validator/ViolationMapper/ViolationPath.php +++ b/Extension/Validator/ViolationMapper/ViolationPath.php @@ -101,7 +101,7 @@ public function __toString(): string /** * {@inheritdoc} */ - public function getLength() + public function getLength(): int { return $this->length; } @@ -109,7 +109,7 @@ public function getLength() /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?PropertyPathInterface { if ($this->length <= 1) { return null; @@ -130,7 +130,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getElements() + public function getElements(): array { return $this->elements; } @@ -138,7 +138,7 @@ public function getElements() /** * {@inheritdoc} */ - public function getElement(int $index) + public function getElement(int $index): string { if (!isset($this->elements[$index])) { throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index)); @@ -150,7 +150,7 @@ public function getElement(int $index) /** * {@inheritdoc} */ - public function isProperty(int $index) + public function isProperty(int $index): bool { if (!isset($this->isIndex[$index])) { throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index)); @@ -162,7 +162,7 @@ public function isProperty(int $index) /** * {@inheritdoc} */ - public function isIndex(int $index) + public function isIndex(int $index): bool { if (!isset($this->isIndex[$index])) { throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index)); @@ -185,7 +185,7 @@ public function isIndex(int $index) * * @throws OutOfBoundsException if the offset is invalid */ - public function mapsForm(int $index) + public function mapsForm(int $index): bool { if (!isset($this->mapsForm[$index])) { throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index)); diff --git a/Form.php b/Form.php index 722545163b..ecf16fdf6c 100644 --- a/Form.php +++ b/Form.php @@ -166,7 +166,7 @@ public function __clone() /** * {@inheritdoc} */ - public function getConfig() + public function getConfig(): FormConfigInterface { return $this->config; } @@ -174,7 +174,7 @@ public function getConfig() /** * {@inheritdoc} */ - public function getName() + public function getName(): string { return $this->name; } @@ -182,7 +182,7 @@ public function getName() /** * {@inheritdoc} */ - public function getPropertyPath() + public function getPropertyPath(): ?PropertyPathInterface { if ($this->propertyPath || $this->propertyPath = $this->config->getPropertyPath()) { return $this->propertyPath; @@ -210,7 +210,7 @@ public function getPropertyPath() /** * {@inheritdoc} */ - public function isRequired() + public function isRequired(): bool { if (null === $this->parent || $this->parent->isRequired()) { return $this->config->getRequired(); @@ -222,7 +222,7 @@ public function isRequired() /** * {@inheritdoc} */ - public function isDisabled() + public function isDisabled(): bool { if (null === $this->parent || !$this->parent->isDisabled()) { return $this->config->getDisabled(); @@ -234,7 +234,7 @@ public function isDisabled() /** * {@inheritdoc} */ - public function setParent(FormInterface $parent = null) + public function setParent(FormInterface $parent = null): static { if ($this->submitted) { throw new AlreadySubmittedException('You cannot set the parent of a submitted form.'); @@ -252,7 +252,7 @@ public function setParent(FormInterface $parent = null) /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?FormInterface { return $this->parent; } @@ -260,7 +260,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getRoot() + public function getRoot(): FormInterface { return $this->parent ? $this->parent->getRoot() : $this; } @@ -268,7 +268,7 @@ public function getRoot() /** * {@inheritdoc} */ - public function isRoot() + public function isRoot(): bool { return null === $this->parent; } @@ -276,7 +276,7 @@ public function isRoot() /** * {@inheritdoc} */ - public function setData(mixed $modelData) + public function setData(mixed $modelData): static { // If the form is submitted while disabled, it is set to submitted, but the data is not // changed. In such cases (i.e. when the form is not initialized yet) don't @@ -358,7 +358,7 @@ public function setData(mixed $modelData) /** * {@inheritdoc} */ - public function getData() + public function getData(): mixed { if ($this->inheritData) { if (!$this->parent) { @@ -382,7 +382,7 @@ public function getData() /** * {@inheritdoc} */ - public function getNormData() + public function getNormData(): mixed { if ($this->inheritData) { if (!$this->parent) { @@ -406,7 +406,7 @@ public function getNormData() /** * {@inheritdoc} */ - public function getViewData() + public function getViewData(): mixed { if ($this->inheritData) { if (!$this->parent) { @@ -430,7 +430,7 @@ public function getViewData() /** * {@inheritdoc} */ - public function getExtraData() + public function getExtraData(): array { return $this->extraData; } @@ -438,7 +438,7 @@ public function getExtraData() /** * {@inheritdoc} */ - public function initialize() + public function initialize(): static { if (null !== $this->parent) { throw new RuntimeException('Only root forms should be initialized.'); @@ -457,7 +457,7 @@ public function initialize() /** * {@inheritdoc} */ - public function handleRequest(mixed $request = null) + public function handleRequest(mixed $request = null): static { $this->config->getRequestHandler()->handleRequest($this, $request); @@ -467,7 +467,7 @@ public function handleRequest(mixed $request = null) /** * {@inheritdoc} */ - public function submit(mixed $submittedData, bool $clearMissing = true) + public function submit(mixed $submittedData, bool $clearMissing = true): static { if ($this->submitted) { throw new AlreadySubmittedException('A form can only be submitted once.'); @@ -646,7 +646,7 @@ public function submit(mixed $submittedData, bool $clearMissing = true) /** * {@inheritdoc} */ - public function addError(FormError $error) + public function addError(FormError $error): static { if (null === $error->getOrigin()) { $error->setOrigin($this); @@ -664,7 +664,7 @@ public function addError(FormError $error) /** * {@inheritdoc} */ - public function isSubmitted() + public function isSubmitted(): bool { return $this->submitted; } @@ -672,7 +672,7 @@ public function isSubmitted() /** * {@inheritdoc} */ - public function isSynchronized() + public function isSynchronized(): bool { return null === $this->transformationFailure; } @@ -680,7 +680,7 @@ public function isSynchronized() /** * {@inheritdoc} */ - public function getTransformationFailure() + public function getTransformationFailure(): ?Exception\TransformationFailedException { return $this->transformationFailure; } @@ -688,7 +688,7 @@ public function getTransformationFailure() /** * {@inheritdoc} */ - public function isEmpty() + public function isEmpty(): bool { foreach ($this->children as $child) { if (!$child->isEmpty()) { @@ -710,7 +710,7 @@ public function isEmpty() /** * {@inheritdoc} */ - public function isValid() + public function isValid(): bool { if (!$this->submitted) { throw new LogicException('Cannot check if an unsubmitted form is valid. Call Form::isSubmitted() before Form::isValid().'); @@ -728,7 +728,7 @@ public function isValid() * * @return FormInterface|ClickableInterface|null */ - public function getClickedButton() + public function getClickedButton(): FormInterface|ClickableInterface|null { if ($this->clickedButton) { return $this->clickedButton; @@ -740,7 +740,7 @@ public function getClickedButton() /** * {@inheritdoc} */ - public function getErrors(bool $deep = false, bool $flatten = true) + public function getErrors(bool $deep = false, bool $flatten = true): FormErrorIterator { $errors = $this->errors; @@ -776,7 +776,7 @@ public function getErrors(bool $deep = false, bool $flatten = true) * * @return $this */ - public function clearErrors(bool $deep = false): self + public function clearErrors(bool $deep = false): static { $this->errors = []; @@ -795,7 +795,7 @@ public function clearErrors(bool $deep = false): self /** * {@inheritdoc} */ - public function all() + public function all(): array { return iterator_to_array($this->children); } @@ -803,7 +803,7 @@ public function all() /** * {@inheritdoc} */ - public function add(FormInterface|string $child, string $type = null, array $options = []) + public function add(FormInterface|string $child, string $type = null, array $options = []): static { if ($this->submitted) { throw new AlreadySubmittedException('You cannot add children to a submitted form.'); @@ -874,7 +874,7 @@ public function add(FormInterface|string $child, string $type = null, array $opt /** * {@inheritdoc} */ - public function remove(string $name) + public function remove(string $name): static { if ($this->submitted) { throw new AlreadySubmittedException('You cannot remove children from a submitted form.'); @@ -894,7 +894,7 @@ public function remove(string $name) /** * {@inheritdoc} */ - public function has(string $name) + public function has(string $name): bool { return isset($this->children[$name]); } @@ -902,7 +902,7 @@ public function has(string $name) /** * {@inheritdoc} */ - public function get(string $name) + public function get(string $name): FormInterface { if (isset($this->children[$name])) { return $this->children[$name]; @@ -984,7 +984,7 @@ public function count(): int /** * {@inheritdoc} */ - public function createView(FormView $parent = null) + public function createView(FormView $parent = null): FormView { if (null === $parent && $this->parent) { $parent = $this->parent->createView(); diff --git a/FormBuilder.php b/FormBuilder.php index 66762cbbff..9af2f4d998 100644 --- a/FormBuilder.php +++ b/FormBuilder.php @@ -46,7 +46,7 @@ public function __construct(?string $name, ?string $dataClass, EventDispatcherIn /** * {@inheritdoc} */ - public function add(FormBuilderInterface|string $child, string $type = null, array $options = []) + public function add(FormBuilderInterface|string $child, string $type = null, array $options = []): static { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -79,7 +79,7 @@ public function add(FormBuilderInterface|string $child, string $type = null, arr /** * {@inheritdoc} */ - public function create(string $name, string $type = null, array $options = []) + public function create(string $name, string $type = null, array $options = []): FormBuilderInterface { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -99,7 +99,7 @@ public function create(string $name, string $type = null, array $options = []) /** * {@inheritdoc} */ - public function get(string $name) + public function get(string $name): FormBuilderInterface { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -119,7 +119,7 @@ public function get(string $name) /** * {@inheritdoc} */ - public function remove(string $name) + public function remove(string $name): static { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -133,7 +133,7 @@ public function remove(string $name) /** * {@inheritdoc} */ - public function has(string $name) + public function has(string $name): bool { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -145,7 +145,7 @@ public function has(string $name) /** * {@inheritdoc} */ - public function all() + public function all(): array { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -168,7 +168,7 @@ public function count(): int /** * {@inheritdoc} */ - public function getFormConfig() + public function getFormConfig(): FormConfigInterface { /** @var $config self */ $config = parent::getFormConfig(); @@ -182,7 +182,7 @@ public function getFormConfig() /** * {@inheritdoc} */ - public function getForm() + public function getForm(): FormInterface { if ($this->locked) { throw new BadMethodCallException('FormBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); diff --git a/FormBuilderInterface.php b/FormBuilderInterface.php index e3f5028d60..d864e3fe42 100644 --- a/FormBuilderInterface.php +++ b/FormBuilderInterface.php @@ -26,10 +26,8 @@ interface FormBuilderInterface extends \Traversable, \Countable, FormConfigBuild * object hierarchy. * * @param array $options - * - * @return self */ - public function add(string|FormBuilderInterface $child, string $type = null, array $options = []); + public function add(string|FormBuilderInterface $child, string $type = null, array $options = []): static; /** * Creates a form builder. @@ -37,45 +35,37 @@ public function add(string|FormBuilderInterface $child, string $type = null, arr * @param string $name The name of the form or the name of the property * @param string|null $type The type of the form or null if name is a property * @param array $options - * - * @return self */ - public function create(string $name, string $type = null, array $options = []); + public function create(string $name, string $type = null, array $options = []): self; /** * Returns a child by name. * - * @return self - * * @throws Exception\InvalidArgumentException if the given child does not exist */ - public function get(string $name); + public function get(string $name): self; /** * Removes the field with the given name. - * - * @return self */ - public function remove(string $name); + public function remove(string $name): static; /** * Returns whether a field with the given name exists. - * - * @return bool */ - public function has(string $name); + public function has(string $name): bool; /** * Returns the children. * * @return array */ - public function all(); + public function all(): array; /** * Creates the form. * * @return FormInterface The form */ - public function getForm(); + public function getForm(): FormInterface; } diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 479d70c45c..43a200fd1a 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -87,7 +87,7 @@ public function __construct(?string $name, ?string $dataClass, EventDispatcherIn /** * {@inheritdoc} */ - public function addEventListener(string $eventName, callable $listener, int $priority = 0) + public function addEventListener(string $eventName, callable $listener, int $priority = 0): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -101,7 +101,7 @@ public function addEventListener(string $eventName, callable $listener, int $pri /** * {@inheritdoc} */ - public function addEventSubscriber(EventSubscriberInterface $subscriber) + public function addEventSubscriber(EventSubscriberInterface $subscriber): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -115,7 +115,7 @@ public function addEventSubscriber(EventSubscriberInterface $subscriber) /** * {@inheritdoc} */ - public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false) + public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -133,7 +133,7 @@ public function addViewTransformer(DataTransformerInterface $viewTransformer, bo /** * {@inheritdoc} */ - public function resetViewTransformers() + public function resetViewTransformers(): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -147,7 +147,7 @@ public function resetViewTransformers() /** * {@inheritdoc} */ - public function addModelTransformer(DataTransformerInterface $modelTransformer, bool $forceAppend = false) + public function addModelTransformer(DataTransformerInterface $modelTransformer, bool $forceAppend = false): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -165,7 +165,7 @@ public function addModelTransformer(DataTransformerInterface $modelTransformer, /** * {@inheritdoc} */ - public function resetModelTransformers() + public function resetModelTransformers(): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -179,7 +179,7 @@ public function resetModelTransformers() /** * {@inheritdoc} */ - public function getEventDispatcher() + public function getEventDispatcher(): EventDispatcherInterface { if ($this->locked && !$this->dispatcher instanceof ImmutableEventDispatcher) { $this->dispatcher = new ImmutableEventDispatcher($this->dispatcher); @@ -191,7 +191,7 @@ public function getEventDispatcher() /** * {@inheritdoc} */ - public function getName() + public function getName(): string { return $this->name; } @@ -199,7 +199,7 @@ public function getName() /** * {@inheritdoc} */ - public function getPropertyPath() + public function getPropertyPath(): ?PropertyPathInterface { return $this->propertyPath; } @@ -207,7 +207,7 @@ public function getPropertyPath() /** * {@inheritdoc} */ - public function getMapped() + public function getMapped(): bool { return $this->mapped; } @@ -215,7 +215,7 @@ public function getMapped() /** * {@inheritdoc} */ - public function getByReference() + public function getByReference(): bool { return $this->byReference; } @@ -223,7 +223,7 @@ public function getByReference() /** * {@inheritdoc} */ - public function getInheritData() + public function getInheritData(): bool { return $this->inheritData; } @@ -231,7 +231,7 @@ public function getInheritData() /** * {@inheritdoc} */ - public function getCompound() + public function getCompound(): bool { return $this->compound; } @@ -239,7 +239,7 @@ public function getCompound() /** * {@inheritdoc} */ - public function getType() + public function getType(): ResolvedFormTypeInterface { return $this->type; } @@ -247,7 +247,7 @@ public function getType() /** * {@inheritdoc} */ - public function getViewTransformers() + public function getViewTransformers(): array { return $this->viewTransformers; } @@ -255,7 +255,7 @@ public function getViewTransformers() /** * {@inheritdoc} */ - public function getModelTransformers() + public function getModelTransformers(): array { return $this->modelTransformers; } @@ -263,7 +263,7 @@ public function getModelTransformers() /** * {@inheritdoc} */ - public function getDataMapper() + public function getDataMapper(): ?DataMapperInterface { return $this->dataMapper; } @@ -271,7 +271,7 @@ public function getDataMapper() /** * {@inheritdoc} */ - public function getRequired() + public function getRequired(): bool { return $this->required; } @@ -279,7 +279,7 @@ public function getRequired() /** * {@inheritdoc} */ - public function getDisabled() + public function getDisabled(): bool { return $this->disabled; } @@ -287,7 +287,7 @@ public function getDisabled() /** * {@inheritdoc} */ - public function getErrorBubbling() + public function getErrorBubbling(): bool { return $this->errorBubbling; } @@ -295,7 +295,7 @@ public function getErrorBubbling() /** * {@inheritdoc} */ - public function getEmptyData() + public function getEmptyData(): mixed { return $this->emptyData; } @@ -303,7 +303,7 @@ public function getEmptyData() /** * {@inheritdoc} */ - public function getAttributes() + public function getAttributes(): array { return $this->attributes; } @@ -311,7 +311,7 @@ public function getAttributes() /** * {@inheritdoc} */ - public function hasAttribute(string $name) + public function hasAttribute(string $name): bool { return \array_key_exists($name, $this->attributes); } @@ -319,7 +319,7 @@ public function hasAttribute(string $name) /** * {@inheritdoc} */ - public function getAttribute(string $name, mixed $default = null) + public function getAttribute(string $name, mixed $default = null): mixed { return \array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; } @@ -327,7 +327,7 @@ public function getAttribute(string $name, mixed $default = null) /** * {@inheritdoc} */ - public function getData() + public function getData(): mixed { return $this->data; } @@ -335,7 +335,7 @@ public function getData() /** * {@inheritdoc} */ - public function getDataClass() + public function getDataClass(): ?string { return $this->dataClass; } @@ -343,7 +343,7 @@ public function getDataClass() /** * {@inheritdoc} */ - public function getDataLocked() + public function getDataLocked(): bool { return $this->dataLocked; } @@ -351,7 +351,7 @@ public function getDataLocked() /** * {@inheritdoc} */ - public function getFormFactory() + public function getFormFactory(): FormFactoryInterface { if (!isset($this->formFactory)) { throw new BadMethodCallException('The form factory must be set before retrieving it.'); @@ -363,7 +363,7 @@ public function getFormFactory() /** * {@inheritdoc} */ - public function getAction() + public function getAction(): string { return $this->action; } @@ -371,7 +371,7 @@ public function getAction() /** * {@inheritdoc} */ - public function getMethod() + public function getMethod(): string { return $this->method; } @@ -379,7 +379,7 @@ public function getMethod() /** * {@inheritdoc} */ - public function getRequestHandler() + public function getRequestHandler(): RequestHandlerInterface { return $this->requestHandler ??= self::$nativeRequestHandler ??= new NativeRequestHandler(); } @@ -387,7 +387,7 @@ public function getRequestHandler() /** * {@inheritdoc} */ - public function getAutoInitialize() + public function getAutoInitialize(): bool { return $this->autoInitialize; } @@ -395,7 +395,7 @@ public function getAutoInitialize() /** * {@inheritdoc} */ - public function getOptions() + public function getOptions(): array { return $this->options; } @@ -403,7 +403,7 @@ public function getOptions() /** * {@inheritdoc} */ - public function hasOption(string $name) + public function hasOption(string $name): bool { return \array_key_exists($name, $this->options); } @@ -411,7 +411,7 @@ public function hasOption(string $name) /** * {@inheritdoc} */ - public function getOption(string $name, mixed $default = null) + public function getOption(string $name, mixed $default = null): mixed { return \array_key_exists($name, $this->options) ? $this->options[$name] : $default; } @@ -427,7 +427,7 @@ public function getIsEmptyCallback(): ?callable /** * {@inheritdoc} */ - public function setAttribute(string $name, mixed $value) + public function setAttribute(string $name, mixed $value): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -441,7 +441,7 @@ public function setAttribute(string $name, mixed $value) /** * {@inheritdoc} */ - public function setAttributes(array $attributes) + public function setAttributes(array $attributes): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -455,7 +455,7 @@ public function setAttributes(array $attributes) /** * {@inheritdoc} */ - public function setDataMapper(DataMapperInterface $dataMapper = null) + public function setDataMapper(DataMapperInterface $dataMapper = null): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -469,7 +469,7 @@ public function setDataMapper(DataMapperInterface $dataMapper = null) /** * {@inheritdoc} */ - public function setDisabled(bool $disabled) + public function setDisabled(bool $disabled): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -483,7 +483,7 @@ public function setDisabled(bool $disabled) /** * {@inheritdoc} */ - public function setEmptyData(mixed $emptyData) + public function setEmptyData(mixed $emptyData): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -497,7 +497,7 @@ public function setEmptyData(mixed $emptyData) /** * {@inheritdoc} */ - public function setErrorBubbling(bool $errorBubbling) + public function setErrorBubbling(bool $errorBubbling): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -511,7 +511,7 @@ public function setErrorBubbling(bool $errorBubbling) /** * {@inheritdoc} */ - public function setRequired(bool $required) + public function setRequired(bool $required): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -525,7 +525,7 @@ public function setRequired(bool $required) /** * {@inheritdoc} */ - public function setPropertyPath(string|PropertyPathInterface|null $propertyPath) + public function setPropertyPath(string|PropertyPathInterface|null $propertyPath): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -543,7 +543,7 @@ public function setPropertyPath(string|PropertyPathInterface|null $propertyPath) /** * {@inheritdoc} */ - public function setMapped(bool $mapped) + public function setMapped(bool $mapped): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -557,7 +557,7 @@ public function setMapped(bool $mapped) /** * {@inheritdoc} */ - public function setByReference(bool $byReference) + public function setByReference(bool $byReference): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -571,7 +571,7 @@ public function setByReference(bool $byReference) /** * {@inheritdoc} */ - public function setInheritData(bool $inheritData) + public function setInheritData(bool $inheritData): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -585,7 +585,7 @@ public function setInheritData(bool $inheritData) /** * {@inheritdoc} */ - public function setCompound(bool $compound) + public function setCompound(bool $compound): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -599,7 +599,7 @@ public function setCompound(bool $compound) /** * {@inheritdoc} */ - public function setType(ResolvedFormTypeInterface $type) + public function setType(ResolvedFormTypeInterface $type): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -613,7 +613,7 @@ public function setType(ResolvedFormTypeInterface $type) /** * {@inheritdoc} */ - public function setData(mixed $data) + public function setData(mixed $data): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -627,7 +627,7 @@ public function setData(mixed $data) /** * {@inheritdoc} */ - public function setDataLocked(bool $locked) + public function setDataLocked(bool $locked): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -655,7 +655,7 @@ public function setFormFactory(FormFactoryInterface $formFactory) /** * {@inheritdoc} */ - public function setAction(string $action) + public function setAction(string $action): static { if ($this->locked) { throw new BadMethodCallException('The config builder cannot be modified anymore.'); @@ -669,7 +669,7 @@ public function setAction(string $action) /** * {@inheritdoc} */ - public function setMethod(string $method) + public function setMethod(string $method): static { if ($this->locked) { throw new BadMethodCallException('The config builder cannot be modified anymore.'); @@ -683,7 +683,7 @@ public function setMethod(string $method) /** * {@inheritdoc} */ - public function setRequestHandler(RequestHandlerInterface $requestHandler) + public function setRequestHandler(RequestHandlerInterface $requestHandler): static { if ($this->locked) { throw new BadMethodCallException('The config builder cannot be modified anymore.'); @@ -697,7 +697,7 @@ public function setRequestHandler(RequestHandlerInterface $requestHandler) /** * {@inheritdoc} */ - public function setAutoInitialize(bool $initialize) + public function setAutoInitialize(bool $initialize): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); @@ -711,7 +711,7 @@ public function setAutoInitialize(bool $initialize) /** * {@inheritdoc} */ - public function getFormConfig() + public function getFormConfig(): FormConfigInterface { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); diff --git a/FormConfigBuilderInterface.php b/FormConfigBuilderInterface.php index 05d527480b..9b95e34182 100644 --- a/FormConfigBuilderInterface.php +++ b/FormConfigBuilderInterface.php @@ -28,14 +28,14 @@ interface FormConfigBuilderInterface extends FormConfigInterface * * @return $this The configuration object */ - public function addEventListener(string $eventName, callable $listener, int $priority = 0); + public function addEventListener(string $eventName, callable $listener, int $priority = 0): static; /** * Adds an event subscriber for events on this form. * * @return $this The configuration object */ - public function addEventSubscriber(EventSubscriberInterface $subscriber); + public function addEventSubscriber(EventSubscriberInterface $subscriber): static; /** * Appends / prepends a transformer to the view transformer chain. @@ -49,14 +49,14 @@ public function addEventSubscriber(EventSubscriberInterface $subscriber); * * @return $this The configuration object */ - public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false); + public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false): static; /** * Clears the view transformers. * * @return $this The configuration object */ - public function resetViewTransformers(); + public function resetViewTransformers(): static; /** * Prepends / appends a transformer to the normalization transformer chain. @@ -70,14 +70,14 @@ public function resetViewTransformers(); * * @return $this The configuration object */ - public function addModelTransformer(DataTransformerInterface $modelTransformer, bool $forceAppend = false); + public function addModelTransformer(DataTransformerInterface $modelTransformer, bool $forceAppend = false): static; /** * Clears the normalization transformers. * * @return $this The configuration object */ - public function resetModelTransformers(); + public function resetModelTransformers(): static; /** * Sets the value for an attribute. @@ -86,28 +86,28 @@ public function resetModelTransformers(); * * @return $this The configuration object */ - public function setAttribute(string $name, mixed $value); + public function setAttribute(string $name, mixed $value): static; /** * Sets the attributes. * * @return $this The configuration object */ - public function setAttributes(array $attributes); + public function setAttributes(array $attributes): static; /** * Sets the data mapper used by the form. * * @return $this The configuration object */ - public function setDataMapper(DataMapperInterface $dataMapper = null); + public function setDataMapper(DataMapperInterface $dataMapper = null): static; /** * Sets whether the form is disabled. * * @return $this The configuration object */ - public function setDisabled(bool $disabled); + public function setDisabled(bool $disabled): static; /** * Sets the data used for the client data when no value is submitted. @@ -116,21 +116,21 @@ public function setDisabled(bool $disabled); * * @return $this The configuration object */ - public function setEmptyData(mixed $emptyData); + public function setEmptyData(mixed $emptyData): static; /** * Sets whether errors bubble up to the parent. * * @return $this The configuration object */ - public function setErrorBubbling(bool $errorBubbling); + public function setErrorBubbling(bool $errorBubbling): static; /** * Sets whether this field is required to be filled out when submitted. * * @return $this The configuration object */ - public function setRequired(bool $required); + public function setRequired(bool $required): static; /** * Sets the property path that the form should be mapped to. @@ -140,7 +140,7 @@ public function setRequired(bool $required); * * @return $this The configuration object */ - public function setPropertyPath(string|PropertyPathInterface|null $propertyPath); + public function setPropertyPath(string|PropertyPathInterface|null $propertyPath): static; /** * Sets whether the form should be mapped to an element of its @@ -148,21 +148,21 @@ public function setPropertyPath(string|PropertyPathInterface|null $propertyPath) * * @return $this The configuration object */ - public function setMapped(bool $mapped); + public function setMapped(bool $mapped): static; /** * Sets whether the form's data should be modified by reference. * * @return $this The configuration object */ - public function setByReference(bool $byReference); + public function setByReference(bool $byReference): static; /** * Sets whether the form should read and write the data of its parent. * * @return $this The configuration object */ - public function setInheritData(bool $inheritData); + public function setInheritData(bool $inheritData): static; /** * Sets whether the form should be compound. @@ -171,14 +171,14 @@ public function setInheritData(bool $inheritData); * * @see FormConfigInterface::getCompound() */ - public function setCompound(bool $compound); + public function setCompound(bool $compound): static; /** * Sets the resolved type. * * @return $this The configuration object */ - public function setType(ResolvedFormTypeInterface $type); + public function setType(ResolvedFormTypeInterface $type): static; /** * Sets the initial data of the form. @@ -187,7 +187,7 @@ public function setType(ResolvedFormTypeInterface $type); * * @return $this The configuration object */ - public function setData(mixed $data); + public function setData(mixed $data): static; /** * Locks the form's data to the data passed in the configuration. @@ -201,7 +201,7 @@ public function setData(mixed $data); * * @return $this The configuration object */ - public function setDataLocked(bool $locked); + public function setDataLocked(bool $locked): static; /** * Sets the form factory used for creating new forms. @@ -213,21 +213,21 @@ public function setFormFactory(FormFactoryInterface $formFactory); * * @return $this The configuration object */ - public function setAction(string $action); + public function setAction(string $action): static; /** * Sets the HTTP method used by the form. * * @return $this The configuration object */ - public function setMethod(string $method); + public function setMethod(string $method): static; /** * Sets the request handler used by the form. * * @return $this The configuration object */ - public function setRequestHandler(RequestHandlerInterface $requestHandler); + public function setRequestHandler(RequestHandlerInterface $requestHandler): static; /** * Sets whether the form should be initialized automatically. @@ -241,14 +241,12 @@ public function setRequestHandler(RequestHandlerInterface $requestHandler); * * @return $this The configuration object */ - public function setAutoInitialize(bool $initialize); + public function setAutoInitialize(bool $initialize): static; /** * Builds and returns the form configuration. - * - * @return FormConfigInterface */ - public function getFormConfig(); + public function getFormConfig(): FormConfigInterface; /** * Sets the callback that will be called to determine if the model diff --git a/FormConfigInterface.php b/FormConfigInterface.php index 7ee4565077..87d7ee7f67 100644 --- a/FormConfigInterface.php +++ b/FormConfigInterface.php @@ -26,21 +26,21 @@ interface FormConfigInterface * * @return EventDispatcherInterface The dispatcher */ - public function getEventDispatcher(); + public function getEventDispatcher(): EventDispatcherInterface; /** * Returns the name of the form used as HTTP parameter. * * @return string The form name */ - public function getName(); + public function getName(): string; /** * Returns the property path that the form should be mapped to. * * @return PropertyPathInterface|null The property path */ - public function getPropertyPath(); + public function getPropertyPath(): ?PropertyPathInterface; /** * Returns whether the form should be mapped to an element of its @@ -48,21 +48,21 @@ public function getPropertyPath(); * * @return bool Whether the form is mapped */ - public function getMapped(); + public function getMapped(): bool; /** * Returns whether the form's data should be modified by reference. * * @return bool Whether to modify the form's data by reference */ - public function getByReference(); + public function getByReference(): bool; /** * Returns whether the form should read and write the data of its parent. * * @return bool Whether the form should inherit its parent's data */ - public function getInheritData(); + public function getInheritData(): bool; /** * Returns whether the form is compound. @@ -75,56 +75,56 @@ public function getInheritData(); * * @return bool Whether the form is compound */ - public function getCompound(); + public function getCompound(): bool; /** * Returns the resolved form type used to construct the form. * * @return ResolvedFormTypeInterface The form's resolved type */ - public function getType(); + public function getType(): ResolvedFormTypeInterface; /** * Returns the view transformers of the form. * * @return DataTransformerInterface[] */ - public function getViewTransformers(); + public function getViewTransformers(): array; /** * Returns the model transformers of the form. * * @return DataTransformerInterface[] */ - public function getModelTransformers(); + public function getModelTransformers(): array; /** * Returns the data mapper of the compound form or null for a simple form. * * @return DataMapperInterface|null The data mapper */ - public function getDataMapper(); + public function getDataMapper(): ?DataMapperInterface; /** * Returns whether the form is required. * * @return bool Whether the form is required */ - public function getRequired(); + public function getRequired(): bool; /** * Returns whether the form is disabled. * * @return bool Whether the form is disabled */ - public function getDisabled(); + public function getDisabled(): bool; /** * Returns whether errors attached to the form will bubble to its parent. * * @return bool Whether errors will bubble up */ - public function getErrorBubbling(); + public function getErrorBubbling(): bool; /** * Used when the view data is empty on submission. @@ -137,42 +137,42 @@ public function getErrorBubbling(); * * @return mixed The data used when the submitted form is initially empty */ - public function getEmptyData(); + public function getEmptyData(): mixed; /** * Returns additional attributes of the form. * * @return array An array of key-value combinations */ - public function getAttributes(); + public function getAttributes(): array; /** * Returns whether the attribute with the given name exists. * * @return bool Whether the attribute exists */ - public function hasAttribute(string $name); + public function hasAttribute(string $name): bool; /** * Returns the value of the given attribute. * * @return mixed The attribute value */ - public function getAttribute(string $name, mixed $default = null); + public function getAttribute(string $name, mixed $default = null): mixed; /** * Returns the initial data of the form. * * @return mixed The initial form data */ - public function getData(); + public function getData(): mixed; /** * Returns the class of the view data or null if the data is scalar or an array. * * @return string|null The data class or null */ - public function getDataClass(); + public function getDataClass(): ?string; /** * Returns whether the form's data is locked. @@ -183,35 +183,35 @@ public function getDataClass(); * * @return bool Whether the data is locked */ - public function getDataLocked(); + public function getDataLocked(): bool; /** * Returns the form factory used for creating new forms. * * @return FormFactoryInterface The form factory */ - public function getFormFactory(); + public function getFormFactory(): FormFactoryInterface; /** * Returns the target URL of the form. * * @return string The target URL of the form */ - public function getAction(); + public function getAction(): string; /** * Returns the HTTP method used by the form. * * @return string The HTTP method of the form */ - public function getMethod(); + public function getMethod(): string; /** * Returns the request handler used by the form. * * @return RequestHandlerInterface The request handler */ - public function getRequestHandler(); + public function getRequestHandler(): RequestHandlerInterface; /** * Returns whether the form should be initialized upon creation. @@ -219,28 +219,28 @@ public function getRequestHandler(); * @return bool returns true if the form should be initialized * when created, false otherwise */ - public function getAutoInitialize(); + public function getAutoInitialize(): bool; /** * Returns all options passed during the construction of the form. * * @return array The passed options */ - public function getOptions(); + public function getOptions(): array; /** * Returns whether a specific option exists. * * @return bool Whether the option exists */ - public function hasOption(string $name); + public function hasOption(string $name): bool; /** * Returns the value of a specific option. * * @return mixed The option value */ - public function getOption(string $name, mixed $default = null); + public function getOption(string $name, mixed $default = null): mixed; /** * Returns a callable that takes the model data as argument and that returns if it is empty or not. diff --git a/FormError.php b/FormError.php index a38b4346d5..01d2c9e62a 100644 --- a/FormError.php +++ b/FormError.php @@ -56,40 +56,32 @@ public function __construct(string $message, string $messageTemplate = null, arr /** * Returns the error message. - * - * @return string */ - public function getMessage() + public function getMessage(): string { return $this->message; } /** * Returns the error message template. - * - * @return string */ - public function getMessageTemplate() + public function getMessageTemplate(): string { return $this->messageTemplate; } /** * Returns the parameters to be inserted in the message template. - * - * @return array */ - public function getMessageParameters() + public function getMessageParameters(): array { return $this->messageParameters; } /** * Returns the value for error message pluralization. - * - * @return int|null */ - public function getMessagePluralization() + public function getMessagePluralization(): ?int { return $this->messagePluralization; } @@ -99,7 +91,7 @@ public function getMessagePluralization() * * @return mixed The cause of this error */ - public function getCause() + public function getCause(): mixed { return $this->cause; } @@ -125,7 +117,7 @@ public function setOrigin(FormInterface $origin) * * @return FormInterface|null The form that caused this error */ - public function getOrigin() + public function getOrigin(): ?FormInterface { return $this->origin; } diff --git a/FormErrorIterator.php b/FormErrorIterator.php index 0cb2ff275a..a6b9719059 100644 --- a/FormErrorIterator.php +++ b/FormErrorIterator.php @@ -82,7 +82,7 @@ public function __toString(): string * * @return FormInterface The form whose errors are iterated by this object */ - public function getForm() + public function getForm(): FormInterface { return $this->form; } @@ -239,10 +239,8 @@ public function seek(int $position): void * Creates iterator for errors with specific codes. * * @param string|string[] $codes The codes to find - * - * @return static */ - public function findByCodes(string|array $codes) + public function findByCodes(string|array $codes): static { $codes = (array) $codes; $errors = []; diff --git a/FormEvent.php b/FormEvent.php index c7999e4b15..c9c3053cfe 100644 --- a/FormEvent.php +++ b/FormEvent.php @@ -29,20 +29,16 @@ public function __construct(FormInterface $form, mixed $data) /** * Returns the form at the source of the event. - * - * @return FormInterface */ - public function getForm() + public function getForm(): FormInterface { return $this->form; } /** * Returns the data associated with this event. - * - * @return mixed */ - public function getData() + public function getData(): mixed { return $this->data; } diff --git a/FormExtensionInterface.php b/FormExtensionInterface.php index c16b13e2fc..84aff31f45 100644 --- a/FormExtensionInterface.php +++ b/FormExtensionInterface.php @@ -25,7 +25,7 @@ interface FormExtensionInterface * * @throws Exception\InvalidArgumentException if the given type is not supported by this extension */ - public function getType(string $name); + public function getType(string $name): FormTypeInterface; /** * Returns whether the given type is supported. @@ -34,7 +34,7 @@ public function getType(string $name); * * @return bool Whether the type is supported by this extension */ - public function hasType(string $name); + public function hasType(string $name): bool; /** * Returns the extensions for the given type. @@ -43,7 +43,7 @@ public function hasType(string $name); * * @return FormTypeExtensionInterface[] */ - public function getTypeExtensions(string $name); + public function getTypeExtensions(string $name): array; /** * Returns whether this extension provides type extensions for the given type. @@ -52,12 +52,12 @@ public function getTypeExtensions(string $name); * * @return bool Whether the given type has extensions */ - public function hasTypeExtensions(string $name); + public function hasTypeExtensions(string $name): bool; /** * Returns the type guesser provided by this extension. * * @return FormTypeGuesserInterface|null The type guesser */ - public function getTypeGuesser(); + public function getTypeGuesser(): ?FormTypeGuesserInterface; } diff --git a/FormFactory.php b/FormFactory.php index 4468183cea..c09c50cf06 100644 --- a/FormFactory.php +++ b/FormFactory.php @@ -26,7 +26,7 @@ public function __construct(FormRegistryInterface $registry) /** * {@inheritdoc} */ - public function create(string $type = FormType::class, mixed $data = null, array $options = []) + public function create(string $type = FormType::class, mixed $data = null, array $options = []): FormInterface { return $this->createBuilder($type, $data, $options)->getForm(); } @@ -34,7 +34,7 @@ public function create(string $type = FormType::class, mixed $data = null, array /** * {@inheritdoc} */ - public function createNamed(string $name, string $type = FormType::class, mixed $data = null, array $options = []) + public function createNamed(string $name, string $type = FormType::class, mixed $data = null, array $options = []): FormInterface { return $this->createNamedBuilder($name, $type, $data, $options)->getForm(); } @@ -42,7 +42,7 @@ public function createNamed(string $name, string $type = FormType::class, mixed /** * {@inheritdoc} */ - public function createForProperty(string $class, string $property, mixed $data = null, array $options = []) + public function createForProperty(string $class, string $property, mixed $data = null, array $options = []): FormInterface { return $this->createBuilderForProperty($class, $property, $data, $options)->getForm(); } @@ -50,7 +50,7 @@ public function createForProperty(string $class, string $property, mixed $data = /** * {@inheritdoc} */ - public function createBuilder(string $type = FormType::class, mixed $data = null, array $options = []) + public function createBuilder(string $type = FormType::class, mixed $data = null, array $options = []): FormBuilderInterface { return $this->createNamedBuilder($this->registry->getType($type)->getBlockPrefix(), $type, $data, $options); } @@ -58,7 +58,7 @@ public function createBuilder(string $type = FormType::class, mixed $data = null /** * {@inheritdoc} */ - public function createNamedBuilder(string $name, string $type = FormType::class, mixed $data = null, array $options = []) + public function createNamedBuilder(string $name, string $type = FormType::class, mixed $data = null, array $options = []): FormBuilderInterface { if (null !== $data && !\array_key_exists('data', $options)) { $options['data'] = $data; @@ -78,7 +78,7 @@ public function createNamedBuilder(string $name, string $type = FormType::class, /** * {@inheritdoc} */ - public function createBuilderForProperty(string $class, string $property, mixed $data = null, array $options = []) + public function createBuilderForProperty(string $class, string $property, mixed $data = null, array $options = []): FormBuilderInterface { if (null === $guesser = $this->registry->getTypeGuesser()) { return $this->createNamedBuilder($property, TextType::class, $data, $options); diff --git a/FormFactoryBuilder.php b/FormFactoryBuilder.php index d541f6aa3a..0ad58a660e 100644 --- a/FormFactoryBuilder.php +++ b/FormFactoryBuilder.php @@ -52,7 +52,7 @@ public function __construct(bool $forceCoreExtension = false) /** * {@inheritdoc} */ - public function setResolvedTypeFactory(ResolvedFormTypeFactoryInterface $resolvedTypeFactory) + public function setResolvedTypeFactory(ResolvedFormTypeFactoryInterface $resolvedTypeFactory): static { $this->resolvedTypeFactory = $resolvedTypeFactory; @@ -62,7 +62,7 @@ public function setResolvedTypeFactory(ResolvedFormTypeFactoryInterface $resolve /** * {@inheritdoc} */ - public function addExtension(FormExtensionInterface $extension) + public function addExtension(FormExtensionInterface $extension): static { $this->extensions[] = $extension; @@ -72,7 +72,7 @@ public function addExtension(FormExtensionInterface $extension) /** * {@inheritdoc} */ - public function addExtensions(array $extensions) + public function addExtensions(array $extensions): static { $this->extensions = array_merge($this->extensions, $extensions); @@ -82,7 +82,7 @@ public function addExtensions(array $extensions) /** * {@inheritdoc} */ - public function addType(FormTypeInterface $type) + public function addType(FormTypeInterface $type): static { $this->types[] = $type; @@ -92,7 +92,7 @@ public function addType(FormTypeInterface $type) /** * {@inheritdoc} */ - public function addTypes(array $types) + public function addTypes(array $types): static { foreach ($types as $type) { $this->types[] = $type; @@ -104,7 +104,7 @@ public function addTypes(array $types) /** * {@inheritdoc} */ - public function addTypeExtension(FormTypeExtensionInterface $typeExtension) + public function addTypeExtension(FormTypeExtensionInterface $typeExtension): static { foreach ($typeExtension::getExtendedTypes() as $extendedType) { $this->typeExtensions[$extendedType][] = $typeExtension; @@ -116,7 +116,7 @@ public function addTypeExtension(FormTypeExtensionInterface $typeExtension) /** * {@inheritdoc} */ - public function addTypeExtensions(array $typeExtensions) + public function addTypeExtensions(array $typeExtensions): static { foreach ($typeExtensions as $typeExtension) { $this->addTypeExtension($typeExtension); @@ -128,7 +128,7 @@ public function addTypeExtensions(array $typeExtensions) /** * {@inheritdoc} */ - public function addTypeGuesser(FormTypeGuesserInterface $typeGuesser) + public function addTypeGuesser(FormTypeGuesserInterface $typeGuesser): static { $this->typeGuessers[] = $typeGuesser; @@ -138,7 +138,7 @@ public function addTypeGuesser(FormTypeGuesserInterface $typeGuesser) /** * {@inheritdoc} */ - public function addTypeGuessers(array $typeGuessers) + public function addTypeGuessers(array $typeGuessers): static { $this->typeGuessers = array_merge($this->typeGuessers, $typeGuessers); @@ -148,7 +148,7 @@ public function addTypeGuessers(array $typeGuessers) /** * {@inheritdoc} */ - public function getFormFactory() + public function getFormFactory(): FormFactoryInterface { $extensions = $this->extensions; diff --git a/FormFactoryBuilderInterface.php b/FormFactoryBuilderInterface.php index 35cdc44d9d..adf2a3bec9 100644 --- a/FormFactoryBuilderInterface.php +++ b/FormFactoryBuilderInterface.php @@ -23,14 +23,14 @@ interface FormFactoryBuilderInterface * * @return $this */ - public function setResolvedTypeFactory(ResolvedFormTypeFactoryInterface $resolvedTypeFactory); + public function setResolvedTypeFactory(ResolvedFormTypeFactoryInterface $resolvedTypeFactory): static; /** * Adds an extension to be loaded by the factory. * * @return $this */ - public function addExtension(FormExtensionInterface $extension); + public function addExtension(FormExtensionInterface $extension): static; /** * Adds a list of extensions to be loaded by the factory. @@ -39,14 +39,14 @@ public function addExtension(FormExtensionInterface $extension); * * @return $this */ - public function addExtensions(array $extensions); + public function addExtensions(array $extensions): static; /** * Adds a form type to the factory. * * @return $this */ - public function addType(FormTypeInterface $type); + public function addType(FormTypeInterface $type): static; /** * Adds a list of form types to the factory. @@ -55,14 +55,14 @@ public function addType(FormTypeInterface $type); * * @return $this */ - public function addTypes(array $types); + public function addTypes(array $types): static; /** * Adds a form type extension to the factory. * * @return $this */ - public function addTypeExtension(FormTypeExtensionInterface $typeExtension); + public function addTypeExtension(FormTypeExtensionInterface $typeExtension): static; /** * Adds a list of form type extensions to the factory. @@ -71,14 +71,14 @@ public function addTypeExtension(FormTypeExtensionInterface $typeExtension); * * @return $this */ - public function addTypeExtensions(array $typeExtensions); + public function addTypeExtensions(array $typeExtensions): static; /** * Adds a type guesser to the factory. * * @return $this */ - public function addTypeGuesser(FormTypeGuesserInterface $typeGuesser); + public function addTypeGuesser(FormTypeGuesserInterface $typeGuesser): static; /** * Adds a list of type guessers to the factory. @@ -87,12 +87,12 @@ public function addTypeGuesser(FormTypeGuesserInterface $typeGuesser); * * @return $this */ - public function addTypeGuessers(array $typeGuessers); + public function addTypeGuessers(array $typeGuessers): static; /** * Builds and returns the factory. * * @return FormFactoryInterface The form factory */ - public function getFormFactory(); + public function getFormFactory(): FormFactoryInterface; } diff --git a/FormFactoryInterface.php b/FormFactoryInterface.php index d91c3845fb..84d55fdefd 100644 --- a/FormFactoryInterface.php +++ b/FormFactoryInterface.php @@ -32,7 +32,7 @@ interface FormFactoryInterface * * @throws InvalidOptionsException if any given option is not applicable to the given type */ - public function create(string $type = FormType::class, mixed $data = null, array $options = []); + public function create(string $type = FormType::class, mixed $data = null, array $options = []): FormInterface; /** * Returns a form. @@ -45,7 +45,7 @@ public function create(string $type = FormType::class, mixed $data = null, array * * @throws InvalidOptionsException if any given option is not applicable to the given type */ - public function createNamed(string $name, string $type = FormType::class, mixed $data = null, array $options = []); + public function createNamed(string $name, string $type = FormType::class, mixed $data = null, array $options = []): FormInterface; /** * Returns a form for a property of a class. @@ -60,7 +60,7 @@ public function createNamed(string $name, string $type = FormType::class, mixed * * @throws InvalidOptionsException if any given option is not applicable to the form type */ - public function createForProperty(string $class, string $property, mixed $data = null, array $options = []); + public function createForProperty(string $class, string $property, mixed $data = null, array $options = []): FormInterface; /** * Returns a form builder. @@ -71,7 +71,7 @@ public function createForProperty(string $class, string $property, mixed $data = * * @throws InvalidOptionsException if any given option is not applicable to the given type */ - public function createBuilder(string $type = FormType::class, mixed $data = null, array $options = []); + public function createBuilder(string $type = FormType::class, mixed $data = null, array $options = []): FormBuilderInterface; /** * Returns a form builder. @@ -82,7 +82,7 @@ public function createBuilder(string $type = FormType::class, mixed $data = null * * @throws InvalidOptionsException if any given option is not applicable to the given type */ - public function createNamedBuilder(string $name, string $type = FormType::class, mixed $data = null, array $options = []); + public function createNamedBuilder(string $name, string $type = FormType::class, mixed $data = null, array $options = []): FormBuilderInterface; /** * Returns a form builder for a property of a class. @@ -98,5 +98,5 @@ public function createNamedBuilder(string $name, string $type = FormType::class, * * @throws InvalidOptionsException if any given option is not applicable to the form type */ - public function createBuilderForProperty(string $class, string $property, mixed $data = null, array $options = []); + public function createBuilderForProperty(string $class, string $property, mixed $data = null, array $options = []): FormBuilderInterface; } diff --git a/FormInterface.php b/FormInterface.php index d3b8073f01..11f1d58834 100644 --- a/FormInterface.php +++ b/FormInterface.php @@ -31,14 +31,14 @@ interface FormInterface extends \ArrayAccess, \Traversable, \Countable * @throws Exception\LogicException when trying to set a parent for a form with * an empty name */ - public function setParent(self $parent = null); + public function setParent(self $parent = null): static; /** * Returns the parent form. * * @return self|null The parent form or null if there is none */ - public function getParent(); + public function getParent(): ?self; /** * Adds or replaces a child to the form. @@ -53,7 +53,7 @@ public function getParent(); * @throws Exception\LogicException when trying to add a child to a non-compound form * @throws Exception\UnexpectedTypeException if $child or $type has an unexpected type */ - public function add(FormInterface|string $child, string $type = null, array $options = []); + public function add(self|string $child, string $type = null, array $options = []): static; /** * Returns the child with the given name. @@ -62,14 +62,12 @@ public function add(FormInterface|string $child, string $type = null, array $opt * * @throws Exception\OutOfBoundsException if the named child does not exist */ - public function get(string $name); + public function get(string $name): self; /** * Returns whether a child with the given name exists. - * - * @return bool */ - public function has(string $name); + public function has(string $name): bool; /** * Removes a child from the form. @@ -78,14 +76,14 @@ public function has(string $name); * * @throws Exception\AlreadySubmittedException if the form has already been submitted */ - public function remove(string $name); + public function remove(string $name): static; /** * Returns all children in this group. * * @return self[] */ - public function all(); + public function all(): array; /** * Returns the errors of this form. @@ -97,7 +95,7 @@ public function all(); * @return FormErrorIterator An iterator over the {@link FormError} * instances that where added to this form */ - public function getErrors(bool $deep = false, bool $flatten = true); + public function getErrors(bool $deep = false, bool $flatten = true): FormErrorIterator; /** * Updates the form with default model data. @@ -113,7 +111,7 @@ public function getErrors(bool $deep = false, bool $flatten = true); * the form inherits data from its parent * @throws Exception\TransformationFailedException if the synchronization failed */ - public function setData(mixed $modelData); + public function setData(mixed $modelData): static; /** * Returns the model data in the format needed for the underlying object. @@ -124,7 +122,7 @@ public function setData(mixed $modelData); * * @throws Exception\RuntimeException If the form inherits data but has no parent */ - public function getData(); + public function getData(): mixed; /** * Returns the normalized data of the field, used as internal bridge @@ -137,7 +135,7 @@ public function getData(); * * @throws Exception\RuntimeException If the form inherits data but has no parent */ - public function getNormData(); + public function getNormData(): mixed; /** * Returns the view data of the field. @@ -156,32 +154,28 @@ public function getNormData(); * * In both cases the view data is the actual altered data on submission. * - * @return mixed - * * @throws Exception\RuntimeException If the form inherits data but has no parent */ - public function getViewData(); + public function getViewData(): mixed; /** * Returns the extra submitted data. * * @return array The submitted data which do not belong to a child */ - public function getExtraData(); + public function getExtraData(): array; /** * Returns the form's configuration. - * - * @return FormConfigInterface */ - public function getConfig(); + public function getConfig(): FormConfigInterface; /** * Returns whether the form is submitted. * * @return bool true if the form is submitted, false otherwise */ - public function isSubmitted(); + public function isSubmitted(): bool; /** * Returns the name by which the form is identified in forms. @@ -190,30 +184,26 @@ public function isSubmitted(); * * @return string The name of the form */ - public function getName(); + public function getName(): string; /** * Returns the property path that the form is mapped to. - * - * @return PropertyPathInterface|null */ - public function getPropertyPath(); + public function getPropertyPath(): ?PropertyPathInterface; /** * Adds an error to this form. * * @return $this */ - public function addError(FormError $error); + public function addError(FormError $error): static; /** * Returns whether the form and all children are valid. * * @throws Exception\LogicException if the form is not submitted - * - * @return bool */ - public function isValid(); + public function isValid(): bool; /** * Returns whether the form is required to be filled out. @@ -221,10 +211,8 @@ public function isValid(); * If the form has a parent and the parent is not required, this method * will always return false. Otherwise the value set with setRequired() * is returned. - * - * @return bool */ - public function isRequired(); + public function isRequired(): bool; /** * Returns whether this form is disabled. @@ -234,17 +222,13 @@ public function isRequired(); * * Forms whose parents are disabled are considered disabled regardless of * their own state. - * - * @return bool */ - public function isDisabled(); + public function isDisabled(): bool; /** * Returns whether the form is empty. - * - * @return bool */ - public function isEmpty(); + public function isEmpty(): bool; /** * Returns whether the data in the different formats is synchronized. @@ -253,17 +237,15 @@ public function isEmpty(); * by calling {@link getTransformationFailure()}. * * If the form is not submitted, this method always returns true. - * - * @return bool */ - public function isSynchronized(); + public function isSynchronized(): bool; /** * Returns the data transformation failure, if any, during submission. * * @return Exception\TransformationFailedException|null The transformation failure or null */ - public function getTransformationFailure(); + public function getTransformationFailure(): ?Exception\TransformationFailedException; /** * Initializes the form tree. @@ -274,7 +256,7 @@ public function getTransformationFailure(); * * @throws Exception\RuntimeException If the form is not the root */ - public function initialize(); + public function initialize(): static; /** * Inspects the given request and calls {@link submit()} if the form was @@ -286,7 +268,7 @@ public function initialize(); * * @return $this */ - public function handleRequest(mixed $request = null); + public function handleRequest(mixed $request = null): static; /** * Submits data to the form. @@ -301,24 +283,22 @@ public function handleRequest(mixed $request = null); * * @throws Exception\AlreadySubmittedException if the form has already been submitted */ - public function submit(string|array|null $submittedData, bool $clearMissing = true); + public function submit(string|array|null $submittedData, bool $clearMissing = true): static; /** * Returns the root of the form tree. * * @return self */ - public function getRoot(); + public function getRoot(): self; /** * Returns whether the field is the root of the form tree. - * - * @return bool */ - public function isRoot(); + public function isRoot(): bool; /** * @return FormView The view */ - public function createView(FormView $parent = null); + public function createView(FormView $parent = null): FormView; } diff --git a/FormRegistry.php b/FormRegistry.php index 8461bbafe4..d7c35796d1 100644 --- a/FormRegistry.php +++ b/FormRegistry.php @@ -57,7 +57,7 @@ public function __construct(array $extensions, ResolvedFormTypeFactoryInterface /** * {@inheritdoc} */ - public function getType(string $name) + public function getType(string $name): ResolvedFormTypeInterface { if (!isset($this->types[$name])) { $type = null; @@ -124,7 +124,7 @@ private function resolveType(FormTypeInterface $type): ResolvedFormTypeInterface /** * {@inheritdoc} */ - public function hasType(string $name) + public function hasType(string $name): bool { if (isset($this->types[$name])) { return true; @@ -142,7 +142,7 @@ public function hasType(string $name) /** * {@inheritdoc} */ - public function getTypeGuesser() + public function getTypeGuesser(): ?FormTypeGuesserInterface { if (false === $this->guesser) { $guessers = []; @@ -164,7 +164,7 @@ public function getTypeGuesser() /** * {@inheritdoc} */ - public function getExtensions() + public function getExtensions(): array { return $this->extensions; } diff --git a/FormRegistryInterface.php b/FormRegistryInterface.php index fd8ed0b172..6dfa5fcffe 100644 --- a/FormRegistryInterface.php +++ b/FormRegistryInterface.php @@ -27,26 +27,24 @@ interface FormRegistryInterface * * @throws Exception\InvalidArgumentException if the type can not be retrieved from any extension */ - public function getType(string $name); + public function getType(string $name): ResolvedFormTypeInterface; /** * Returns whether the given form type is supported. * * @return bool Whether the type is supported */ - public function hasType(string $name); + public function hasType(string $name): bool; /** * Returns the guesser responsible for guessing types. - * - * @return FormTypeGuesserInterface|null */ - public function getTypeGuesser(); + public function getTypeGuesser(): ?FormTypeGuesserInterface; /** * Returns the extensions loaded by the framework. * * @return FormExtensionInterface[] */ - public function getExtensions(); + public function getExtensions(): array; } diff --git a/FormRenderer.php b/FormRenderer.php index 41f78c91e6..ab8ff1aa3b 100644 --- a/FormRenderer.php +++ b/FormRenderer.php @@ -40,7 +40,7 @@ public function __construct(FormRendererEngineInterface $engine, CsrfTokenManage /** * {@inheritdoc} */ - public function getEngine() + public function getEngine(): FormRendererEngineInterface { return $this->engine; } @@ -56,7 +56,7 @@ public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = /** * {@inheritdoc} */ - public function renderCsrfToken(string $tokenId) + public function renderCsrfToken(string $tokenId): string { if (null === $this->csrfTokenManager) { throw new BadMethodCallException('CSRF tokens can only be generated if a CsrfTokenManagerInterface is injected in FormRenderer::__construct(). Try running "composer require symfony/security-csrf".'); @@ -68,7 +68,7 @@ public function renderCsrfToken(string $tokenId) /** * {@inheritdoc} */ - public function renderBlock(FormView $view, string $blockName, array $variables = []) + public function renderBlock(FormView $view, string $blockName, array $variables = []): string { $resource = $this->engine->getResourceForBlockName($view, $blockName); @@ -127,7 +127,7 @@ public function renderBlock(FormView $view, string $blockName, array $variables /** * {@inheritdoc} */ - public function searchAndRenderBlock(FormView $view, string $blockNameSuffix, array $variables = []) + public function searchAndRenderBlock(FormView $view, string $blockNameSuffix, array $variables = []): string { $renderOnlyOnce = 'row' === $blockNameSuffix || 'widget' === $blockNameSuffix; @@ -280,7 +280,7 @@ public function searchAndRenderBlock(FormView $view, string $blockNameSuffix, ar /** * {@inheritdoc} */ - public function humanize(string $text) + public function humanize(string $text): string { return ucfirst(strtolower(trim(preg_replace(['/([A-Z])/', '/[_\s]+/'], ['_$1', ' '], $text)))); } diff --git a/FormRendererEngineInterface.php b/FormRendererEngineInterface.php index 9009ba39b2..0cb76a1568 100644 --- a/FormRendererEngineInterface.php +++ b/FormRendererEngineInterface.php @@ -43,7 +43,7 @@ public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = * * @return mixed the renderer resource or false, if none was found */ - public function getResourceForBlockName(FormView $view, string $blockName); + public function getResourceForBlockName(FormView $view, string $blockName): mixed; /** * Returns the resource for a block hierarchy. @@ -79,7 +79,7 @@ public function getResourceForBlockName(FormView $view, string $blockName); * * @return mixed The renderer resource or false, if none was found */ - public function getResourceForBlockNameHierarchy(FormView $view, array $blockNameHierarchy, int $hierarchyLevel); + public function getResourceForBlockNameHierarchy(FormView $view, array $blockNameHierarchy, int $hierarchyLevel): mixed; /** * Returns the hierarchy level at which a resource can be found. @@ -117,7 +117,7 @@ public function getResourceForBlockNameHierarchy(FormView $view, array $blockNam * * @return int|bool The hierarchy level or false, if no resource was found */ - public function getResourceHierarchyLevel(FormView $view, array $blockNameHierarchy, int $hierarchyLevel); + public function getResourceHierarchyLevel(FormView $view, array $blockNameHierarchy, int $hierarchyLevel): int|bool; /** * Renders a block in the given renderer resource. diff --git a/FormRendererInterface.php b/FormRendererInterface.php index 0d0ad72674..9ef80b075e 100644 --- a/FormRendererInterface.php +++ b/FormRendererInterface.php @@ -23,7 +23,7 @@ interface FormRendererInterface * * @return FormRendererEngineInterface The renderer engine */ - public function getEngine(); + public function getEngine(): FormRendererEngineInterface; /** * Sets the theme(s) to be used for rendering a view and its children. @@ -44,7 +44,7 @@ public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = * * @return string The HTML markup */ - public function renderBlock(FormView $view, string $blockName, array $variables = []); + public function renderBlock(FormView $view, string $blockName, array $variables = []): string; /** * Searches and renders a block for a given name suffix. @@ -61,7 +61,7 @@ public function renderBlock(FormView $view, string $blockName, array $variables * * @return string The HTML markup */ - public function searchAndRenderBlock(FormView $view, string $blockNameSuffix, array $variables = []); + public function searchAndRenderBlock(FormView $view, string $blockNameSuffix, array $variables = []): string; /** * Renders a CSRF token. @@ -80,7 +80,7 @@ public function searchAndRenderBlock(FormView $view, string $blockNameSuffix, ar * * @return string A CSRF token */ - public function renderCsrfToken(string $tokenId); + public function renderCsrfToken(string $tokenId): string; /** * Makes a technical name human readable. @@ -91,5 +91,5 @@ public function renderCsrfToken(string $tokenId); * * @return string The humanized text */ - public function humanize(string $text); + public function humanize(string $text): string; } diff --git a/FormTypeGuesserChain.php b/FormTypeGuesserChain.php index 4d1923c3c6..edce99559f 100644 --- a/FormTypeGuesserChain.php +++ b/FormTypeGuesserChain.php @@ -13,6 +13,8 @@ use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Guess\Guess; +use Symfony\Component\Form\Guess\TypeGuess; +use Symfony\Component\Form\Guess\ValueGuess; class FormTypeGuesserChain implements FormTypeGuesserInterface { @@ -41,7 +43,7 @@ public function __construct(iterable $guessers) /** * {@inheritdoc} */ - public function guessType(string $class, string $property) + public function guessType(string $class, string $property): ?TypeGuess { return $this->guess(function ($guesser) use ($class, $property) { return $guesser->guessType($class, $property); @@ -51,7 +53,7 @@ public function guessType(string $class, string $property) /** * {@inheritdoc} */ - public function guessRequired(string $class, string $property) + public function guessRequired(string $class, string $property): ?ValueGuess { return $this->guess(function ($guesser) use ($class, $property) { return $guesser->guessRequired($class, $property); @@ -61,7 +63,7 @@ public function guessRequired(string $class, string $property) /** * {@inheritdoc} */ - public function guessMaxLength(string $class, string $property) + public function guessMaxLength(string $class, string $property): ?ValueGuess { return $this->guess(function ($guesser) use ($class, $property) { return $guesser->guessMaxLength($class, $property); @@ -71,7 +73,7 @@ public function guessMaxLength(string $class, string $property) /** * {@inheritdoc} */ - public function guessPattern(string $class, string $property) + public function guessPattern(string $class, string $property): ?ValueGuess { return $this->guess(function ($guesser) use ($class, $property) { return $guesser->guessPattern($class, $property); diff --git a/FormView.php b/FormView.php index 651d64af38..27f061fe30 100644 --- a/FormView.php +++ b/FormView.php @@ -59,7 +59,7 @@ public function __construct(self $parent = null) * * @return bool Whether this view's widget is rendered */ - public function isRendered() + public function isRendered(): bool { if (true === $this->rendered || 0 === \count($this->children)) { return $this->rendered; @@ -79,17 +79,14 @@ public function isRendered() * * @return $this */ - public function setRendered() + public function setRendered(): static { $this->rendered = true; return $this; } - /** - * @return bool - */ - public function isMethodRendered() + public function isMethodRendered(): bool { return $this->methodRendered; } diff --git a/Guess/Guess.php b/Guess/Guess.php index 57f1f63222..abe09cb39f 100644 --- a/Guess/Guess.php +++ b/Guess/Guess.php @@ -59,10 +59,8 @@ abstract class Guess * returned guess is any of them. * * @param static[] $guesses An array of guesses - * - * @return static|null */ - public static function getBestGuess(array $guesses) + public static function getBestGuess(array $guesses): ?static { $result = null; $maxConfidence = -1; @@ -96,7 +94,7 @@ public function __construct(int $confidence) * @return int One of the constants VERY_HIGH_CONFIDENCE, HIGH_CONFIDENCE, * MEDIUM_CONFIDENCE and LOW_CONFIDENCE */ - public function getConfidence() + public function getConfidence(): int { return $this->confidence; } diff --git a/Guess/TypeGuess.php b/Guess/TypeGuess.php index 9d82e83ce2..8ede78eb8c 100644 --- a/Guess/TypeGuess.php +++ b/Guess/TypeGuess.php @@ -39,20 +39,16 @@ public function __construct(string $type, array $options, int $confidence) /** * Returns the guessed field type. - * - * @return string */ - public function getType() + public function getType(): string { return $this->type; } /** * Returns the guessed options for creating instances of the guessed type. - * - * @return array */ - public function getOptions() + public function getOptions(): array { return $this->options; } diff --git a/Guess/ValueGuess.php b/Guess/ValueGuess.php index 2b01e389bc..ddc8b53dd5 100644 --- a/Guess/ValueGuess.php +++ b/Guess/ValueGuess.php @@ -35,7 +35,7 @@ public function __construct(string|int|bool|null $value, int $confidence) * * @return string|int|bool|null */ - public function getValue() + public function getValue(): string|int|bool|null { return $this->value; } diff --git a/NativeRequestHandler.php b/NativeRequestHandler.php index 95318d49c4..272239e65b 100644 --- a/NativeRequestHandler.php +++ b/NativeRequestHandler.php @@ -127,7 +127,7 @@ public function handleRequest(FormInterface $form, mixed $request = null) /** * {@inheritdoc} */ - public function isFileUpload(mixed $data) + public function isFileUpload(mixed $data): bool { // POST data will always be strings or arrays of strings. Thus, we can be sure // that the submitted data is a file upload if the "error" value is an integer @@ -135,10 +135,7 @@ public function isFileUpload(mixed $data) return \is_array($data) && isset($data['error']) && \is_int($data['error']); } - /** - * @return int|null - */ - public function getUploadFileError(mixed $data) + public function getUploadFileError(mixed $data): ?int { if (!\is_array($data)) { return null; diff --git a/PreloadedExtension.php b/PreloadedExtension.php index 7c97cf89d1..cfed38f4f0 100644 --- a/PreloadedExtension.php +++ b/PreloadedExtension.php @@ -43,7 +43,7 @@ public function __construct(array $types, array $typeExtensions, FormTypeGuesser /** * {@inheritdoc} */ - public function getType(string $name) + public function getType(string $name): FormTypeInterface { if (!isset($this->types[$name])) { throw new InvalidArgumentException(sprintf('The type "%s" can not be loaded by this extension.', $name)); @@ -55,7 +55,7 @@ public function getType(string $name) /** * {@inheritdoc} */ - public function hasType(string $name) + public function hasType(string $name): bool { return isset($this->types[$name]); } @@ -63,7 +63,7 @@ public function hasType(string $name) /** * {@inheritdoc} */ - public function getTypeExtensions(string $name) + public function getTypeExtensions(string $name): array { return $this->typeExtensions[$name] ?? []; @@ -72,7 +72,7 @@ public function getTypeExtensions(string $name) /** * {@inheritdoc} */ - public function hasTypeExtensions(string $name) + public function hasTypeExtensions(string $name): bool { return !empty($this->typeExtensions[$name]); } @@ -80,7 +80,7 @@ public function hasTypeExtensions(string $name) /** * {@inheritdoc} */ - public function getTypeGuesser() + public function getTypeGuesser(): ?FormTypeGuesserInterface { return $this->typeGuesser; } diff --git a/RequestHandlerInterface.php b/RequestHandlerInterface.php index 2cb671df71..8eb8f1a688 100644 --- a/RequestHandlerInterface.php +++ b/RequestHandlerInterface.php @@ -25,8 +25,6 @@ public function handleRequest(FormInterface $form, mixed $request = null); /** * Returns true if the given data is a file upload. - * - * @return bool */ - public function isFileUpload(mixed $data); + public function isFileUpload(mixed $data): bool; } diff --git a/ResolvedFormType.php b/ResolvedFormType.php index 657a4014dd..37a5bf45be 100644 --- a/ResolvedFormType.php +++ b/ResolvedFormType.php @@ -32,9 +32,6 @@ class ResolvedFormType implements ResolvedFormTypeInterface private ?ResolvedFormTypeInterface $parent; - /** - * @var OptionsResolver - */ private OptionsResolver $optionsResolver; /** @@ -56,7 +53,7 @@ public function __construct(FormTypeInterface $innerType, array $typeExtensions /** * {@inheritdoc} */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return $this->innerType->getBlockPrefix(); } @@ -64,7 +61,7 @@ public function getBlockPrefix() /** * {@inheritdoc} */ - public function getParent() + public function getParent(): ?ResolvedFormTypeInterface { return $this->parent; } @@ -72,7 +69,7 @@ public function getParent() /** * {@inheritdoc} */ - public function getInnerType() + public function getInnerType(): FormTypeInterface { return $this->innerType; } @@ -80,7 +77,7 @@ public function getInnerType() /** * {@inheritdoc} */ - public function getTypeExtensions() + public function getTypeExtensions(): array { return $this->typeExtensions; } @@ -88,7 +85,7 @@ public function getTypeExtensions() /** * {@inheritdoc} */ - public function createBuilder(FormFactoryInterface $factory, string $name, array $options = []) + public function createBuilder(FormFactoryInterface $factory, string $name, array $options = []): FormBuilderInterface { try { $options = $this->getOptionsResolver()->resolve($options); @@ -108,7 +105,7 @@ public function createBuilder(FormFactoryInterface $factory, string $name, array /** * {@inheritdoc} */ - public function createView(FormInterface $form, FormView $parent = null) + public function createView(FormInterface $form, FormView $parent = null): FormView { return $this->newView($parent); } @@ -165,7 +162,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) /** * {@inheritdoc} */ - public function getOptionsResolver() + public function getOptionsResolver(): OptionsResolver { if (!isset($this->optionsResolver)) { if (null !== $this->parent) { @@ -188,10 +185,8 @@ public function getOptionsResolver() * Creates a new builder instance. * * Override this method if you want to customize the builder class. - * - * @return FormBuilderInterface */ - protected function newBuilder(string $name, ?string $dataClass, FormFactoryInterface $factory, array $options) + protected function newBuilder(string $name, ?string $dataClass, FormFactoryInterface $factory, array $options): FormBuilderInterface { if ($this->innerType instanceof ButtonTypeInterface) { return new ButtonBuilder($name, $options); @@ -208,10 +203,8 @@ protected function newBuilder(string $name, ?string $dataClass, FormFactoryInter * Creates a new view instance. * * Override this method if you want to customize the view class. - * - * @return FormView */ - protected function newView(FormView $parent = null) + protected function newView(FormView $parent = null): FormView { return new FormView($parent); } diff --git a/ResolvedFormTypeFactory.php b/ResolvedFormTypeFactory.php index d93d1c06df..48f62bad32 100644 --- a/ResolvedFormTypeFactory.php +++ b/ResolvedFormTypeFactory.php @@ -19,7 +19,7 @@ class ResolvedFormTypeFactory implements ResolvedFormTypeFactoryInterface /** * {@inheritdoc} */ - public function createResolvedType(FormTypeInterface $type, array $typeExtensions, ResolvedFormTypeInterface $parent = null) + public function createResolvedType(FormTypeInterface $type, array $typeExtensions, ResolvedFormTypeInterface $parent = null): ResolvedFormTypeInterface { return new ResolvedFormType($type, $typeExtensions, $parent); } diff --git a/ResolvedFormTypeFactoryInterface.php b/ResolvedFormTypeFactoryInterface.php index 9b20b44027..6f5ef35e5e 100644 --- a/ResolvedFormTypeFactoryInterface.php +++ b/ResolvedFormTypeFactoryInterface.php @@ -27,10 +27,8 @@ interface ResolvedFormTypeFactoryInterface * * @param FormTypeExtensionInterface[] $typeExtensions * - * @return ResolvedFormTypeInterface - * * @throws Exception\UnexpectedTypeException if the types parent {@link FormTypeInterface::getParent()} is not a string * @throws Exception\InvalidArgumentException if the types parent can not be retrieved from any extension */ - public function createResolvedType(FormTypeInterface $type, array $typeExtensions, ResolvedFormTypeInterface $parent = null); + public function createResolvedType(FormTypeInterface $type, array $typeExtensions, ResolvedFormTypeInterface $parent = null): ResolvedFormTypeInterface; } diff --git a/ResolvedFormTypeInterface.php b/ResolvedFormTypeInterface.php index 42e958d2b2..f684548d66 100644 --- a/ResolvedFormTypeInterface.php +++ b/ResolvedFormTypeInterface.php @@ -25,28 +25,28 @@ interface ResolvedFormTypeInterface * * @return string The prefix of the template block name */ - public function getBlockPrefix(); + public function getBlockPrefix(): string; /** * Returns the parent type. * * @return self|null The parent type or null */ - public function getParent(); + public function getParent(): ?self; /** * Returns the wrapped form type. * * @return FormTypeInterface The wrapped form type */ - public function getInnerType(); + public function getInnerType(): FormTypeInterface; /** * Returns the extensions of the wrapped form type. * * @return FormTypeExtensionInterface[] */ - public function getTypeExtensions(); + public function getTypeExtensions(): array; /** * Creates a new form builder for this type. @@ -55,14 +55,14 @@ public function getTypeExtensions(); * * @return FormBuilderInterface The created form builder */ - public function createBuilder(FormFactoryInterface $factory, string $name, array $options = []); + public function createBuilder(FormFactoryInterface $factory, string $name, array $options = []): FormBuilderInterface; /** * Creates a new form view for a form of this type. * * @return FormView The created form view */ - public function createView(FormInterface $form, FormView $parent = null); + public function createView(FormInterface $form, FormView $parent = null): FormView; /** * Configures a form builder for the type hierarchy. @@ -88,5 +88,5 @@ public function finishView(FormView $view, FormInterface $form, array $options); * * @return OptionsResolver The options resolver */ - public function getOptionsResolver(); + public function getOptionsResolver(): OptionsResolver; } diff --git a/ReversedTransformer.php b/ReversedTransformer.php index 0591c4f3b0..d2a835ba90 100644 --- a/ReversedTransformer.php +++ b/ReversedTransformer.php @@ -31,7 +31,7 @@ public function __construct(DataTransformerInterface $reversedTransformer) /** * {@inheritdoc} */ - public function transform(mixed $value) + public function transform(mixed $value): mixed { return $this->reversedTransformer->reverseTransform($value); } @@ -39,7 +39,7 @@ public function transform(mixed $value) /** * {@inheritdoc} */ - public function reverseTransform(mixed $value) + public function reverseTransform(mixed $value): mixed { return $this->reversedTransformer->transform($value); } diff --git a/SubmitButton.php b/SubmitButton.php index e47eee8a85..bc7e1c3f7f 100644 --- a/SubmitButton.php +++ b/SubmitButton.php @@ -23,7 +23,7 @@ class SubmitButton extends Button implements ClickableInterface /** * {@inheritdoc} */ - public function isClicked() + public function isClicked(): bool { return $this->clicked; } @@ -35,7 +35,7 @@ public function isClicked() * * @throws Exception\AlreadySubmittedException if the form has already been submitted */ - public function submit(array|string|null $submittedData, bool $clearMissing = true) + public function submit(array|string|null $submittedData, bool $clearMissing = true): static { if ($this->getConfig()->getDisabled()) { $this->clicked = false; diff --git a/SubmitButtonBuilder.php b/SubmitButtonBuilder.php index 931f399daf..4a26dde50a 100644 --- a/SubmitButtonBuilder.php +++ b/SubmitButtonBuilder.php @@ -23,7 +23,7 @@ class SubmitButtonBuilder extends ButtonBuilder * * @return SubmitButton The button */ - public function getForm() + public function getForm(): SubmitButton { return new SubmitButton($this->getFormConfig()); } diff --git a/Test/FormPerformanceTestCase.php b/Test/FormPerformanceTestCase.php index 732f9ec3dd..2547e871cc 100644 --- a/Test/FormPerformanceTestCase.php +++ b/Test/FormPerformanceTestCase.php @@ -56,10 +56,7 @@ public function setMaxRunningTime(int $maxRunningTime) $this->maxRunningTime = $maxRunningTime; } - /** - * @return int - */ - public function getMaxRunningTime() + public function getMaxRunningTime(): int { return $this->maxRunningTime; } diff --git a/Tests/FormBuilderTest.php b/Tests/FormBuilderTest.php index c937f01954..e68d3c7b1a 100644 --- a/Tests/FormBuilderTest.php +++ b/Tests/FormBuilderTest.php @@ -15,7 +15,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\ButtonBuilder; use Symfony\Component\Form\Exception\InvalidArgumentException; -use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Form; use Symfony\Component\Form\FormBuilder; diff --git a/Util/FormUtil.php b/Util/FormUtil.php index 9dbbfc7bc7..cc86cf7872 100644 --- a/Util/FormUtil.php +++ b/Util/FormUtil.php @@ -29,10 +29,8 @@ private function __construct() * This logic is reused multiple times throughout the processing of * a form and needs to be consistent. PHP keyword `empty` cannot * be used as it also considers 0 and "0" to be empty. - * - * @return bool */ - public static function isEmpty(mixed $data) + public static function isEmpty(mixed $data): bool { // Should not do a check for [] === $data!!! // This method is used in occurrences where arrays are diff --git a/Util/OptionsResolverWrapper.php b/Util/OptionsResolverWrapper.php index b983018fe9..9819074eed 100644 --- a/Util/OptionsResolverWrapper.php +++ b/Util/OptionsResolverWrapper.php @@ -27,7 +27,7 @@ class OptionsResolverWrapper extends OptionsResolver /** * @return $this */ - public function setNormalizer(string $option, \Closure $normalizer): self + public function setNormalizer(string $option, \Closure $normalizer): static { try { parent::setNormalizer($option, $normalizer); @@ -41,7 +41,7 @@ public function setNormalizer(string $option, \Closure $normalizer): self /** * @return $this */ - public function setAllowedValues(string $option, mixed $allowedValues): self + public function setAllowedValues(string $option, mixed $allowedValues): static { try { parent::setAllowedValues($option, $allowedValues); @@ -55,7 +55,7 @@ public function setAllowedValues(string $option, mixed $allowedValues): self /** * @return $this */ - public function addAllowedValues(string $option, mixed $allowedValues): self + public function addAllowedValues(string $option, mixed $allowedValues): static { try { parent::addAllowedValues($option, $allowedValues); @@ -71,7 +71,7 @@ public function addAllowedValues(string $option, mixed $allowedValues): self * * @return $this */ - public function setAllowedTypes(string $option, $allowedTypes): self + public function setAllowedTypes(string $option, $allowedTypes): static { try { parent::setAllowedTypes($option, $allowedTypes); @@ -87,7 +87,7 @@ public function setAllowedTypes(string $option, $allowedTypes): self * * @return $this */ - public function addAllowedTypes(string $option, $allowedTypes): self + public function addAllowedTypes(string $option, $allowedTypes): static { try { parent::addAllowedTypes($option, $allowedTypes); diff --git a/Util/ServerParams.php b/Util/ServerParams.php index 4076b7c49b..ea8f857ee5 100644 --- a/Util/ServerParams.php +++ b/Util/ServerParams.php @@ -27,10 +27,8 @@ public function __construct(RequestStack $requestStack = null) /** * Returns true if the POST max size has been exceeded in the request. - * - * @return bool */ - public function hasPostMaxSizeBeenExceeded() + public function hasPostMaxSizeBeenExceeded(): bool { $contentLength = $this->getContentLength(); $maxContentLength = $this->getPostMaxSize(); @@ -40,10 +38,8 @@ public function hasPostMaxSizeBeenExceeded() /** * Returns maximum post size in bytes. - * - * @return int|null The maximum post size in bytes */ - public function getPostMaxSize() + public function getPostMaxSize(): int|float|null { $iniMax = strtolower($this->getNormalizedIniPostMaxSize()); @@ -75,10 +71,8 @@ public function getPostMaxSize() /** * Returns the normalized "post_max_size" ini setting. - * - * @return string */ - public function getNormalizedIniPostMaxSize() + public function getNormalizedIniPostMaxSize(): string { return strtoupper(trim(ini_get('post_max_size'))); } @@ -88,7 +82,7 @@ public function getNormalizedIniPostMaxSize() * * @return mixed The request content length */ - public function getContentLength() + public function getContentLength(): mixed { if (null !== $this->requestStack && null !== $request = $this->requestStack->getCurrentRequest()) { return $request->server->get('CONTENT_LENGTH'); diff --git a/Util/StringUtil.php b/Util/StringUtil.php index 851baf0c19..7383253cd2 100644 --- a/Util/StringUtil.php +++ b/Util/StringUtil.php @@ -26,10 +26,8 @@ private function __construct() /** * Returns the trimmed data. - * - * @return string */ - public static function trim(string $string) + public static function trim(string $string): string { if (null !== $result = @preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $string)) { return $result; @@ -45,7 +43,7 @@ public static function trim(string $string) * * @return string|null The block prefix or null if not a valid FQCN */ - public static function fqcnToBlockPrefix(string $fqcn) + public static function fqcnToBlockPrefix(string $fqcn): ?string { // Non-greedy ("+?") to match "type" suffix, if present if (preg_match('~([^\\\\]+?)(type)?$~i', $fqcn, $matches)) { From e3ecbc027786b724c8ea19d4e5b4d40b1056eeff Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 16 Aug 2021 18:31:32 +0200 Subject: [PATCH 023/208] Run php-cs-fixer --- FormInterface.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/FormInterface.php b/FormInterface.php index 11f1d58834..f63ba0cf1d 100644 --- a/FormInterface.php +++ b/FormInterface.php @@ -58,8 +58,6 @@ public function add(self|string $child, string $type = null, array $options = [] /** * Returns the child with the given name. * - * @return self - * * @throws Exception\OutOfBoundsException if the named child does not exist */ public function get(string $name): self; @@ -287,8 +285,6 @@ public function submit(string|array|null $submittedData, bool $clearMissing = tr /** * Returns the root of the form tree. - * - * @return self */ public function getRoot(): self; From 2948707bc5b2fea5854c715ac528ebdfd5fd3c60 Mon Sep 17 00:00:00 2001 From: W0rma Date: Tue, 17 Aug 2021 14:52:50 +0200 Subject: [PATCH 024/208] Throw exception if child element is not iterable --- FormErrorIterator.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/FormErrorIterator.php b/FormErrorIterator.php index a6b9719059..56921e73f2 100644 --- a/FormErrorIterator.php +++ b/FormErrorIterator.php @@ -190,8 +190,7 @@ public function hasChildren(): bool public function getChildren(): self { if (!$this->hasChildren()) { - trigger_deprecation('symfony/form', '5.4', 'Calling "%s()" if the current element is not iterable is deprecated, call "%s" to get the current element.', __METHOD__, self::class.'::current()'); - // throw new LogicException(sprintf('The current element is not iterable. Use "%s" to get the current element.', self::class.'::current()')); + throw new LogicException(sprintf('The current element is not iterable. Use "%s" to get the current element.', self::class.'::current()')); } return current($this->errors); From 2537987d7c97850b8267c859b832309c7d646a4a Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 7 Sep 2021 15:39:06 +0200 Subject: [PATCH 025/208] Remove deprecated code paths --- Extension/Validator/Type/FormTypeValidatorExtension.php | 3 --- .../PercentToLocalizedStringTransformerTest.php | 3 --- Tests/Extension/Core/Type/ChoiceTypeTest.php | 3 --- Tests/Extension/Core/Type/PercentTypeTest.php | 3 --- .../Validator/Type/BirthdayTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/CheckboxTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/ChoiceTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/CollectionTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/ColorTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/CountryTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/CurrencyTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/DateIntervalTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/DateTimeTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/DateTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/EmailTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/FileTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/FormTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/HiddenTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/IntegerTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/LanguageTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/LocaleTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/MoneyTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/NumberTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/PasswordTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/PercentTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/RadioTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/RangeTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/RepeatedTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/SearchTypeValidatorExtensionTest.php | 2 -- .../Extension/Validator/Type/TelTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/TimeTypeValidatorExtensionTest.php | 2 -- .../Validator/Type/TimezoneTypeValidatorExtensionTest.php | 2 -- .../Extension/Validator/Type/UrlTypeValidatorExtensionTest.php | 2 -- 33 files changed, 70 deletions(-) diff --git a/Extension/Validator/Type/FormTypeValidatorExtension.php b/Extension/Validator/Type/FormTypeValidatorExtension.php index cab3a7ae23..50c6ba590f 100644 --- a/Extension/Validator/Type/FormTypeValidatorExtension.php +++ b/Extension/Validator/Type/FormTypeValidatorExtension.php @@ -34,7 +34,6 @@ public function __construct(ValidatorInterface $validator, bool $legacyErrorMess { $this->validator = $validator; $this->violationMapper = new ViolationMapper($formRenderer, $translator); - $this->legacyErrorMessages = $legacyErrorMessages; } /** @@ -62,11 +61,9 @@ public function configureOptions(OptionsResolver $resolver) 'constraints' => [], 'invalid_message' => 'This value is not valid.', 'invalid_message_parameters' => [], - 'legacy_error_messages' => $this->legacyErrorMessages, 'allow_extra_fields' => false, 'extra_fields_message' => 'This form should not contain extra fields.', ]); - $resolver->setAllowedTypes('legacy_error_messages', 'bool'); $resolver->setNormalizer('constraints', $constraintsNormalizer); } diff --git a/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php index 3ee2f43d7c..c3502644bf 100644 --- a/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php @@ -12,15 +12,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\PercentToLocalizedStringTransformer; use Symfony\Component\Intl\Util\IntlTestHelper; class PercentToLocalizedStringTransformerTest extends TestCase { - use ExpectDeprecationTrait; - private $defaultLocale; protected function setUp(): void diff --git a/Tests/Extension/Core/Type/ChoiceTypeTest.php b/Tests/Extension/Core/Type/ChoiceTypeTest.php index bca4a4cd8e..b7d9329849 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -11,7 +11,6 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\ChoiceList\Loader\CallbackChoiceLoader; use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView; use Symfony\Component\Form\ChoiceList\View\ChoiceView; @@ -20,8 +19,6 @@ class ChoiceTypeTest extends BaseTypeTest { - use ExpectDeprecationTrait; - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\ChoiceType'; private $choices = [ diff --git a/Tests/Extension/Core/Type/PercentTypeTest.php b/Tests/Extension/Core/Type/PercentTypeTest.php index a4e3617d54..be92926e0b 100644 --- a/Tests/Extension/Core/Type/PercentTypeTest.php +++ b/Tests/Extension/Core/Type/PercentTypeTest.php @@ -11,15 +11,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\PercentType; use Symfony\Component\Form\Test\TypeTestCase; use Symfony\Component\Intl\Util\IntlTestHelper; class PercentTypeTest extends TypeTestCase { - use ExpectDeprecationTrait; - public const TESTED_TYPE = PercentType::class; private $defaultLocale; diff --git a/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php index 51e10719d3..8beaaf6e58 100644 --- a/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\BirthdayType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class BirthdayTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php index 89b26d5644..6617389a1c 100644 --- a/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class CheckboxTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php index 432e7072fc..e8c3c94bf8 100644 --- a/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class ChoiceTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php index 1985a925e7..34105251c3 100644 --- a/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class CollectionTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php index 059e39eefd..51567835c1 100644 --- a/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\ColorType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class ColorTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php index cd95fb04df..1470b49c6c 100644 --- a/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\CountryType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class CountryTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php index 57d68b6c14..b340de93a1 100644 --- a/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\CurrencyType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class CurrencyTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php index be2d5f3d96..634af5696a 100644 --- a/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\DateIntervalType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class DateIntervalTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php index 013b964e25..973e86d66d 100644 --- a/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\DateTimeType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class DateTimeTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php index f5a702a491..fe76eaf97f 100644 --- a/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class DateTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php index db2e3b5e75..e8de05ae05 100644 --- a/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\EmailType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class EmailTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php index 78b38efe2e..7cda446bb8 100644 --- a/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class FileTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php index ad7d00bc34..ba78dbd4b3 100644 --- a/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php @@ -11,7 +11,6 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Validator\ValidatorExtension; use Symfony\Component\Form\Form; use Symfony\Component\Form\Forms; @@ -30,7 +29,6 @@ class FormTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; public function testSubmitValidatesData() diff --git a/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php index 29e5bdb325..955027ff09 100644 --- a/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\HiddenType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class HiddenTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php index 5d101ef2dd..e664003274 100644 --- a/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class IntegerTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php index 3a3e09a1aa..e29e837e0c 100644 --- a/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\LanguageType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class LanguageTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php index bbb8048c77..83f7c762f2 100644 --- a/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\LocaleType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class LocaleTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php index f8668caf46..5d62c63852 100644 --- a/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\MoneyType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class MoneyTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php index 1d693133a4..11efbde963 100644 --- a/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\NumberType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class NumberTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php index 1c55d87774..489d87283b 100644 --- a/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\PasswordType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class PasswordTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php index dd05b64a88..2ac42f674f 100644 --- a/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\PercentType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class PercentTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php index 4ca686ac38..cc489c90aa 100644 --- a/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\RadioType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class RadioTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php index 2832ef9eca..eba6049e95 100644 --- a/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\RangeType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class RangeTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php index 8bb635e077..445e60c6c2 100644 --- a/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\RepeatedType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class RepeatedTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php index 5ce3fff70a..d362c8cfe6 100644 --- a/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\SearchType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class SearchTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php index 969f2c9f2a..7d7f5307bf 100644 --- a/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\TelType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class TelTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php index 29019cd0b6..2b48de4d19 100644 --- a/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\TimeType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class TimeTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php index 7e00cff6d4..f66d4d4229 100644 --- a/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\TimezoneType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class TimezoneTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) diff --git a/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php index 698b181314..cb85fde39a 100644 --- a/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php @@ -11,13 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\Extension\Core\Type\UrlType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; class UrlTypeValidatorExtensionTest extends BaseValidatorExtensionTest { - use ExpectDeprecationTrait; use ValidatorExtensionTrait; protected function createForm(array $options = []) From 896c471afa61097f97d4e4f1f346ad31dcfc2daf Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 9 Sep 2021 14:56:10 +0200 Subject: [PATCH 026/208] Fix return types --- ClearableErrorsInterface.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ClearableErrorsInterface.php b/ClearableErrorsInterface.php index e609bed02f..a05ece05a8 100644 --- a/ClearableErrorsInterface.php +++ b/ClearableErrorsInterface.php @@ -25,5 +25,5 @@ interface ClearableErrorsInterface * * @return $this */ - public function clearErrors(bool $deep = false); + public function clearErrors(bool $deep = false): static; } From d8292573be0334494ec99036ac18595dd540da63 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 30 Sep 2021 16:50:34 +0200 Subject: [PATCH 027/208] Use #[AsCommand] to describe commands --- Command/DebugCommand.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index 245ebb4772..2f74e8b6ce 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Command; +use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; @@ -29,11 +30,9 @@ * * @author Yonel Ceruto */ +#[AsCommand(name: 'debug:form', description: 'Display form type information')] class DebugCommand extends Command { - protected static $defaultName = 'debug:form'; - protected static $defaultDescription = 'Display form type information'; - private FormRegistryInterface $formRegistry; private array $namespaces; private array $types; @@ -65,7 +64,6 @@ protected function configure() new InputOption('show-deprecated', null, InputOption::VALUE_NONE, 'Display deprecated options in form types'), new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt or json)', 'txt'), ]) - ->setDescription(self::$defaultDescription) ->setHelp(<<<'EOF' The %command.name% command displays information about form types. From 51ae9c69c41e67d69cdbf9eefb40a794a7deaa80 Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Wed, 8 Dec 2021 14:13:04 +0100 Subject: [PATCH 028/208] Leverage str_starts_with(), str_ends_with() and str_contains() --- Extension/Core/DataAccessor/PropertyPathAccessor.php | 2 +- Extension/Validator/ViolationMapper/ViolationMapper.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Extension/Core/DataAccessor/PropertyPathAccessor.php b/Extension/Core/DataAccessor/PropertyPathAccessor.php index aab95f3741..9e1e0af520 100644 --- a/Extension/Core/DataAccessor/PropertyPathAccessor.php +++ b/Extension/Core/DataAccessor/PropertyPathAccessor.php @@ -92,7 +92,7 @@ private function getPropertyValue(object|array $data, PropertyPathInterface $pro } catch (PropertyAccessException $e) { if (!$e instanceof UninitializedPropertyException // For versions without UninitializedPropertyException check the exception message - && (class_exists(UninitializedPropertyException::class) || false === strpos($e->getMessage(), 'You should initialize it')) + && (class_exists(UninitializedPropertyException::class) || !str_contains($e->getMessage(), 'You should initialize it')) ) { throw $e; } diff --git a/Extension/Validator/ViolationMapper/ViolationMapper.php b/Extension/Validator/ViolationMapper/ViolationMapper.php index cdcd1c1a76..7f6b88d6c4 100644 --- a/Extension/Validator/ViolationMapper/ViolationMapper.php +++ b/Extension/Validator/ViolationMapper/ViolationMapper.php @@ -153,7 +153,7 @@ public function mapViolation(ConstraintViolation $violation, FormInterface $form $message = $violation->getMessage(); $messageTemplate = $violation->getMessageTemplate(); - if (false !== strpos($message, '{{ label }}') || false !== strpos($messageTemplate, '{{ label }}')) { + if (str_contains($message, '{{ label }}') || str_contains($messageTemplate, '{{ label }}')) { $form = $scope; do { From ff3f9fdbfbfc6e4813880fa48c014003d6b60f65 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 7 Dec 2021 12:27:08 +0100 Subject: [PATCH 029/208] Remove FQCN type hints on properties --- AbstractExtension.php | 2 +- Button.php | 4 ++-- ButtonBuilder.php | 2 +- ChoiceList/Factory/CachingFactoryDecorator.php | 2 +- ChoiceList/Factory/PropertyAccessDecorator.php | 4 ++-- ChoiceList/LazyChoiceList.php | 2 +- ChoiceList/Loader/AbstractChoiceLoader.php | 2 +- ChoiceList/Loader/FilterChoiceLoaderDecorator.php | 2 +- Command/DebugCommand.php | 4 ++-- Console/Descriptor/TextDescriptor.php | 2 +- Extension/Core/CoreExtension.php | 6 +++--- Extension/Core/DataAccessor/PropertyPathAccessor.php | 2 +- Extension/Core/DataMapper/DataMapper.php | 2 +- .../DataTransformer/ChoiceToValueTransformer.php | 2 +- .../DataTransformer/ChoicesToValuesTransformer.php | 2 +- .../EventListener/TransformationFailureListener.php | 2 +- Extension/Core/Type/ChoiceType.php | 4 ++-- Extension/Core/Type/ColorType.php | 2 +- Extension/Core/Type/FileType.php | 2 +- Extension/Core/Type/FormType.php | 2 +- .../Core/Type/TransformationFailureExtension.php | 2 +- Extension/Csrf/CsrfExtension.php | 4 ++-- .../Csrf/EventListener/CsrfValidationListener.php | 6 +++--- Extension/Csrf/Type/FormTypeCsrfExtension.php | 6 +++--- Extension/DataCollector/DataCollectorExtension.php | 2 +- .../EventListener/DataCollectorListener.php | 2 +- Extension/DataCollector/FormDataCollector.php | 2 +- .../Proxy/ResolvedTypeDataCollectorProxy.php | 4 ++-- .../Proxy/ResolvedTypeFactoryDataCollectorProxy.php | 4 ++-- .../Type/DataCollectorTypeExtension.php | 2 +- .../DependencyInjectionExtension.php | 4 ++-- .../HttpFoundation/HttpFoundationRequestHandler.php | 2 +- .../Type/FormTypeHttpFoundationExtension.php | 2 +- .../Validator/EventListener/ValidationListener.php | 4 ++-- .../Validator/Type/FormTypeValidatorExtension.php | 4 ++-- .../Validator/Type/UploadValidatorExtension.php | 2 +- Extension/Validator/ValidatorExtension.php | 6 +++--- Extension/Validator/ValidatorTypeGuesser.php | 2 +- Extension/Validator/ViolationMapper/MappingRule.php | 2 +- Extension/Validator/ViolationMapper/RelativePath.php | 2 +- .../Validator/ViolationMapper/ViolationMapper.php | 4 ++-- Form.php | 12 ++++++------ FormConfigBuilder.php | 12 ++++++------ FormError.php | 2 +- FormErrorIterator.php | 2 +- FormEvent.php | 2 +- FormFactory.php | 2 +- FormFactoryBuilder.php | 2 +- FormRegistry.php | 4 ++-- FormRenderer.php | 4 ++-- NativeRequestHandler.php | 2 +- PreloadedExtension.php | 2 +- ResolvedFormType.php | 6 +++--- Util/ServerParams.php | 2 +- 54 files changed, 87 insertions(+), 87 deletions(-) diff --git a/AbstractExtension.php b/AbstractExtension.php index 79d61e8bc0..5a077a42a6 100644 --- a/AbstractExtension.php +++ b/AbstractExtension.php @@ -36,7 +36,7 @@ abstract class AbstractExtension implements FormExtensionInterface /** * The type guesser provided by this extension. */ - private ?FormTypeGuesserInterface $typeGuesser = null; + private $typeGuesser = null; /** * Whether the type guesser has been loaded. diff --git a/Button.php b/Button.php index 92d00ee145..ad10066fac 100644 --- a/Button.php +++ b/Button.php @@ -25,8 +25,8 @@ */ class Button implements \IteratorAggregate, FormInterface { - private ?FormInterface $parent = null; - private FormConfigInterface $config; + private $parent = null; + private $config; private bool $submitted = false; /** diff --git a/ButtonBuilder.php b/ButtonBuilder.php index 7c8f186e12..30e07fb811 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -29,7 +29,7 @@ class ButtonBuilder implements \IteratorAggregate, FormBuilderInterface protected $locked = false; private bool $disabled = false; - private ResolvedFormTypeInterface $type; + private $type; private string $name; private array $attributes = []; private array $options; diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index f5174bcfd5..fb7b945162 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -27,7 +27,7 @@ */ class CachingFactoryDecorator implements ChoiceListFactoryInterface, ResetInterface { - private ChoiceListFactoryInterface $decoratedFactory; + private $decoratedFactory; /** * @var ChoiceListInterface[] diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index 8a678e7e18..782c122989 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -38,8 +38,8 @@ */ class PropertyAccessDecorator implements ChoiceListFactoryInterface { - private ChoiceListFactoryInterface $decoratedFactory; - private PropertyAccessorInterface $propertyAccessor; + private $decoratedFactory; + private $propertyAccessor; public function __construct(ChoiceListFactoryInterface $decoratedFactory, PropertyAccessorInterface $propertyAccessor = null) { diff --git a/ChoiceList/LazyChoiceList.php b/ChoiceList/LazyChoiceList.php index e339bcd249..1518658b9b 100644 --- a/ChoiceList/LazyChoiceList.php +++ b/ChoiceList/LazyChoiceList.php @@ -27,7 +27,7 @@ */ class LazyChoiceList implements ChoiceListInterface { - private ChoiceLoaderInterface $loader; + private $loader; /** * The callable creating string values for each choice. diff --git a/ChoiceList/Loader/AbstractChoiceLoader.php b/ChoiceList/Loader/AbstractChoiceLoader.php index def29c80de..b8f2aa7a4b 100644 --- a/ChoiceList/Loader/AbstractChoiceLoader.php +++ b/ChoiceList/Loader/AbstractChoiceLoader.php @@ -22,7 +22,7 @@ abstract class AbstractChoiceLoader implements ChoiceLoaderInterface /** * The loaded choice list. */ - private ArrayChoiceList $choiceList; + private $choiceList; /** * @final diff --git a/ChoiceList/Loader/FilterChoiceLoaderDecorator.php b/ChoiceList/Loader/FilterChoiceLoaderDecorator.php index 12e6d0e2a1..569276e7ad 100644 --- a/ChoiceList/Loader/FilterChoiceLoaderDecorator.php +++ b/ChoiceList/Loader/FilterChoiceLoaderDecorator.php @@ -18,7 +18,7 @@ */ class FilterChoiceLoaderDecorator extends AbstractChoiceLoader { - private ChoiceLoaderInterface $decoratedLoader; + private $decoratedLoader; private \Closure $filter; public function __construct(ChoiceLoaderInterface $loader, callable $filter) diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index d5545a6704..23008e3458 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -35,12 +35,12 @@ #[AsCommand(name: 'debug:form', description: 'Display form type information')] class DebugCommand extends Command { - private FormRegistryInterface $formRegistry; + private $formRegistry; private array $namespaces; private array $types; private array $extensions; private array $guessers; - private ?FileLinkFormatter $fileLinkFormatter; + private $fileLinkFormatter; public function __construct(FormRegistryInterface $formRegistry, array $namespaces = ['Symfony\Component\Form\Extension\Core\Type'], array $types = [], array $extensions = [], array $guessers = [], FileLinkFormatter $fileLinkFormatter = null) { diff --git a/Console/Descriptor/TextDescriptor.php b/Console/Descriptor/TextDescriptor.php index ba79d806ad..4862a674c2 100644 --- a/Console/Descriptor/TextDescriptor.php +++ b/Console/Descriptor/TextDescriptor.php @@ -24,7 +24,7 @@ */ class TextDescriptor extends Descriptor { - private ?FileLinkFormatter $fileLinkFormatter; + private $fileLinkFormatter; public function __construct(FileLinkFormatter $fileLinkFormatter = null) { diff --git a/Extension/Core/CoreExtension.php b/Extension/Core/CoreExtension.php index 951bf345c0..9eae0a0ce1 100644 --- a/Extension/Core/CoreExtension.php +++ b/Extension/Core/CoreExtension.php @@ -28,9 +28,9 @@ */ class CoreExtension extends AbstractExtension { - private PropertyAccessorInterface $propertyAccessor; - private ChoiceListFactoryInterface $choiceListFactory; - private ?TranslatorInterface $translator; + private $propertyAccessor; + private $choiceListFactory; + private $translator; public function __construct(PropertyAccessorInterface $propertyAccessor = null, ChoiceListFactoryInterface $choiceListFactory = null, TranslatorInterface $translator = null) { diff --git a/Extension/Core/DataAccessor/PropertyPathAccessor.php b/Extension/Core/DataAccessor/PropertyPathAccessor.php index aab95f3741..f73187bb4d 100644 --- a/Extension/Core/DataAccessor/PropertyPathAccessor.php +++ b/Extension/Core/DataAccessor/PropertyPathAccessor.php @@ -28,7 +28,7 @@ */ class PropertyPathAccessor implements DataAccessorInterface { - private PropertyAccessorInterface $propertyAccessor; + private $propertyAccessor; public function __construct(PropertyAccessorInterface $propertyAccessor = null) { diff --git a/Extension/Core/DataMapper/DataMapper.php b/Extension/Core/DataMapper/DataMapper.php index 58f6ff5e5a..2b8f98f701 100644 --- a/Extension/Core/DataMapper/DataMapper.php +++ b/Extension/Core/DataMapper/DataMapper.php @@ -25,7 +25,7 @@ */ class DataMapper implements DataMapperInterface { - private DataAccessorInterface $dataAccessor; + private $dataAccessor; public function __construct(DataAccessorInterface $dataAccessor = null) { diff --git a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php index f7b0798224..b02ffab716 100644 --- a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php +++ b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php @@ -20,7 +20,7 @@ */ class ChoiceToValueTransformer implements DataTransformerInterface { - private ChoiceListInterface $choiceList; + private $choiceList; public function __construct(ChoiceListInterface $choiceList) { diff --git a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php index e2f1f2f22d..96f217e6e7 100644 --- a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php +++ b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php @@ -20,7 +20,7 @@ */ class ChoicesToValuesTransformer implements DataTransformerInterface { - private ChoiceListInterface $choiceList; + private $choiceList; public function __construct(ChoiceListInterface $choiceList) { diff --git a/Extension/Core/EventListener/TransformationFailureListener.php b/Extension/Core/EventListener/TransformationFailureListener.php index ae705fc57a..d2fbfeb887 100644 --- a/Extension/Core/EventListener/TransformationFailureListener.php +++ b/Extension/Core/EventListener/TransformationFailureListener.php @@ -22,7 +22,7 @@ */ class TransformationFailureListener implements EventSubscriberInterface { - private ?TranslatorInterface $translator; + private $translator; public function __construct(TranslatorInterface $translator = null) { diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 3980d579fa..f01f212ab7 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -49,8 +49,8 @@ class ChoiceType extends AbstractType { - private ChoiceListFactoryInterface $choiceListFactory; - private ?TranslatorInterface $translator; + private $choiceListFactory; + private $translator; public function __construct(ChoiceListFactoryInterface $choiceListFactory = null, TranslatorInterface $translator = null) { diff --git a/Extension/Core/Type/ColorType.php b/Extension/Core/Type/ColorType.php index cca92e6e26..f8caf35477 100644 --- a/Extension/Core/Type/ColorType.php +++ b/Extension/Core/Type/ColorType.php @@ -26,7 +26,7 @@ class ColorType extends AbstractType */ private const HTML5_PATTERN = '/^#[0-9a-f]{6}$/i'; - private ?TranslatorInterface $translator; + private $translator; public function __construct(TranslatorInterface $translator = null) { diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index 89f70bcde8..37fbd62442 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -33,7 +33,7 @@ class FileType extends AbstractType self::MIB_BYTES => 'MiB', ]; - private ?TranslatorInterface $translator; + private $translator; public function __construct(TranslatorInterface $translator = null) { diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index b2ad206236..8b02a26dd6 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -28,7 +28,7 @@ class FormType extends BaseType { - private DataMapper $dataMapper; + private $dataMapper; public function __construct(PropertyAccessorInterface $propertyAccessor = null) { diff --git a/Extension/Core/Type/TransformationFailureExtension.php b/Extension/Core/Type/TransformationFailureExtension.php index c73bd29582..f766633c9b 100644 --- a/Extension/Core/Type/TransformationFailureExtension.php +++ b/Extension/Core/Type/TransformationFailureExtension.php @@ -21,7 +21,7 @@ */ class TransformationFailureExtension extends AbstractTypeExtension { - private ?TranslatorInterface $translator; + private $translator; public function __construct(TranslatorInterface $translator = null) { diff --git a/Extension/Csrf/CsrfExtension.php b/Extension/Csrf/CsrfExtension.php index 97228f56c9..e7460d610c 100644 --- a/Extension/Csrf/CsrfExtension.php +++ b/Extension/Csrf/CsrfExtension.php @@ -22,8 +22,8 @@ */ class CsrfExtension extends AbstractExtension { - private CsrfTokenManagerInterface $tokenManager; - private ?TranslatorInterface $translator; + private $tokenManager; + private $translator; private ?string $translationDomain; public function __construct(CsrfTokenManagerInterface $tokenManager, TranslatorInterface $translator = null, string $translationDomain = null) diff --git a/Extension/Csrf/EventListener/CsrfValidationListener.php b/Extension/Csrf/EventListener/CsrfValidationListener.php index 732b036de1..a6428fac2c 100644 --- a/Extension/Csrf/EventListener/CsrfValidationListener.php +++ b/Extension/Csrf/EventListener/CsrfValidationListener.php @@ -26,12 +26,12 @@ class CsrfValidationListener implements EventSubscriberInterface { private string $fieldName; - private CsrfTokenManagerInterface $tokenManager; + private $tokenManager; private string $tokenId; private string $errorMessage; - private ?TranslatorInterface $translator; + private $translator; private ?string $translationDomain; - private ServerParams $serverParams; + private $serverParams; public static function getSubscribedEvents(): array { diff --git a/Extension/Csrf/Type/FormTypeCsrfExtension.php b/Extension/Csrf/Type/FormTypeCsrfExtension.php index ca3bf22dff..e8f90fe326 100644 --- a/Extension/Csrf/Type/FormTypeCsrfExtension.php +++ b/Extension/Csrf/Type/FormTypeCsrfExtension.php @@ -28,12 +28,12 @@ */ class FormTypeCsrfExtension extends AbstractTypeExtension { - private CsrfTokenManagerInterface $defaultTokenManager; + private $defaultTokenManager; private bool $defaultEnabled; private string $defaultFieldName; - private ?TranslatorInterface $translator; + private $translator; private ?string $translationDomain; - private ?ServerParams $serverParams; + private $serverParams; public function __construct(CsrfTokenManagerInterface $defaultTokenManager, bool $defaultEnabled = true, string $defaultFieldName = '_token', TranslatorInterface $translator = null, string $translationDomain = null, ServerParams $serverParams = null) { diff --git a/Extension/DataCollector/DataCollectorExtension.php b/Extension/DataCollector/DataCollectorExtension.php index cafd0ffc66..3e4785670e 100644 --- a/Extension/DataCollector/DataCollectorExtension.php +++ b/Extension/DataCollector/DataCollectorExtension.php @@ -21,7 +21,7 @@ */ class DataCollectorExtension extends AbstractExtension { - private FormDataCollectorInterface $dataCollector; + private $dataCollector; public function __construct(FormDataCollectorInterface $dataCollector) { diff --git a/Extension/DataCollector/EventListener/DataCollectorListener.php b/Extension/DataCollector/EventListener/DataCollectorListener.php index dbc36123c7..4007935d62 100644 --- a/Extension/DataCollector/EventListener/DataCollectorListener.php +++ b/Extension/DataCollector/EventListener/DataCollectorListener.php @@ -24,7 +24,7 @@ */ class DataCollectorListener implements EventSubscriberInterface { - private FormDataCollectorInterface $dataCollector; + private $dataCollector; public function __construct(FormDataCollectorInterface $dataCollector) { diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index 023a63fe17..8bf2c48008 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -33,7 +33,7 @@ */ class FormDataCollector extends DataCollector implements FormDataCollectorInterface { - private FormDataExtractorInterface $dataExtractor; + private $dataExtractor; /** * Stores the collected data per {@link FormInterface} instance. diff --git a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php index 7563e778e8..ca010e7edb 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php @@ -27,8 +27,8 @@ */ class ResolvedTypeDataCollectorProxy implements ResolvedFormTypeInterface { - private ResolvedFormTypeInterface $proxiedType; - private FormDataCollectorInterface $dataCollector; + private $proxiedType; + private $dataCollector; public function __construct(ResolvedFormTypeInterface $proxiedType, FormDataCollectorInterface $dataCollector) { diff --git a/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php index 835a7e879a..606e269be9 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php @@ -24,8 +24,8 @@ */ class ResolvedTypeFactoryDataCollectorProxy implements ResolvedFormTypeFactoryInterface { - private ResolvedFormTypeFactoryInterface $proxiedFactory; - private FormDataCollectorInterface $dataCollector; + private $proxiedFactory; + private $dataCollector; public function __construct(ResolvedFormTypeFactoryInterface $proxiedFactory, FormDataCollectorInterface $dataCollector) { diff --git a/Extension/DataCollector/Type/DataCollectorTypeExtension.php b/Extension/DataCollector/Type/DataCollectorTypeExtension.php index 73f8a214fa..b6b98cc3a4 100644 --- a/Extension/DataCollector/Type/DataCollectorTypeExtension.php +++ b/Extension/DataCollector/Type/DataCollectorTypeExtension.php @@ -25,7 +25,7 @@ */ class DataCollectorTypeExtension extends AbstractTypeExtension { - private DataCollectorListener $listener; + private $listener; public function __construct(FormDataCollectorInterface $dataCollector) { diff --git a/Extension/DependencyInjection/DependencyInjectionExtension.php b/Extension/DependencyInjection/DependencyInjectionExtension.php index 5fe0371df7..0a24e18f1b 100644 --- a/Extension/DependencyInjection/DependencyInjectionExtension.php +++ b/Extension/DependencyInjection/DependencyInjectionExtension.php @@ -20,9 +20,9 @@ class DependencyInjectionExtension implements FormExtensionInterface { - private ?FormTypeGuesserChain $guesser = null; + private $guesser = null; private bool $guesserLoaded = false; - private ContainerInterface $typeContainer; + private $typeContainer; private array $typeExtensionServices; private iterable $guesserServices; diff --git a/Extension/HttpFoundation/HttpFoundationRequestHandler.php b/Extension/HttpFoundation/HttpFoundationRequestHandler.php index 7180bafd81..57eb234206 100644 --- a/Extension/HttpFoundation/HttpFoundationRequestHandler.php +++ b/Extension/HttpFoundation/HttpFoundationRequestHandler.php @@ -28,7 +28,7 @@ */ class HttpFoundationRequestHandler implements RequestHandlerInterface { - private ServerParams $serverParams; + private $serverParams; public function __construct(ServerParams $serverParams = null) { diff --git a/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php b/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php index 3d283d0e4e..0d77f06ce3 100644 --- a/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php +++ b/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php @@ -22,7 +22,7 @@ */ class FormTypeHttpFoundationExtension extends AbstractTypeExtension { - private RequestHandlerInterface $requestHandler; + private $requestHandler; public function __construct(RequestHandlerInterface $requestHandler = null) { diff --git a/Extension/Validator/EventListener/ValidationListener.php b/Extension/Validator/EventListener/ValidationListener.php index 3d010b77c5..22520ee205 100644 --- a/Extension/Validator/EventListener/ValidationListener.php +++ b/Extension/Validator/EventListener/ValidationListener.php @@ -23,8 +23,8 @@ */ class ValidationListener implements EventSubscriberInterface { - private ValidatorInterface $validator; - private ViolationMapperInterface $violationMapper; + private $validator; + private $violationMapper; /** * {@inheritdoc} diff --git a/Extension/Validator/Type/FormTypeValidatorExtension.php b/Extension/Validator/Type/FormTypeValidatorExtension.php index 40fe64df40..865047fa04 100644 --- a/Extension/Validator/Type/FormTypeValidatorExtension.php +++ b/Extension/Validator/Type/FormTypeValidatorExtension.php @@ -27,8 +27,8 @@ */ class FormTypeValidatorExtension extends BaseValidatorExtension { - private ValidatorInterface $validator; - private ViolationMapper $violationMapper; + private $validator; + private $violationMapper; private bool $legacyErrorMessages; public function __construct(ValidatorInterface $validator, bool $legacyErrorMessages = true, FormRendererInterface $formRenderer = null, TranslatorInterface $translator = null) diff --git a/Extension/Validator/Type/UploadValidatorExtension.php b/Extension/Validator/Type/UploadValidatorExtension.php index b5ddecd99d..0730c73601 100644 --- a/Extension/Validator/Type/UploadValidatorExtension.php +++ b/Extension/Validator/Type/UploadValidatorExtension.php @@ -23,7 +23,7 @@ */ class UploadValidatorExtension extends AbstractTypeExtension { - private TranslatorInterface $translator; + private $translator; private ?string $translationDomain; public function __construct(TranslatorInterface $translator, string $translationDomain = null) diff --git a/Extension/Validator/ValidatorExtension.php b/Extension/Validator/ValidatorExtension.php index 3a0ec662a1..5e79071b1e 100644 --- a/Extension/Validator/ValidatorExtension.php +++ b/Extension/Validator/ValidatorExtension.php @@ -27,9 +27,9 @@ */ class ValidatorExtension extends AbstractExtension { - private ValidatorInterface $validator; - private ?FormRendererInterface $formRenderer; - private ?TranslatorInterface $translator; + private $validator; + private $formRenderer; + private $translator; private bool $legacyErrorMessages; public function __construct(ValidatorInterface $validator, bool $legacyErrorMessages = true, FormRendererInterface $formRenderer = null, TranslatorInterface $translator = null) diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index 7c9afa7c9b..9e7c724afa 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -21,7 +21,7 @@ class ValidatorTypeGuesser implements FormTypeGuesserInterface { - private MetadataFactoryInterface $metadataFactory; + private $metadataFactory; public function __construct(MetadataFactoryInterface $metadataFactory) { diff --git a/Extension/Validator/ViolationMapper/MappingRule.php b/Extension/Validator/ViolationMapper/MappingRule.php index 6e33f22297..0202ac16df 100644 --- a/Extension/Validator/ViolationMapper/MappingRule.php +++ b/Extension/Validator/ViolationMapper/MappingRule.php @@ -19,7 +19,7 @@ */ class MappingRule { - private FormInterface $origin; + private $origin; private string $propertyPath; private string $targetPath; diff --git a/Extension/Validator/ViolationMapper/RelativePath.php b/Extension/Validator/ViolationMapper/RelativePath.php index 0384edb444..d32d90d41e 100644 --- a/Extension/Validator/ViolationMapper/RelativePath.php +++ b/Extension/Validator/ViolationMapper/RelativePath.php @@ -19,7 +19,7 @@ */ class RelativePath extends PropertyPath { - private FormInterface $root; + private $root; public function __construct(FormInterface $root, string $propertyPath) { diff --git a/Extension/Validator/ViolationMapper/ViolationMapper.php b/Extension/Validator/ViolationMapper/ViolationMapper.php index cdcd1c1a76..8e4b6d4b36 100644 --- a/Extension/Validator/ViolationMapper/ViolationMapper.php +++ b/Extension/Validator/ViolationMapper/ViolationMapper.php @@ -28,8 +28,8 @@ */ class ViolationMapper implements ViolationMapperInterface { - private ?FormRendererInterface $formRenderer; - private ?TranslatorInterface $translator; + private $formRenderer; + private $translator; private bool $allowNonSynchronized = false; public function __construct(FormRendererInterface $formRenderer = null, TranslatorInterface $translator = null) diff --git a/Form.php b/Form.php index bed1fcb6c3..2b7ac7ced8 100644 --- a/Form.php +++ b/Form.php @@ -71,15 +71,15 @@ */ class Form implements \IteratorAggregate, FormInterface, ClearableErrorsInterface { - private FormConfigInterface $config; - private ?FormInterface $parent = null; + private $config; + private $parent = null; /** * A map of FormInterface instances. * * @var OrderedHashMap */ - private OrderedHashMap $children; + private $children; /** * @var FormError[] @@ -91,7 +91,7 @@ class Form implements \IteratorAggregate, FormInterface, ClearableErrorsInterfac /** * The button that was used to submit the form. */ - private FormInterface|ClickableInterface|null $clickedButton = null; + private $clickedButton = null; private mixed $modelData = null; private mixed $normData = null; @@ -105,7 +105,7 @@ class Form implements \IteratorAggregate, FormInterface, ClearableErrorsInterfac /** * The transformation failure generated during submission, if any. */ - private ?TransformationFailedException $transformationFailure = null; + private $transformationFailure = null; /** * Whether the form's data has been initialized. @@ -131,7 +131,7 @@ class Form implements \IteratorAggregate, FormInterface, ClearableErrorsInterfac */ private bool $inheritData; - private ?PropertyPathInterface $propertyPath = null; + private $propertyPath = null; /** * @throws LogicException if a data mapper is not provided for a compound form diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 9bbe7abcc4..02731ff449 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -34,17 +34,17 @@ class FormConfigBuilder implements FormConfigBuilderInterface /** @var bool */ protected $locked = false; - private EventDispatcherInterface $dispatcher; + private $dispatcher; private string $name; - private ?PropertyPathInterface $propertyPath = null; + private $propertyPath = null; private bool $mapped = true; private bool $byReference = true; private bool $inheritData = false; private bool $compound = false; - private ResolvedFormTypeInterface $type; + private $type; private array $viewTransformers = []; private array $modelTransformers = []; - private ?DataMapperInterface $dataMapper = null; + private $dataMapper = null; private bool $required = true; private bool $disabled = false; private bool $errorBubbling = false; @@ -53,10 +53,10 @@ class FormConfigBuilder implements FormConfigBuilderInterface private mixed $data = null; private ?string $dataClass; private bool $dataLocked = false; - private FormFactoryInterface $formFactory; + private $formFactory; private string $action = ''; private string $method = 'POST'; - private RequestHandlerInterface $requestHandler; + private $requestHandler; private bool $autoInitialize = false; private array $options; private ?\Closure $isEmptyCallback = null; diff --git a/FormError.php b/FormError.php index aafd723f22..59dbc49376 100644 --- a/FormError.php +++ b/FormError.php @@ -30,7 +30,7 @@ class FormError /** * The form that spawned this error. */ - private ?FormInterface $origin = null; + private $origin = null; /** * Any array key in $messageParameters will be used as a placeholder in diff --git a/FormErrorIterator.php b/FormErrorIterator.php index 7b0574dd9f..79b0d6206d 100644 --- a/FormErrorIterator.php +++ b/FormErrorIterator.php @@ -40,7 +40,7 @@ class FormErrorIterator implements \RecursiveIterator, \SeekableIterator, \Array */ public const INDENTATION = ' '; - private FormInterface $form; + private $form; private array $errors; /** diff --git a/FormEvent.php b/FormEvent.php index c9c3053cfe..5a9956fda3 100644 --- a/FormEvent.php +++ b/FormEvent.php @@ -18,7 +18,7 @@ */ class FormEvent extends Event { - private FormInterface $form; + private $form; protected $data; public function __construct(FormInterface $form, mixed $data) diff --git a/FormFactory.php b/FormFactory.php index 2f5e172f7a..087fd75af8 100644 --- a/FormFactory.php +++ b/FormFactory.php @@ -16,7 +16,7 @@ class FormFactory implements FormFactoryInterface { - private FormRegistryInterface $registry; + private $registry; public function __construct(FormRegistryInterface $registry) { diff --git a/FormFactoryBuilder.php b/FormFactoryBuilder.php index 0ad58a660e..0413a6df3f 100644 --- a/FormFactoryBuilder.php +++ b/FormFactoryBuilder.php @@ -22,7 +22,7 @@ class FormFactoryBuilder implements FormFactoryBuilderInterface { private bool $forceCoreExtension; - private ResolvedFormTypeFactoryInterface $resolvedTypeFactory; + private $resolvedTypeFactory; /** * @var FormExtensionInterface[] diff --git a/FormRegistry.php b/FormRegistry.php index acd392d337..18f91ce535 100644 --- a/FormRegistry.php +++ b/FormRegistry.php @@ -33,8 +33,8 @@ class FormRegistry implements FormRegistryInterface */ private array $types = []; - private FormTypeGuesserInterface|null|false $guesser = false; - private ResolvedFormTypeFactoryInterface $resolvedTypeFactory; + private $guesser = false; + private $resolvedTypeFactory; private array $checkedTypes = []; /** diff --git a/FormRenderer.php b/FormRenderer.php index ab8ff1aa3b..513ce4abd8 100644 --- a/FormRenderer.php +++ b/FormRenderer.php @@ -25,8 +25,8 @@ class FormRenderer implements FormRendererInterface { public const CACHE_KEY_VAR = 'unique_block_prefix'; - private FormRendererEngineInterface $engine; - private ?CsrfTokenManagerInterface $csrfTokenManager; + private $engine; + private $csrfTokenManager; private array $blockNameHierarchyMap = []; private array $hierarchyLevelMap = []; private array $variableStack = []; diff --git a/NativeRequestHandler.php b/NativeRequestHandler.php index 272239e65b..d821b5cef4 100644 --- a/NativeRequestHandler.php +++ b/NativeRequestHandler.php @@ -21,7 +21,7 @@ */ class NativeRequestHandler implements RequestHandlerInterface { - private ServerParams $serverParams; + private $serverParams; /** * The allowed keys of the $_FILES array. diff --git a/PreloadedExtension.php b/PreloadedExtension.php index 3c0ae26e89..d15eb801ec 100644 --- a/PreloadedExtension.php +++ b/PreloadedExtension.php @@ -22,7 +22,7 @@ class PreloadedExtension implements FormExtensionInterface { private array $types = []; private array $typeExtensions = []; - private ?FormTypeGuesserInterface $typeGuesser; + private $typeGuesser; /** * Creates a new preloaded extension. diff --git a/ResolvedFormType.php b/ResolvedFormType.php index 37a5bf45be..619ce4bb9d 100644 --- a/ResolvedFormType.php +++ b/ResolvedFormType.php @@ -23,16 +23,16 @@ */ class ResolvedFormType implements ResolvedFormTypeInterface { - private FormTypeInterface $innerType; + private $innerType; /** * @var FormTypeExtensionInterface[] */ private array $typeExtensions; - private ?ResolvedFormTypeInterface $parent; + private $parent; - private OptionsResolver $optionsResolver; + private $optionsResolver; /** * @param FormTypeExtensionInterface[] $typeExtensions diff --git a/Util/ServerParams.php b/Util/ServerParams.php index 0038cb83cc..cc7225d5cd 100644 --- a/Util/ServerParams.php +++ b/Util/ServerParams.php @@ -18,7 +18,7 @@ */ class ServerParams { - private ?RequestStack $requestStack; + private $requestStack; public function __construct(RequestStack $requestStack = null) { From 80470cc50a46664caf3d877677fbcd100d5df873 Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Mon, 13 Dec 2021 16:44:47 +0100 Subject: [PATCH 030/208] Make use of the nullsafe operator --- FormFactory.php | 4 ++-- ResolvedFormType.php | 12 +++--------- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/FormFactory.php b/FormFactory.php index 2f5e172f7a..1b76273995 100644 --- a/FormFactory.php +++ b/FormFactory.php @@ -91,8 +91,8 @@ public function createBuilderForProperty(string $class, string $property, mixed $type = $typeGuess ? $typeGuess->getType() : TextType::class; - $maxLength = $maxLengthGuess ? $maxLengthGuess->getValue() : null; - $pattern = $patternGuess ? $patternGuess->getValue() : null; + $maxLength = $maxLengthGuess?->getValue(); + $pattern = $patternGuess?->getValue(); if (null !== $pattern) { $options = array_replace_recursive(['attr' => ['pattern' => $pattern]], $options); diff --git a/ResolvedFormType.php b/ResolvedFormType.php index 37a5bf45be..884d538a44 100644 --- a/ResolvedFormType.php +++ b/ResolvedFormType.php @@ -115,9 +115,7 @@ public function createView(FormInterface $form, FormView $parent = null): FormVi */ public function buildForm(FormBuilderInterface $builder, array $options) { - if (null !== $this->parent) { - $this->parent->buildForm($builder, $options); - } + $this->parent?->buildForm($builder, $options); $this->innerType->buildForm($builder, $options); @@ -131,9 +129,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) */ public function buildView(FormView $view, FormInterface $form, array $options) { - if (null !== $this->parent) { - $this->parent->buildView($view, $form, $options); - } + $this->parent?->buildView($view, $form, $options); $this->innerType->buildView($view, $form, $options); @@ -147,9 +143,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) */ public function finishView(FormView $view, FormInterface $form, array $options) { - if (null !== $this->parent) { - $this->parent->finishView($view, $form, $options); - } + $this->parent?->finishView($view, $form, $options); $this->innerType->finishView($view, $form, $options); From 65c14e9e34a8445760c2fab5736c2e41e61876ce Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 16 Dec 2021 23:13:01 +0100 Subject: [PATCH 031/208] [6.0] cs fixes --- Extension/DataCollector/FormDataCollectorInterface.php | 2 -- Form.php | 2 -- Guess/ValueGuess.php | 2 -- 3 files changed, 6 deletions(-) diff --git a/Extension/DataCollector/FormDataCollectorInterface.php b/Extension/DataCollector/FormDataCollectorInterface.php index f51773e405..0e1d32bfc8 100644 --- a/Extension/DataCollector/FormDataCollectorInterface.php +++ b/Extension/DataCollector/FormDataCollectorInterface.php @@ -78,8 +78,6 @@ public function buildFinalFormTree(FormInterface $form, FormView $view); /** * Returns all collected data. - * - * @return array|Data */ public function getData(): array|Data; } diff --git a/Form.php b/Form.php index 2b7ac7ced8..7c07824cf8 100644 --- a/Form.php +++ b/Form.php @@ -727,8 +727,6 @@ public function isValid(): bool /** * Returns the button that was used to submit the form. - * - * @return FormInterface|ClickableInterface|null */ public function getClickedButton(): FormInterface|ClickableInterface|null { diff --git a/Guess/ValueGuess.php b/Guess/ValueGuess.php index ddc8b53dd5..36abe6602d 100644 --- a/Guess/ValueGuess.php +++ b/Guess/ValueGuess.php @@ -32,8 +32,6 @@ public function __construct(string|int|bool|null $value, int $confidence) /** * Returns the guessed value. - * - * @return string|int|bool|null */ public function getValue(): string|int|bool|null { From 7ac3d0f8067bd42f436506799925bdcf39221258 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 16 Dec 2021 11:11:51 +0100 Subject: [PATCH 032/208] Add more nullsafe operators --- Button.php | 2 +- Extension/DataCollector/FormDataCollector.php | 4 +--- Form.php | 2 +- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/Button.php b/Button.php index 92d00ee145..7c80d03e34 100644 --- a/Button.php +++ b/Button.php @@ -271,7 +271,7 @@ public function isRequired(): bool */ public function isDisabled(): bool { - if ($this->parent && $this->parent->isDisabled()) { + if ($this->parent?->isDisabled()) { return true; } diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index 023a63fe17..f4640f1ff0 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -326,9 +326,7 @@ private function &recursiveBuildFinalFormTree(FormInterface $form = null, FormVi foreach ($view->children as $name => $childView) { // The CSRF token, for example, is never added to the form tree. // It is only present in the view. - $childForm = null !== $form && $form->has($name) - ? $form->get($name) - : null; + $childForm = $form?->has($name) ? $form->get($name) : null; $output['children'][$name] = &$this->recursiveBuildFinalFormTree($childForm, $childView, $outputByHash); } diff --git a/Form.php b/Form.php index 69108b82be..394f6a89f2 100644 --- a/Form.php +++ b/Form.php @@ -196,7 +196,7 @@ public function getPropertyPath(): ?PropertyPathInterface $parent = $this->parent; - while ($parent && $parent->getConfig()->getInheritData()) { + while ($parent?->getConfig()->getInheritData()) { $parent = $parent->getParent(); } From dadf38c5a69177f91aab87838f6f8ebf9551a178 Mon Sep 17 00:00:00 2001 From: Mathieu Santostefano Date: Fri, 21 Jan 2022 09:32:21 +0100 Subject: [PATCH 033/208] Add inputmode attribute on NumberType --- Extension/Core/Type/NumberType.php | 2 ++ Tests/Extension/Core/Type/NumberTypeTest.php | 32 ++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/Extension/Core/Type/NumberType.php b/Extension/Core/Type/NumberType.php index 1437369fba..fd75f689d7 100644 --- a/Extension/Core/Type/NumberType.php +++ b/Extension/Core/Type/NumberType.php @@ -47,6 +47,8 @@ public function buildView(FormView $view, FormInterface $form, array $options) { if ($options['html5']) { $view->vars['type'] = 'number'; + } else { + $view->vars['attr']['inputmode'] = 0 === $options['scale'] ? 'numeric' : 'decimal'; } } diff --git a/Tests/Extension/Core/Type/NumberTypeTest.php b/Tests/Extension/Core/Type/NumberTypeTest.php index 4aa86db62b..0cf482a9d8 100644 --- a/Tests/Extension/Core/Type/NumberTypeTest.php +++ b/Tests/Extension/Core/Type/NumberTypeTest.php @@ -202,4 +202,36 @@ public function testGroupingNotAllowedWithHtml5Widget() 'html5' => true, ]); } + + public function testNumericInputmode() + { + $form = $this->factory->create(static::TESTED_TYPE, null, [ + 'scale' => 0, + 'html5' => false, + ]); + $form->setData(12345.54321); + + $this->assertSame('numeric', $form->createView()->vars['attr']['inputmode']); + } + + public function testDecimalInputmode() + { + $form = $this->factory->create(static::TESTED_TYPE, null, [ + 'scale' => 2, + 'html5' => false, + ]); + $form->setData(12345.54321); + + $this->assertSame('decimal', $form->createView()->vars['attr']['inputmode']); + } + + public function testNoInputmodeWithHtml5Widget() + { + $form = $this->factory->create(static::TESTED_TYPE, null, [ + 'html5' => true, + ]); + $form->setData(12345.54321); + + $this->assertArrayNotHasKey('inputmode', $form->createView()->vars['attr']); + } } From ac9c573de97571f26a7cea266e11ce12f70413d7 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 9 Feb 2022 10:54:40 +0100 Subject: [PATCH 034/208] [Validator] Deprecate `Constraint::$errorNames` in favor of `Constraint::ERROR_NAMES` --- Extension/Validator/Constraints/Form.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Extension/Validator/Constraints/Form.php b/Extension/Validator/Constraints/Form.php index 714ef312dc..694281ddd1 100644 --- a/Extension/Validator/Constraints/Form.php +++ b/Extension/Validator/Constraints/Form.php @@ -21,11 +21,16 @@ class Form extends Constraint public const NOT_SYNCHRONIZED_ERROR = '1dafa156-89e1-4736-b832-419c2e501fca'; public const NO_SUCH_FIELD_ERROR = '6e5212ed-a197-4339-99aa-5654798a4854'; - protected static $errorNames = [ + protected const ERROR_NAMES = [ self::NOT_SYNCHRONIZED_ERROR => 'NOT_SYNCHRONIZED_ERROR', self::NO_SUCH_FIELD_ERROR => 'NO_SUCH_FIELD_ERROR', ]; + /** + * @deprecated since Symfony 6.1, use const ERROR_NAMES instead + */ + protected static $errorNames = self::ERROR_NAMES; + /** * {@inheritdoc} */ From e6b352a3461b3ebc0786dd2534107dd7f3b87116 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 8 Feb 2022 19:16:54 +0100 Subject: [PATCH 035/208] [ErrorHandler] trigger deprecations for `@final` properties --- Tests/VersionAwareTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/VersionAwareTest.php b/Tests/VersionAwareTest.php index 9ab4797b30..1a35b72fc0 100644 --- a/Tests/VersionAwareTest.php +++ b/Tests/VersionAwareTest.php @@ -13,7 +13,7 @@ trait VersionAwareTest { - protected static $supportedFeatureSetVersion = 404; + protected static int $supportedFeatureSetVersion = 404; protected function requiresFeatureSet(int $requiredFeatureSetVersion) { From f41c7b48e1c8ee4afd7dff99b3fd9851d0312fb6 Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Tue, 15 Feb 2022 16:42:18 +0100 Subject: [PATCH 036/208] Leverage the match expression --- Extension/Validator/ValidatorTypeGuesser.php | 17 ++++----- .../Factory/DefaultChoiceListFactoryTest.php | 36 +++++++++---------- 2 files changed, 27 insertions(+), 26 deletions(-) diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index 7c9afa7c9b..dd4f8c7684 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -16,6 +16,9 @@ use Symfony\Component\Form\Guess\TypeGuess; use Symfony\Component\Form\Guess\ValueGuess; use Symfony\Component\Validator\Constraint; +use Symfony\Component\Validator\Constraints\IsTrue; +use Symfony\Component\Validator\Constraints\NotBlank; +use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Mapping\ClassMetadataInterface; use Symfony\Component\Validator\Mapping\Factory\MetadataFactoryInterface; @@ -166,14 +169,12 @@ public function guessTypeForConstraint(Constraint $constraint): ?TypeGuess */ public function guessRequiredForConstraint(Constraint $constraint): ?ValueGuess { - switch (\get_class($constraint)) { - case 'Symfony\Component\Validator\Constraints\NotNull': - case 'Symfony\Component\Validator\Constraints\NotBlank': - case 'Symfony\Component\Validator\Constraints\IsTrue': - return new ValueGuess(true, Guess::HIGH_CONFIDENCE); - } - - return null; + return match (\get_class($constraint)) { + NotNull::class, + NotBlank::class, + IsTrue::class => new ValueGuess(true, Guess::HIGH_CONFIDENCE), + default => null, + }; } /** diff --git a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index 95f011899e..aac5736870 100644 --- a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -729,11 +729,11 @@ public function testCreateViewFlatAttrClosureReceivesKey() null, // index null, // group function ($object, $key) { - switch ($key) { - case 'B': return ['attr1' => 'value1']; - case 'C': return ['attr2' => 'value2']; - default: return []; - } + return match ($key) { + 'B' => ['attr1' => 'value1'], + 'C' => ['attr2' => 'value2'], + default => [], + }; } ); @@ -749,11 +749,11 @@ public function testCreateViewFlatAttrClosureReceivesValue() null, // index null, // group function ($object, $key, $value) { - switch ($value) { - case '1': return ['attr1' => 'value1']; - case '2': return ['attr2' => 'value2']; - default: return []; - } + return match ($value) { + '1' => ['attr1' => 'value1'], + '2' => ['attr2' => 'value2'], + default => [], + }; } ); @@ -852,10 +852,10 @@ public function testCreateViewFlatlabelTranslationParametersClosureReceivesKey() null, // group null, // attr function ($object, $key) { - switch ($key) { - case 'D': return ['%placeholder1%' => 'value1']; - default: return []; - } + return match ($key) { + 'D' => ['%placeholder1%' => 'value1'], + default => [], + }; } ); @@ -872,10 +872,10 @@ public function testCreateViewFlatlabelTranslationParametersClosureReceivesValue null, // group null, // attr function ($object, $key, $value) { - switch ($value) { - case '3': return ['%placeholder1%' => 'value1']; - default: return []; - } + return match ($value) { + '3' => ['%placeholder1%' => 'value1'], + default => [], + }; } ); From 78cba1f6075b37afd70ec926bd1cc20194a5efff Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Sun, 20 Feb 2022 16:28:15 +0100 Subject: [PATCH 037/208] Use ::class instead of FQCN --- Extension/Core/Type/FileType.php | 5 +- .../HttpFoundationRequestHandler.php | 2 +- Extension/Validator/ValidatorExtension.php | 2 +- Extension/Validator/ValidatorTypeGuesser.php | 127 +++++++++++------- 4 files changed, 85 insertions(+), 51 deletions(-) diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index 89f70bcde8..e78822dca4 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -18,6 +18,7 @@ use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; +use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Contracts\Translation\TranslatorInterface; @@ -114,9 +115,9 @@ public function finishView(FormView $view, FormInterface $form, array $options) public function configureOptions(OptionsResolver $resolver) { $dataClass = null; - if (class_exists(\Symfony\Component\HttpFoundation\File\File::class)) { + if (class_exists(File::class)) { $dataClass = function (Options $options) { - return $options['multiple'] ? null : 'Symfony\Component\HttpFoundation\File\File'; + return $options['multiple'] ? null : File::class; }; } diff --git a/Extension/HttpFoundation/HttpFoundationRequestHandler.php b/Extension/HttpFoundation/HttpFoundationRequestHandler.php index 7180bafd81..17317c780f 100644 --- a/Extension/HttpFoundation/HttpFoundationRequestHandler.php +++ b/Extension/HttpFoundation/HttpFoundationRequestHandler.php @@ -41,7 +41,7 @@ public function __construct(ServerParams $serverParams = null) public function handleRequest(FormInterface $form, mixed $request = null) { if (!$request instanceof Request) { - throw new UnexpectedTypeException($request, 'Symfony\Component\HttpFoundation\Request'); + throw new UnexpectedTypeException($request, Request::class); } $name = $form->getName(); diff --git a/Extension/Validator/ValidatorExtension.php b/Extension/Validator/ValidatorExtension.php index 3a0ec662a1..fe1bd33f5f 100644 --- a/Extension/Validator/ValidatorExtension.php +++ b/Extension/Validator/ValidatorExtension.php @@ -36,7 +36,7 @@ public function __construct(ValidatorInterface $validator, bool $legacyErrorMess { $this->legacyErrorMessages = $legacyErrorMessages; - $metadata = $validator->getMetadataFor('Symfony\Component\Form\Form'); + $metadata = $validator->getMetadataFor(\Symfony\Component\Form\Form::class); // Register the form constraints in the validator programmatically. // This functionality is required when using the Form component without diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index dd4f8c7684..5eba3a291a 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -11,14 +11,47 @@ namespace Symfony\Component\Form\Extension\Validator; +use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\Form\Extension\Core\Type\CollectionType; +use Symfony\Component\Form\Extension\Core\Type\CountryType; +use Symfony\Component\Form\Extension\Core\Type\CurrencyType; +use Symfony\Component\Form\Extension\Core\Type\DateTimeType; +use Symfony\Component\Form\Extension\Core\Type\DateType; +use Symfony\Component\Form\Extension\Core\Type\EmailType; +use Symfony\Component\Form\Extension\Core\Type\FileType; +use Symfony\Component\Form\Extension\Core\Type\IntegerType; +use Symfony\Component\Form\Extension\Core\Type\LanguageType; +use Symfony\Component\Form\Extension\Core\Type\LocaleType; +use Symfony\Component\Form\Extension\Core\Type\NumberType; +use Symfony\Component\Form\Extension\Core\Type\TextType; +use Symfony\Component\Form\Extension\Core\Type\TimeType; +use Symfony\Component\Form\Extension\Core\Type\UrlType; use Symfony\Component\Form\FormTypeGuesserInterface; use Symfony\Component\Form\Guess\Guess; use Symfony\Component\Form\Guess\TypeGuess; use Symfony\Component\Form\Guess\ValueGuess; use Symfony\Component\Validator\Constraint; +use Symfony\Component\Validator\Constraints\Count; +use Symfony\Component\Validator\Constraints\Country; +use Symfony\Component\Validator\Constraints\Currency; +use Symfony\Component\Validator\Constraints\Date; +use Symfony\Component\Validator\Constraints\DateTime; +use Symfony\Component\Validator\Constraints\Email; +use Symfony\Component\Validator\Constraints\File; +use Symfony\Component\Validator\Constraints\Image; +use Symfony\Component\Validator\Constraints\Ip; +use Symfony\Component\Validator\Constraints\IsFalse; use Symfony\Component\Validator\Constraints\IsTrue; +use Symfony\Component\Validator\Constraints\Language; +use Symfony\Component\Validator\Constraints\Length; +use Symfony\Component\Validator\Constraints\Locale; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\NotNull; +use Symfony\Component\Validator\Constraints\Range; +use Symfony\Component\Validator\Constraints\Regex; +use Symfony\Component\Validator\Constraints\Time; +use Symfony\Component\Validator\Constraints\Type; +use Symfony\Component\Validator\Constraints\Url; use Symfony\Component\Validator\Mapping\ClassMetadataInterface; use Symfony\Component\Validator\Mapping\Factory\MetadataFactoryInterface; @@ -79,86 +112,86 @@ public function guessPattern(string $class, string $property): ?ValueGuess public function guessTypeForConstraint(Constraint $constraint): ?TypeGuess { switch (\get_class($constraint)) { - case 'Symfony\Component\Validator\Constraints\Type': + case Type::class: switch ($constraint->type) { case 'array': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CollectionType', [], Guess::MEDIUM_CONFIDENCE); + return new TypeGuess(CollectionType::class, [], Guess::MEDIUM_CONFIDENCE); case 'boolean': case 'bool': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CheckboxType', [], Guess::MEDIUM_CONFIDENCE); + return new TypeGuess(CheckboxType::class, [], Guess::MEDIUM_CONFIDENCE); case 'double': case 'float': case 'numeric': case 'real': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\NumberType', [], Guess::MEDIUM_CONFIDENCE); + return new TypeGuess(NumberType::class, [], Guess::MEDIUM_CONFIDENCE); case 'integer': case 'int': case 'long': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\IntegerType', [], Guess::MEDIUM_CONFIDENCE); + return new TypeGuess(IntegerType::class, [], Guess::MEDIUM_CONFIDENCE); case \DateTime::class: case '\DateTime': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateType', [], Guess::MEDIUM_CONFIDENCE); + return new TypeGuess(DateType::class, [], Guess::MEDIUM_CONFIDENCE); case 'string': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', [], Guess::LOW_CONFIDENCE); + return new TypeGuess(TextType::class, [], Guess::LOW_CONFIDENCE); } break; - case 'Symfony\Component\Validator\Constraints\Country': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CountryType', [], Guess::HIGH_CONFIDENCE); + case Country::class: + return new TypeGuess(CountryType::class, [], Guess::HIGH_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\Currency': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CurrencyType', [], Guess::HIGH_CONFIDENCE); + case Currency::class: + return new TypeGuess(CurrencyType::class, [], Guess::HIGH_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\Date': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateType', ['input' => 'string'], Guess::HIGH_CONFIDENCE); + case Date::class: + return new TypeGuess(DateType::class, ['input' => 'string'], Guess::HIGH_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\DateTime': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateTimeType', ['input' => 'string'], Guess::HIGH_CONFIDENCE); + case DateTime::class: + return new TypeGuess(DateTimeType::class, ['input' => 'string'], Guess::HIGH_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\Email': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\EmailType', [], Guess::HIGH_CONFIDENCE); + case Email::class: + return new TypeGuess(EmailType::class, [], Guess::HIGH_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\File': - case 'Symfony\Component\Validator\Constraints\Image': + case File::class: + case Image::class: $options = []; if ($constraint->mimeTypes) { $options = ['attr' => ['accept' => implode(',', (array) $constraint->mimeTypes)]]; } - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\FileType', $options, Guess::HIGH_CONFIDENCE); + return new TypeGuess(FileType::class, $options, Guess::HIGH_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\Language': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\LanguageType', [], Guess::HIGH_CONFIDENCE); + case Language::class: + return new TypeGuess(LanguageType::class, [], Guess::HIGH_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\Locale': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\LocaleType', [], Guess::HIGH_CONFIDENCE); + case Locale::class: + return new TypeGuess(LocaleType::class, [], Guess::HIGH_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\Time': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TimeType', ['input' => 'string'], Guess::HIGH_CONFIDENCE); + case Time::class: + return new TypeGuess(TimeType::class, ['input' => 'string'], Guess::HIGH_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\Url': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\UrlType', [], Guess::HIGH_CONFIDENCE); + case Url::class: + return new TypeGuess(UrlType::class, [], Guess::HIGH_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\Ip': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', [], Guess::MEDIUM_CONFIDENCE); + case Ip::class: + return new TypeGuess(TextType::class, [], Guess::MEDIUM_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\Length': - case 'Symfony\Component\Validator\Constraints\Regex': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', [], Guess::LOW_CONFIDENCE); + case Length::class: + case Regex::class: + return new TypeGuess(TextType::class, [], Guess::LOW_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\Range': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\NumberType', [], Guess::LOW_CONFIDENCE); + case Range::class: + return new TypeGuess(NumberType::class, [], Guess::LOW_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\Count': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CollectionType', [], Guess::LOW_CONFIDENCE); + case Count::class: + return new TypeGuess(CollectionType::class, [], Guess::LOW_CONFIDENCE); - case 'Symfony\Component\Validator\Constraints\IsTrue': - case 'Symfony\Component\Validator\Constraints\IsFalse': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CheckboxType', [], Guess::MEDIUM_CONFIDENCE); + case IsTrue::class: + case IsFalse::class: + return new TypeGuess(CheckboxType::class, [], Guess::MEDIUM_CONFIDENCE); } return null; @@ -183,19 +216,19 @@ public function guessRequiredForConstraint(Constraint $constraint): ?ValueGuess public function guessMaxLengthForConstraint(Constraint $constraint): ?ValueGuess { switch (\get_class($constraint)) { - case 'Symfony\Component\Validator\Constraints\Length': + case Length::class: if (is_numeric($constraint->max)) { return new ValueGuess($constraint->max, Guess::HIGH_CONFIDENCE); } break; - case 'Symfony\Component\Validator\Constraints\Type': + case Type::class: if (\in_array($constraint->type, ['double', 'float', 'numeric', 'real'])) { return new ValueGuess(null, Guess::MEDIUM_CONFIDENCE); } break; - case 'Symfony\Component\Validator\Constraints\Range': + case Range::class: if (is_numeric($constraint->max)) { return new ValueGuess(\strlen((string) $constraint->max), Guess::LOW_CONFIDENCE); } @@ -211,13 +244,13 @@ public function guessMaxLengthForConstraint(Constraint $constraint): ?ValueGuess public function guessPatternForConstraint(Constraint $constraint): ?ValueGuess { switch (\get_class($constraint)) { - case 'Symfony\Component\Validator\Constraints\Length': + case Length::class: if (is_numeric($constraint->min)) { return new ValueGuess(sprintf('.{%s,}', (string) $constraint->min), Guess::LOW_CONFIDENCE); } break; - case 'Symfony\Component\Validator\Constraints\Regex': + case Regex::class: $htmlPattern = $constraint->getHtmlPattern(); if (null !== $htmlPattern) { @@ -225,13 +258,13 @@ public function guessPatternForConstraint(Constraint $constraint): ?ValueGuess } break; - case 'Symfony\Component\Validator\Constraints\Range': + case Range::class: if (is_numeric($constraint->min)) { return new ValueGuess(sprintf('.{%s,}', \strlen((string) $constraint->min)), Guess::LOW_CONFIDENCE); } break; - case 'Symfony\Component\Validator\Constraints\Type': + case Type::class: if (\in_array($constraint->type, ['double', 'float', 'numeric', 'real'])) { return new ValueGuess(null, Guess::MEDIUM_CONFIDENCE); } From c57c2ebc21aac3200c365b4b09e71325aec4f066 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 9 Feb 2022 15:00:38 +0100 Subject: [PATCH 038/208] Bump minimum version of PHP to 8.1 --- CallbackTransformer.php | 4 ++-- ChoiceList/Factory/Cache/AbstractStaticOption.php | 2 +- ChoiceList/LazyChoiceList.php | 2 +- ChoiceList/Loader/CallbackChoiceLoader.php | 2 +- ChoiceList/Loader/FilterChoiceLoaderDecorator.php | 2 +- Command/DebugCommand.php | 1 - Console/Descriptor/TextDescriptor.php | 10 +++++----- .../Core/EventListener/ResizeFormListener.php | 2 +- Extension/Core/Type/EnumType.php | 2 +- FormConfigBuilder.php | 2 +- Tests/AbstractFormTest.php | 10 ++-------- Tests/Command/DebugCommandTest.php | 1 - Tests/Extension/Core/Type/EnumTypeTest.php | 5 +---- Tests/FormBuilderTest.php | 3 --- Tests/FormFactoryBuilderTest.php | 1 - Tests/ResolvedFormTypeTest.php | 15 +++------------ composer.json | 3 +-- 17 files changed, 21 insertions(+), 46 deletions(-) diff --git a/CallbackTransformer.php b/CallbackTransformer.php index c5ec2a1050..8870526b8f 100644 --- a/CallbackTransformer.php +++ b/CallbackTransformer.php @@ -18,8 +18,8 @@ class CallbackTransformer implements DataTransformerInterface public function __construct(callable $transform, callable $reverseTransform) { - $this->transform = $transform instanceof \Closure ? $transform : \Closure::fromCallable($transform); - $this->reverseTransform = $reverseTransform instanceof \Closure ? $reverseTransform : \Closure::fromCallable($reverseTransform); + $this->transform = $transform(...); + $this->reverseTransform = $reverseTransform(...); } /** diff --git a/ChoiceList/Factory/Cache/AbstractStaticOption.php b/ChoiceList/Factory/Cache/AbstractStaticOption.php index 5ccdbdb22e..2686017c91 100644 --- a/ChoiceList/Factory/Cache/AbstractStaticOption.php +++ b/ChoiceList/Factory/Cache/AbstractStaticOption.php @@ -40,7 +40,7 @@ final public function __construct(FormTypeInterface|FormTypeExtensionInterface $ { $hash = CachingFactoryDecorator::generateHash([static::class, $formType, $vary]); - $this->option = self::$options[$hash] ??= $option instanceof \Closure || !\is_callable($option) ? $option : \Closure::fromCallable($option); + $this->option = self::$options[$hash] ??= $option instanceof \Closure || \is_string($option) || \is_bool($option) || $option instanceof ChoiceLoaderInterface || !\is_callable($option) ? $option : $option(...); } final public function getOption(): mixed diff --git a/ChoiceList/LazyChoiceList.php b/ChoiceList/LazyChoiceList.php index e339bcd249..dd545430cf 100644 --- a/ChoiceList/LazyChoiceList.php +++ b/ChoiceList/LazyChoiceList.php @@ -48,7 +48,7 @@ class LazyChoiceList implements ChoiceListInterface public function __construct(ChoiceLoaderInterface $loader, callable $value = null) { $this->loader = $loader; - $this->value = null === $value || $value instanceof \Closure ? $value : \Closure::fromCallable($value); + $this->value = null === $value ? null : $value(...); } /** diff --git a/ChoiceList/Loader/CallbackChoiceLoader.php b/ChoiceList/Loader/CallbackChoiceLoader.php index 991b13407e..088f91dae2 100644 --- a/ChoiceList/Loader/CallbackChoiceLoader.php +++ b/ChoiceList/Loader/CallbackChoiceLoader.php @@ -25,7 +25,7 @@ class CallbackChoiceLoader extends AbstractChoiceLoader */ public function __construct(callable $callback) { - $this->callback = $callback instanceof \Closure ? $callback : \Closure::fromCallable($callback); + $this->callback = $callback(...); } protected function loadChoices(): iterable diff --git a/ChoiceList/Loader/FilterChoiceLoaderDecorator.php b/ChoiceList/Loader/FilterChoiceLoaderDecorator.php index 12e6d0e2a1..277aba0cf2 100644 --- a/ChoiceList/Loader/FilterChoiceLoaderDecorator.php +++ b/ChoiceList/Loader/FilterChoiceLoaderDecorator.php @@ -24,7 +24,7 @@ class FilterChoiceLoaderDecorator extends AbstractChoiceLoader public function __construct(ChoiceLoaderInterface $loader, callable $filter) { $this->decoratedLoader = $loader; - $this->filter = $filter instanceof \Closure ? $filter : \Closure::fromCallable($filter); + $this->filter = $filter(...); } protected function loadChoices(): iterable diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index c58dc2217d..d30a547ce8 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -209,7 +209,6 @@ private function getCoreTypes(): array { $coreExtension = new CoreExtension(); $loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes'); - $loadTypesRefMethod->setAccessible(true); $coreTypes = $loadTypesRefMethod->invoke($coreExtension); $coreTypes = array_map(function (FormTypeInterface $type) { return \get_class($type); }, $coreTypes); sort($coreTypes); diff --git a/Console/Descriptor/TextDescriptor.php b/Console/Descriptor/TextDescriptor.php index ba79d806ad..c1991e3aed 100644 --- a/Console/Descriptor/TextDescriptor.php +++ b/Console/Descriptor/TextDescriptor.php @@ -45,18 +45,18 @@ protected function describeDefaults(array $options) if ($options['service_types']) { $this->output->section('Service form types'); - $this->output->listing(array_map([$this, 'formatClassLink'], $options['service_types'])); + $this->output->listing(array_map($this->formatClassLink(...), $options['service_types'])); } if (!$options['show_deprecated']) { if ($options['extensions']) { $this->output->section('Type extensions'); - $this->output->listing(array_map([$this, 'formatClassLink'], $options['extensions'])); + $this->output->listing(array_map($this->formatClassLink(...), $options['extensions'])); } if ($options['guessers']) { $this->output->section('Type guessers'); - $this->output->listing(array_map([$this, 'formatClassLink'], $options['guessers'])); + $this->output->listing(array_map($this->formatClassLink(...), $options['guessers'])); } } } @@ -92,12 +92,12 @@ protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedF if ($this->parents) { $this->output->section('Parent types'); - $this->output->listing(array_map([$this, 'formatClassLink'], $this->parents)); + $this->output->listing(array_map($this->formatClassLink(...), $this->parents)); } if ($this->extensions) { $this->output->section('Type extensions'); - $this->output->listing(array_map([$this, 'formatClassLink'], $this->extensions)); + $this->output->listing(array_map($this->formatClassLink(...), $this->extensions)); } } diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index 8cbfa8b36b..c5258469c3 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -37,7 +37,7 @@ public function __construct(string $type, array $options = [], bool $allowAdd = $this->allowAdd = $allowAdd; $this->allowDelete = $allowDelete; $this->options = $options; - $this->deleteEmpty = $deleteEmpty instanceof \Closure || !\is_callable($deleteEmpty) ? $deleteEmpty : \Closure::fromCallable($deleteEmpty); + $this->deleteEmpty = \is_bool($deleteEmpty) ? $deleteEmpty : $deleteEmpty(...); } public static function getSubscribedEvents(): array diff --git a/Extension/Core/Type/EnumType.php b/Extension/Core/Type/EnumType.php index c251cdbd00..33944c2aec 100644 --- a/Extension/Core/Type/EnumType.php +++ b/Extension/Core/Type/EnumType.php @@ -27,7 +27,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver ->setRequired(['class']) ->setAllowedTypes('class', 'string') - ->setAllowedValues('class', \Closure::fromCallable('enum_exists')) + ->setAllowedValues('class', enum_exists(...)) ->setDefault('choices', static function (Options $options): array { return $options['class']::cases(); }) diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 9bbe7abcc4..4a03594e0d 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -729,7 +729,7 @@ public function getFormConfig(): FormConfigInterface */ public function setIsEmptyCallback(?callable $isEmptyCallback): static { - $this->isEmptyCallback = null === $isEmptyCallback || $isEmptyCallback instanceof \Closure ? $isEmptyCallback : \Closure::fromCallable($isEmptyCallback); + $this->isEmptyCallback = null === $isEmptyCallback ? null : $isEmptyCallback(...); return $this; } diff --git a/Tests/AbstractFormTest.php b/Tests/AbstractFormTest.php index 193bb31b15..5408416191 100644 --- a/Tests/AbstractFormTest.php +++ b/Tests/AbstractFormTest.php @@ -59,18 +59,12 @@ protected function getBuilder(?string $name = 'name', EventDispatcherInterface $ return new FormBuilder($name, $dataClass, $dispatcher ?: $this->dispatcher, $this->factory, $options); } - /** - * @return MockObject&DataMapperInterface - */ - protected function getDataMapper(): DataMapperInterface + protected function getDataMapper(): MockObject&DataMapperInterface { return $this->createMock(DataMapperInterface::class); } - /** - * @return MockObject&DataTransformerInterface - */ - protected function getDataTransformer(): DataTransformerInterface + protected function getDataTransformer(): MockObject&DataTransformerInterface { return $this->createMock(DataTransformerInterface::class); } diff --git a/Tests/Command/DebugCommandTest.php b/Tests/Command/DebugCommandTest.php index 5e18de686c..be54d2350d 100644 --- a/Tests/Command/DebugCommandTest.php +++ b/Tests/Command/DebugCommandTest.php @@ -266,7 +266,6 @@ private function getCoreTypes(): array { $coreExtension = new CoreExtension(); $loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes'); - $loadTypesRefMethod->setAccessible(true); $coreTypes = $loadTypesRefMethod->invoke($coreExtension); $coreTypes = array_map(function (FormTypeInterface $type) { return \get_class($type); }, $coreTypes); sort($coreTypes); diff --git a/Tests/Extension/Core/Type/EnumTypeTest.php b/Tests/Extension/Core/Type/EnumTypeTest.php index 083952a332..f571d631b4 100644 --- a/Tests/Extension/Core/Type/EnumTypeTest.php +++ b/Tests/Extension/Core/Type/EnumTypeTest.php @@ -19,10 +19,7 @@ use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; -/** - * @requires PHP 8.1 - */ -final class EnumTypeTest extends BaseTypeTest +class EnumTypeTest extends BaseTypeTest { public const TESTED_TYPE = EnumType::class; diff --git a/Tests/FormBuilderTest.php b/Tests/FormBuilderTest.php index e68d3c7b1a..2213e07874 100644 --- a/Tests/FormBuilderTest.php +++ b/Tests/FormBuilderTest.php @@ -204,9 +204,6 @@ public function testGetFormConfigErasesReferences() $children = $reflClass->getProperty('children'); $unresolvedChildren = $reflClass->getProperty('unresolvedChildren'); - $children->setAccessible(true); - $unresolvedChildren->setAccessible(true); - $this->assertEmpty($children->getValue($config)); $this->assertEmpty($unresolvedChildren->getValue($config)); } diff --git a/Tests/FormFactoryBuilderTest.php b/Tests/FormFactoryBuilderTest.php index 9f4825e3fc..c53badd9b9 100644 --- a/Tests/FormFactoryBuilderTest.php +++ b/Tests/FormFactoryBuilderTest.php @@ -27,7 +27,6 @@ protected function setUp(): void { $factory = new \ReflectionClass(FormFactory::class); $this->registry = $factory->getProperty('registry'); - $this->registry->setAccessible(true); $this->guesser = $this->createMock(FormTypeGuesserInterface::class); $this->type = new FooType(); diff --git a/Tests/ResolvedFormTypeTest.php b/Tests/ResolvedFormTypeTest.php index b0a7617847..e6e5ee87f8 100644 --- a/Tests/ResolvedFormTypeTest.php +++ b/Tests/ResolvedFormTypeTest.php @@ -373,26 +373,17 @@ public function provideTypeClassBlockPrefixTuples() ]; } - /** - * @return MockObject&FormTypeInterface - */ - private function getMockFormType($typeClass = AbstractType::class): FormTypeInterface + private function getMockFormType($typeClass = AbstractType::class): MockObject&FormTypeInterface { return $this->getMockBuilder($typeClass)->setMethods(['getBlockPrefix', 'configureOptions', 'finishView', 'buildView', 'buildForm'])->getMock(); } - /** - * @return MockObject&FormTypeExtensionInterface - */ - private function getMockFormTypeExtension(): FormTypeExtensionInterface + private function getMockFormTypeExtension(): MockObject&FormTypeExtensionInterface { return $this->getMockBuilder(AbstractTypeExtension::class)->setMethods(['getExtendedTypes', 'configureOptions', 'finishView', 'buildView', 'buildForm'])->getMock(); } - /** - * @return MockObject&FormFactoryInterface - */ - private function getMockFormFactory(): FormFactoryInterface + private function getMockFormFactory(): MockObject&FormFactoryInterface { return $this->createMock(FormFactoryInterface::class); } diff --git a/composer.json b/composer.json index 9bdf5a8778..6fb2b50866 100644 --- a/composer.json +++ b/composer.json @@ -16,14 +16,13 @@ } ], "require": { - "php": ">=8.0.2", + "php": ">=8.1", "symfony/deprecation-contracts": "^2.1|^3", "symfony/event-dispatcher": "^5.4|^6.0", "symfony/options-resolver": "^5.4|^6.0", "symfony/polyfill-ctype": "~1.8", "symfony/polyfill-intl-icu": "^1.21", "symfony/polyfill-mbstring": "~1.0", - "symfony/polyfill-php81": "^1.23", "symfony/property-access": "^5.4|^6.0", "symfony/service-contracts": "^1.1|^2|^3" }, From b9f2987ddb9acc9b442fbc0da5c978903e812193 Mon Sep 17 00:00:00 2001 From: Tijs Verkoyen Date: Thu, 17 Mar 2022 15:30:44 +0100 Subject: [PATCH 039/208] [TwigBridge] Use a div instead of p to prevent invalid HTML --- Tests/AbstractLayoutTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/AbstractLayoutTest.php b/Tests/AbstractLayoutTest.php index 4b5d18b867..8e191bd1c7 100644 --- a/Tests/AbstractLayoutTest.php +++ b/Tests/AbstractLayoutTest.php @@ -432,7 +432,7 @@ public function testHelp() $html = $this->renderHelp($view); $this->assertMatchesXpath($html, -'/p +'/div [@id="name_help"] [@class="help-text"] [.="[trans]Help text test![/trans]"] From 73b8062176d8ab6fc4c9d6776374a512bd9375a2 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 24 Mar 2022 19:10:40 +0100 Subject: [PATCH 040/208] [Form] keep compat with older tests --- Tests/AbstractLayoutTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/AbstractLayoutTest.php b/Tests/AbstractLayoutTest.php index 8e191bd1c7..28f8520d5f 100644 --- a/Tests/AbstractLayoutTest.php +++ b/Tests/AbstractLayoutTest.php @@ -432,7 +432,7 @@ public function testHelp() $html = $this->renderHelp($view); $this->assertMatchesXpath($html, -'/div +'/*[self::div or self::p] [@id="name_help"] [@class="help-text"] [.="[trans]Help text test![/trans]"] From b802731de9753a9dfbd8243c93c27e8cb026fa45 Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Thu, 31 Mar 2022 18:23:12 +0200 Subject: [PATCH 041/208] Leverage non-capturing catches --- ChoiceList/Factory/PropertyAccessDecorator.php | 4 ++-- Console/Descriptor/Descriptor.php | 2 +- Console/Descriptor/TextDescriptor.php | 2 +- Extension/Core/Type/LanguageType.php | 2 +- FormRegistry.php | 2 +- Util/OptionsResolverWrapper.php | 10 +++++----- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index 8a678e7e18..3da57ecfbf 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -148,7 +148,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = $preferredChoices = function ($choice) use ($accessor, $preferredChoices) { try { return $accessor->getValue($choice, $preferredChoices); - } catch (UnexpectedTypeException $e) { + } catch (UnexpectedTypeException) { // Assume not preferred if not readable return false; } @@ -173,7 +173,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = $groupBy = function ($choice) use ($accessor, $groupBy) { try { return $accessor->getValue($choice, $groupBy); - } catch (UnexpectedTypeException $e) { + } catch (UnexpectedTypeException) { // Don't group if path is not readable return null; } diff --git a/Console/Descriptor/Descriptor.php b/Console/Descriptor/Descriptor.php index 50a9351fbe..975ae405f6 100644 --- a/Console/Descriptor/Descriptor.php +++ b/Console/Descriptor/Descriptor.php @@ -135,7 +135,7 @@ protected function getOptionDefinition(OptionsResolver $optionsResolver, string foreach ($map as $key => $method) { try { $definition[$key] = $introspector->{$method}($option); - } catch (NoConfigurationException $e) { + } catch (NoConfigurationException) { // noop } } diff --git a/Console/Descriptor/TextDescriptor.php b/Console/Descriptor/TextDescriptor.php index c1991e3aed..497167ddd7 100644 --- a/Console/Descriptor/TextDescriptor.php +++ b/Console/Descriptor/TextDescriptor.php @@ -213,7 +213,7 @@ private function getFileLink(string $class): string try { $r = new \ReflectionClass($class); - } catch (\ReflectionException $e) { + } catch (\ReflectionException) { return ''; } diff --git a/Extension/Core/Type/LanguageType.php b/Extension/Core/Type/LanguageType.php index ef6486f06e..b1184a4309 100644 --- a/Extension/Core/Type/LanguageType.php +++ b/Extension/Core/Type/LanguageType.php @@ -43,7 +43,7 @@ public function configureOptions(OptionsResolver $resolver) try { $languageCode = $useAlpha3Codes ? Languages::getAlpha3Code($alpha2Code) : $alpha2Code; $languagesList[$languageCode] = Languages::getName($alpha2Code, $alpha2Code); - } catch (MissingResourceException $e) { + } catch (MissingResourceException) { // ignore errors like "Couldn't read the indices for the locale 'meta'" } } diff --git a/FormRegistry.php b/FormRegistry.php index acd392d337..5453c6d356 100644 --- a/FormRegistry.php +++ b/FormRegistry.php @@ -129,7 +129,7 @@ public function hasType(string $name): bool try { $this->getType($name); - } catch (ExceptionInterface $e) { + } catch (ExceptionInterface) { return false; } diff --git a/Util/OptionsResolverWrapper.php b/Util/OptionsResolverWrapper.php index 9819074eed..51cba4e08f 100644 --- a/Util/OptionsResolverWrapper.php +++ b/Util/OptionsResolverWrapper.php @@ -31,7 +31,7 @@ public function setNormalizer(string $option, \Closure $normalizer): static { try { parent::setNormalizer($option, $normalizer); - } catch (UndefinedOptionsException $e) { + } catch (UndefinedOptionsException) { $this->undefined[$option] = true; } @@ -45,7 +45,7 @@ public function setAllowedValues(string $option, mixed $allowedValues): static { try { parent::setAllowedValues($option, $allowedValues); - } catch (UndefinedOptionsException $e) { + } catch (UndefinedOptionsException) { $this->undefined[$option] = true; } @@ -59,7 +59,7 @@ public function addAllowedValues(string $option, mixed $allowedValues): static { try { parent::addAllowedValues($option, $allowedValues); - } catch (UndefinedOptionsException $e) { + } catch (UndefinedOptionsException) { $this->undefined[$option] = true; } @@ -75,7 +75,7 @@ public function setAllowedTypes(string $option, $allowedTypes): static { try { parent::setAllowedTypes($option, $allowedTypes); - } catch (UndefinedOptionsException $e) { + } catch (UndefinedOptionsException) { $this->undefined[$option] = true; } @@ -91,7 +91,7 @@ public function addAllowedTypes(string $option, $allowedTypes): static { try { parent::addAllowedTypes($option, $allowedTypes); - } catch (UndefinedOptionsException $e) { + } catch (UndefinedOptionsException) { $this->undefined[$option] = true; } From 1d88387fa4aeb497bcc8122137f9168c0a6cea76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20K=C3=A4fer?= Date: Sat, 2 Apr 2022 20:30:07 +0200 Subject: [PATCH 042/208] [Form] Add prototype_options to CollectionType --- CHANGELOG.md | 5 +++++ Extension/Core/Type/CollectionType.php | 5 ++++- .../Extension/Core/Type/CollectionTypeTest.php | 17 +++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22b9c84f2a..f2f949c897 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +6.1 +--- + + * Add a `prototype_options` option to `CollectionType` + 6.0 --- diff --git a/Extension/Core/Type/CollectionType.php b/Extension/Core/Type/CollectionType.php index 480d31dc94..4ec0f1be70 100644 --- a/Extension/Core/Type/CollectionType.php +++ b/Extension/Core/Type/CollectionType.php @@ -30,7 +30,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) $prototypeOptions = array_replace([ 'required' => $options['required'], 'label' => $options['prototype_name'].'label__', - ], $options['entry_options']); + ], array_replace($options['entry_options'], $options['prototype_options'])); if (null !== $options['prototype_data']) { $prototypeOptions['data'] = $options['prototype_data']; @@ -120,12 +120,15 @@ public function configureOptions(OptionsResolver $resolver) 'prototype_name' => '__name__', 'entry_type' => TextType::class, 'entry_options' => [], + 'prototype_options' => [], 'delete_empty' => false, 'invalid_message' => 'The collection is invalid.', ]); $resolver->setNormalizer('entry_options', $entryOptionsNormalizer); + $resolver->setAllowedTypes('delete_empty', ['bool', 'callable']); + $resolver->setAllowedTypes('prototype_options', 'array'); } /** diff --git a/Tests/Extension/Core/Type/CollectionTypeTest.php b/Tests/Extension/Core/Type/CollectionTypeTest.php index b7e68ba0d0..129c2c97b9 100644 --- a/Tests/Extension/Core/Type/CollectionTypeTest.php +++ b/Tests/Extension/Core/Type/CollectionTypeTest.php @@ -430,6 +430,23 @@ public function testPrototypeNotOverrideRequiredByEntryOptionsInFavorOfParent() $this->assertFalse($child->createView()->vars['prototype']->vars['required'], '"Prototype" should not be required'); } + public function testPrototypeOptionsOverrideEntryOptions() + { + $form = $this->factory->create(static::TESTED_TYPE, [], [ + 'allow_add' => true, + 'prototype' => true, + 'entry_type' => TextTypeTest::TESTED_TYPE, + 'entry_options' => [ + 'help' => null, + ], + 'prototype_options' => [ + 'help' => 'foo', + ], + ]); + + $this->assertSame('foo', $form->createView()->vars['prototype']->vars['help']); + } + public function testEntriesBlockPrefixes() { $collectionView = $this->factory->createNamed('fields', static::TESTED_TYPE, [''], [ From 96cef47e743174d19304201094937e0f924e8526 Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Fri, 8 Apr 2022 18:15:24 +0200 Subject: [PATCH 043/208] Leverage array_is_list(), get_debug_type(), is_countable(), is_iterable(), str_contains() and str_starts_with() --- Form.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Form.php b/Form.php index 394f6a89f2..f404aece25 100644 --- a/Form.php +++ b/Form.php @@ -704,7 +704,7 @@ public function isEmpty(): bool return FormUtil::isEmpty($this->modelData) || // arrays, countables - ((\is_array($this->modelData) || $this->modelData instanceof \Countable) && 0 === \count($this->modelData)) || + (is_countable($this->modelData) && 0 === \count($this->modelData)) || // traversables that are not countable ($this->modelData instanceof \Traversable && 0 === iterator_count($this->modelData)); } From ebf7b746160cf3597867b44f95ddf4b7f5ca29eb Mon Sep 17 00:00:00 2001 From: Maxime Pinot Date: Fri, 15 Apr 2022 10:48:25 +0200 Subject: [PATCH 044/208] Remove useless condition --- FormBuilder.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/FormBuilder.php b/FormBuilder.php index 37fca950a7..42020c921e 100644 --- a/FormBuilder.php +++ b/FormBuilder.php @@ -69,10 +69,6 @@ public function add($child, string $type = null, array $options = []) throw new UnexpectedTypeException($child, 'string or Symfony\Component\Form\FormBuilderInterface'); } - if (null !== $type && !\is_string($type)) { - throw new UnexpectedTypeException($type, 'string or null'); - } - // Add to "children" to maintain order $this->children[$child] = null; $this->unresolvedChildren[$child] = [$type, $options]; From 26f6c54ab5c5eb58b379d2bc5e2d6a71fedac11b Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Fri, 15 Apr 2022 15:56:01 +0200 Subject: [PATCH 045/208] Clean skippable tests that are never skipped --- Tests/Command/DebugCommandTest.php | 4 ---- Tests/FormErrorIteratorTest.php | 4 ---- 2 files changed, 8 deletions(-) diff --git a/Tests/Command/DebugCommandTest.php b/Tests/Command/DebugCommandTest.php index be54d2350d..ad52a4fd25 100644 --- a/Tests/Command/DebugCommandTest.php +++ b/Tests/Command/DebugCommandTest.php @@ -189,10 +189,6 @@ class:%s */ public function testComplete(array $input, array $expectedSuggestions) { - if (!class_exists(CommandCompletionTester::class)) { - $this->markTestSkipped('Test command completion requires symfony/console 5.4+.'); - } - $formRegistry = new FormRegistry([], new ResolvedFormTypeFactory()); $command = new DebugCommand($formRegistry); $application = new Application(); diff --git a/Tests/FormErrorIteratorTest.php b/Tests/FormErrorIteratorTest.php index b818dcd8c4..b9add5877e 100644 --- a/Tests/FormErrorIteratorTest.php +++ b/Tests/FormErrorIteratorTest.php @@ -26,10 +26,6 @@ class FormErrorIteratorTest extends TestCase */ public function testFindByCodes($code, $violationsCount) { - if (!class_exists(ConstraintViolation::class)) { - $this->markTestSkipped('Validator component required.'); - } - $formBuilder = new FormBuilder( 'form', null, From b29ddc5e2d447c36b73d9140c56d33af16494cf1 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Sun, 17 Apr 2022 13:38:16 +0200 Subject: [PATCH 046/208] fix merge --- Tests/Fixtures/Map.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Tests/Fixtures/Map.php b/Tests/Fixtures/Map.php index 93409aceee..d3a9de6f92 100644 --- a/Tests/Fixtures/Map.php +++ b/Tests/Fixtures/Map.php @@ -20,11 +20,7 @@ public function offsetExists($offset): bool return isset($this->data[$offset]); } - /** - * @return mixed - */ - #[\ReturnTypeWillChange] - public function offsetGet($offset) + public function offsetGet($offset): mixed { return $this->data[$offset]; } From 5c765b6ece96c3f9ddc9637079016c082d588a9f Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Wed, 20 Apr 2022 17:01:42 +0200 Subject: [PATCH 047/208] Minor @requires function tests cleanup --- Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index 0fa93ba32d..f3c790aa0c 100644 --- a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -759,9 +759,6 @@ function ($object, $key, $value) { $this->assertFlatViewWithAttr($view); } - /** - * @requires function Symfony\Component\Translation\TranslatableMessage::__construct - */ public function testPassTranslatableMessageAsLabelDoesntCastItToString() { $view = $this->factory->createView( From c8ec6048931c8313a0b4acfb71b8cb405f7dd2a9 Mon Sep 17 00:00:00 2001 From: Maxime Pinot Date: Fri, 22 Apr 2022 10:06:46 +0200 Subject: [PATCH 048/208] Remove useless condition --- Form.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Form.php b/Form.php index f404aece25..fc2b3fdb66 100644 --- a/Form.php +++ b/Form.php @@ -818,10 +818,6 @@ public function add(FormInterface|string $child, string $type = null, array $opt $child = (string) $child; - if (null !== $type && !\is_string($type)) { - throw new UnexpectedTypeException($type, 'string or null'); - } - // Never initialize child forms automatically $options['auto_initialize'] = false; From 0020235fca8706e9d1272e2496dcd63f3d5041a0 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 12 May 2022 18:47:43 +0200 Subject: [PATCH 049/208] [FrameworkBundle][TwigBundle][Form] Add Twig filter, form-type extension and improve service definitions for HtmlSanitizer --- .../HtmlSanitizer/HtmlSanitizerExtension.php | 36 ++++++++++ .../Type/TextTypeHtmlSanitizerExtension.php | 66 +++++++++++++++++++ .../TextTypeHtmlSanitizerExtensionTest.php | 63 ++++++++++++++++++ composer.json | 1 + 4 files changed, 166 insertions(+) create mode 100644 Extension/HtmlSanitizer/HtmlSanitizerExtension.php create mode 100644 Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php create mode 100644 Tests/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtensionTest.php diff --git a/Extension/HtmlSanitizer/HtmlSanitizerExtension.php b/Extension/HtmlSanitizer/HtmlSanitizerExtension.php new file mode 100644 index 0000000000..6c4bf49d6a --- /dev/null +++ b/Extension/HtmlSanitizer/HtmlSanitizerExtension.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Extension\HtmlSanitizer; + +use Psr\Container\ContainerInterface; +use Symfony\Component\Form\AbstractExtension; + +/** + * Integrates the HtmlSanitizer component with the Form library. + * + * @author Nicolas Grekas + */ +class HtmlSanitizerExtension extends AbstractExtension +{ + public function __construct( + private ContainerInterface $sanitizers, + private string $defaultSanitizer = 'default', + ) { + } + + protected function loadTypeExtensions(): array + { + return [ + new Type\TextTypeHtmlSanitizerExtension($this->sanitizers, $this->defaultSanitizer), + ]; + } +} diff --git a/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php b/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php new file mode 100644 index 0000000000..0d28c65bce --- /dev/null +++ b/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php @@ -0,0 +1,66 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Extension\HtmlSanitizer\Type; + +use Psr\Container\ContainerInterface; +use Symfony\Component\Form\AbstractTypeExtension; +use Symfony\Component\Form\Extension\Core\Type\TextType; +use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\Form\FormEvent; +use Symfony\Component\Form\FormEvents; +use Symfony\Component\OptionsResolver\OptionsResolver; + +/** + * @author Titouan Galopin + */ +class TextTypeHtmlSanitizerExtension extends AbstractTypeExtension +{ + public function __construct( + private ContainerInterface $sanitizers, + private string $defaultSanitizer = 'default', + ) { + } + + public static function getExtendedTypes(): iterable + { + return [TextType::class]; + } + + public function configureOptions(OptionsResolver $resolver) + { + $resolver + ->setDefaults(['sanitize_html' => false, 'sanitizer' => null]) + ->setAllowedTypes('sanitize_html', 'bool') + ->setAllowedTypes('sanitizer', ['string', 'null']) + ; + } + + public function buildForm(FormBuilderInterface $builder, array $options) + { + if (!$options['sanitize_html']) { + return; + } + + $sanitizers = $this->sanitizers; + $sanitizer = $options['sanitizer'] ?? $this->defaultSanitizer; + + $builder->addEventListener( + FormEvents::PRE_SUBMIT, + static function (FormEvent $event) use ($sanitizers, $sanitizer) { + if (is_scalar($data = $event->getData()) && '' !== trim($data)) { + $event->setData($sanitizers->get($sanitizer)->sanitize($data)); + } + }, + 10000 /* as soon as possible */ + ); + } +} diff --git a/Tests/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtensionTest.php b/Tests/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtensionTest.php new file mode 100644 index 0000000000..39b8d03323 --- /dev/null +++ b/Tests/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtensionTest.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Tests\Extension\Csrf\Type; + +use Symfony\Component\DependencyInjection\ServiceLocator; +use Symfony\Component\Form\Extension\Core\Type\FormType; +use Symfony\Component\Form\Extension\Core\Type\TextType; +use Symfony\Component\Form\Extension\HtmlSanitizer\HtmlSanitizerExtension; +use Symfony\Component\Form\Test\TypeTestCase; +use Symfony\Component\HtmlSanitizer\HtmlSanitizerInterface; + +class TextTypeHtmlSanitizerExtensionTest extends TypeTestCase +{ + protected function getExtensions() + { + $fooSanitizer = $this->createMock(HtmlSanitizerInterface::class); + $fooSanitizer->expects($this->once()) + ->method('sanitize') + ->with('foobar') + ->willReturn('foo'); + + $barSanitizer = $this->createMock(HtmlSanitizerInterface::class); + $barSanitizer->expects($this->once()) + ->method('sanitize') + ->with('foobar') + ->willReturn('bar'); + + return array_merge(parent::getExtensions(), [ + new HtmlSanitizerExtension(new ServiceLocator([ + 'foo' => fn () => $fooSanitizer, + 'bar' => fn () => $barSanitizer, + ]), 'foo'), + ]); + } + + public function testSanitizer() + { + $form = $this->factory->createBuilder(FormType::class, ['data' => null]) + ->add('data', TextType::class, ['sanitize_html' => true]) + ->getForm() + ; + $form->submit(['data' => 'foobar']); + + $this->assertSame(['data' => 'foo'], $form->getData()); + + $form = $this->factory->createBuilder(FormType::class, ['data' => null]) + ->add('data', TextType::class, ['sanitize_html' => true, 'sanitizer' => 'bar']) + ->getForm() + ; + $form->submit(['data' => 'foobar']); + + $this->assertSame(['data' => 'bar'], $form->getData()); + } +} diff --git a/composer.json b/composer.json index 6fb2b50866..05193a2f0c 100644 --- a/composer.json +++ b/composer.json @@ -33,6 +33,7 @@ "symfony/expression-language": "^5.4|^6.0", "symfony/config": "^5.4|^6.0", "symfony/console": "^5.4|^6.0", + "symfony/html-sanitizer": "^6.1", "symfony/http-foundation": "^5.4|^6.0", "symfony/http-kernel": "^5.4|^6.0", "symfony/intl": "^5.4|^6.0", From c9bdcedf711a60ce446dc9d957f84c56f0ce64d9 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Thu, 30 Jun 2022 13:19:28 +0200 Subject: [PATCH 050/208] [Form] Provide string keys when iterating on a form --- Form.php | 2 +- Tests/CompoundFormTest.php | 10 ++++++++++ Tests/Util/OrderedHashMapTest.php | 22 +++++++++++++++++++-- Util/OrderedHashMap.php | 14 +++++++------- Util/OrderedHashMapIterator.php | 32 ++++++++++++++----------------- 5 files changed, 52 insertions(+), 28 deletions(-) diff --git a/Form.php b/Form.php index d1c60025cf..88d60a140e 100644 --- a/Form.php +++ b/Form.php @@ -77,7 +77,7 @@ class Form implements \IteratorAggregate, FormInterface, ClearableErrorsInterfac /** * A map of FormInterface instances. * - * @var OrderedHashMap + * @var OrderedHashMap */ private OrderedHashMap $children; diff --git a/Tests/CompoundFormTest.php b/Tests/CompoundFormTest.php index 5244948a0c..5efdfa3d1b 100644 --- a/Tests/CompoundFormTest.php +++ b/Tests/CompoundFormTest.php @@ -333,6 +333,16 @@ public function testIterator() $this->assertSame($this->form->all(), iterator_to_array($this->form)); } + public function testIteratorKeys() + { + $this->form->add($this->getBuilder('0')->getForm()); + $this->form->add($this->getBuilder('1')->getForm()); + + foreach ($this->form as $key => $value) { + $this->assertIsString($key); + } + } + public function testAddMapsViewDataToFormIfInitialized() { $form = $this->getBuilder() diff --git a/Tests/Util/OrderedHashMapTest.php b/Tests/Util/OrderedHashMapTest.php index 894da681d5..0cafaafad7 100644 --- a/Tests/Util/OrderedHashMapTest.php +++ b/Tests/Util/OrderedHashMapTest.php @@ -51,7 +51,7 @@ public function testInsertNullKeys() $map['foo'] = 2; $map[] = 3; - $this->assertSame([0 => 1, 'foo' => 2, 1 => 3], iterator_to_array($map)); + $this->assertSame(['0' => 1, 'foo' => 2, '1' => 3], iterator_to_array($map)); } public function testInsertLooselyEqualKeys() @@ -496,12 +496,30 @@ public function testParallelIteration() $this->assertNull($it1->current()); } + public function testKeysAreString() + { + $map = new OrderedHashMap(['1' => 1]); + $map['2'] = 2; + + $it = $map->getIterator(); + + $it->rewind(); + $this->assertTrue($it->valid()); + $this->assertSame('1', $it->key()); + $this->assertSame(1, $it->current()); + + $it->next(); + $this->assertTrue($it->valid()); + $this->assertSame('2', $it->key()); + $this->assertSame(2, $it->current()); + } + public function testCount() { $map = new OrderedHashMap(); $map[] = 1; $map['foo'] = 2; - unset($map[0]); + unset($map['0']); $map[] = 3; $this->assertCount(2, $map); diff --git a/Util/OrderedHashMap.php b/Util/OrderedHashMap.php index 5cfa872917..32d08caa8f 100644 --- a/Util/OrderedHashMap.php +++ b/Util/OrderedHashMap.php @@ -64,25 +64,24 @@ * * @author Bernhard Schussek * - * @template TKey of array-key * @template TValue * - * @implements \ArrayAccess - * @implements \IteratorAggregate + * @implements \ArrayAccess + * @implements \IteratorAggregate */ class OrderedHashMap implements \ArrayAccess, \IteratorAggregate, \Countable { /** * The elements of the map, indexed by their keys. * - * @var array + * @var TValue[] */ private array $elements = []; /** * The keys of the map in the order in which they were inserted or changed. * - * @var list + * @var list */ private array $orderedKeys = []; @@ -96,12 +95,13 @@ class OrderedHashMap implements \ArrayAccess, \IteratorAggregate, \Countable /** * Creates a new map. * - * @param array $elements The elements to insert initially + * @param TValue[] $elements The elements to insert initially */ public function __construct(array $elements = []) { $this->elements = $elements; - $this->orderedKeys = array_keys($elements); + // the explicit string type-cast is necessary as digit-only keys would be returned as integers otherwise + $this->orderedKeys = array_map(strval(...), array_keys($elements)); } public function offsetExists(mixed $key): bool diff --git a/Util/OrderedHashMapIterator.php b/Util/OrderedHashMapIterator.php index 7a3cafff6c..b3cdf5e571 100644 --- a/Util/OrderedHashMapIterator.php +++ b/Util/OrderedHashMapIterator.php @@ -18,36 +18,34 @@ * * @internal * - * @template-covariant TKey of array-key * @template-covariant TValue * - * @implements \Iterator + * @implements \Iterator */ class OrderedHashMapIterator implements \Iterator { - /** @var array */ + /** @var TValue[] */ private array $elements; - /** @var list */ + /** @var list */ private array $orderedKeys; private int $cursor = 0; private int $cursorId; /** @var array */ private array $managedCursors; - /** @var TKey|null */ - private string|int|null $key = null; + private string|null $key = null; /** @var TValue|null */ private mixed $current = null; /** - * @param array $elements The elements of the map, indexed by their - * keys - * @param list $orderedKeys The keys of the map in the order in which - * they should be iterated - * @param array $managedCursors An array from which to reference the - * iterator's cursor as long as it is alive. - * This array is managed by the corresponding - * {@link OrderedHashMap} instance to support - * recognizing the deletion of elements. + * @param TValue[] $elements The elements of the map, indexed by their + * keys + * @param list $orderedKeys The keys of the map in the order in which + * they should be iterated + * @param array $managedCursors An array from which to reference the + * iterator's cursor as long as it is alive. + * This array is managed by the corresponding + * {@link OrderedHashMap} instance to support + * recognizing the deletion of elements. */ public function __construct(array &$elements, array &$orderedKeys, array &$managedCursors) { @@ -113,9 +111,7 @@ public function key(): mixed return null; } - $array = [$this->key => null]; - - return key($array); + return $this->key; } /** From a6a25131acc3e7864fbbb8b404e75c7e1b8ed0b9 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault Date: Thu, 14 Jul 2022 22:24:06 +0200 Subject: [PATCH 051/208] [Form] ChoiceView label allow TranslatableInterface, not only TranslatableMessage --- CHANGELOG.md | 5 +++++ .../Factory/DefaultChoiceListFactory.php | 4 ++-- ChoiceList/View/ChoiceView.php | 14 ++++++------ .../Factory/DefaultChoiceListFactoryTest.php | 22 +++++++++++++++++++ 4 files changed, 36 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f2f949c897..588408aaf4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +6.2 +--- + +* Allow passing `TranslatableInterface` objects to the `ChoiceView` label + 6.1 --- diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index e22e81f235..cee3e2840a 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -20,7 +20,7 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView; use Symfony\Component\Form\ChoiceList\View\ChoiceListView; use Symfony\Component\Form\ChoiceList\View\ChoiceView; -use Symfony\Component\Translation\TranslatableMessage; +use Symfony\Contracts\Translation\TranslatableInterface; /** * Default implementation of {@link ChoiceListFactoryInterface}. @@ -175,7 +175,7 @@ private static function addChoiceView($choice, string $value, $label, array $key if (false === $dynamicLabel) { $label = false; - } elseif ($dynamicLabel instanceof TranslatableMessage) { + } elseif ($dynamicLabel instanceof TranslatableInterface) { $label = $dynamicLabel; } else { $label = (string) $dynamicLabel; diff --git a/ChoiceList/View/ChoiceView.php b/ChoiceList/View/ChoiceView.php index a98dd79541..050d8ed243 100644 --- a/ChoiceList/View/ChoiceView.php +++ b/ChoiceList/View/ChoiceView.php @@ -11,7 +11,7 @@ namespace Symfony\Component\Form\ChoiceList\View; -use Symfony\Component\Translation\TranslatableMessage; +use Symfony\Contracts\Translation\TranslatableInterface; /** * Represents a choice in templates. @@ -37,13 +37,13 @@ class ChoiceView /** * Creates a new choice view. * - * @param mixed $data The original choice - * @param string $value The view representation of the choice - * @param string|TranslatableMessage|false $label The label displayed to humans; pass false to discard the label - * @param array $attr Additional attributes for the HTML tag - * @param array $labelTranslationParameters Additional parameters used to translate the label + * @param mixed $data The original choice + * @param string $value The view representation of the choice + * @param string|TranslatableInterface|false $label The label displayed to humans; pass false to discard the label + * @param array $attr Additional attributes for the HTML tag + * @param array $labelTranslationParameters Additional parameters used to translate the label */ - public function __construct(mixed $data, string $value, string|TranslatableMessage|false $label, array $attr = [], array $labelTranslationParameters = []) + public function __construct(mixed $data, string $value, string|TranslatableInterface|false $label, array $attr = [], array $labelTranslationParameters = []) { $this->data = $data; $this->value = $value; diff --git a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index 767662f698..ab26d4cbe3 100644 --- a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -22,6 +22,8 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\Tests\Fixtures\ArrayChoiceLoader; use Symfony\Component\Translation\TranslatableMessage; +use Symfony\Contracts\Translation\TranslatableInterface; +use Symfony\Contracts\Translation\TranslatorInterface; class DefaultChoiceListFactoryTest extends TestCase { @@ -774,6 +776,26 @@ static function ($choice, $key, $value) { $this->assertArrayHasKey('param1', $view->choices[0]->label->getParameters()); } + public function testPassTranslatableInterfaceAsLabelDoesntCastItToString() + { + $message = new class() implements TranslatableInterface { + public function trans(TranslatorInterface $translator, string $locale = null): string + { + return 'my_message'; + } + }; + + $view = $this->factory->createView( + $this->list, + [$this->obj1], + static function () use ($message) { + return $message; + } + ); + + $this->assertSame($message, $view->choices[0]->label); + } + public function testCreateViewFlatLabelTranslationParametersAsArray() { $view = $this->factory->createView( From d3553e1c66c87b10c66232c446e3bade1c3db0c9 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 20 Jul 2022 15:55:56 +0200 Subject: [PATCH 052/208] Fix CS --- ChoiceList/Factory/DefaultChoiceListFactory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index e22e81f235..e065dde2cc 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -41,7 +41,7 @@ public function createListFromChoices(iterable $choices, callable $value = null, new CallbackChoiceLoader(static function () use ($choices) { return $choices; } - ), $filter), $value); + ), $filter), $value); } return new ArrayChoiceList($choices, $value); From b435d0eebfcd6985e8bdc984e67888278a6e6d6d Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 20 Jul 2022 17:00:40 +0200 Subject: [PATCH 053/208] Fix CS --- Tests/AbstractLayoutTest.php | 214 +++++++++++++++++------------------ 1 file changed, 107 insertions(+), 107 deletions(-) diff --git a/Tests/AbstractLayoutTest.php b/Tests/AbstractLayoutTest.php index 28f8520d5f..c093f4cdf0 100644 --- a/Tests/AbstractLayoutTest.php +++ b/Tests/AbstractLayoutTest.php @@ -150,7 +150,7 @@ public function testLabel() $html = $this->renderLabel($view); $this->assertMatchesXpath($html, -'/label + '/label [@for="name"] [.="[trans]Name[/trans]"] ' @@ -164,7 +164,7 @@ public function testLabelWithoutTranslation() ]); $this->assertMatchesXpath($this->renderLabel($form->createView()), -'/label + '/label [@for="name"] [.="Name"] ' @@ -179,7 +179,7 @@ public function testLabelOnForm() $html = $this->renderLabel($view); $this->assertMatchesXpath($html, -'/label + '/label [@class="required"] [.="[trans]Name[/trans]"] ' @@ -194,7 +194,7 @@ public function testLabelWithCustomTextPassedAsOption() $html = $this->renderLabel($form->createView()); $this->assertMatchesXpath($html, -'/label + '/label [@for="name"] [.="[trans]Custom label[/trans]"] ' @@ -207,7 +207,7 @@ public function testLabelWithCustomTextPassedDirectly() $html = $this->renderLabel($form->createView(), 'Custom label'); $this->assertMatchesXpath($html, -'/label + '/label [@for="name"] [.="[trans]Custom label[/trans]"] ' @@ -222,7 +222,7 @@ public function testLabelWithCustomTextPassedAsOptionAndDirectly() $html = $this->renderLabel($form->createView(), 'Overridden label'); $this->assertMatchesXpath($html, -'/label + '/label [@for="name"] [.="[trans]Overridden label[/trans]"] ' @@ -239,7 +239,7 @@ public function testLabelDoesNotRenderFieldAttributes() ]); $this->assertMatchesXpath($html, -'/label + '/label [@for="name"] [@class="required"] ' @@ -256,7 +256,7 @@ public function testLabelWithCustomAttributesPassedDirectly() ]); $this->assertMatchesXpath($html, -'/label + '/label [@for="name"] [@class="my&class required"] ' @@ -273,7 +273,7 @@ public function testLabelWithCustomTextAndCustomAttributesPassedDirectly() ]); $this->assertMatchesXpath($html, -'/label + '/label [@for="name"] [@class="my&class required"] [.="[trans]Custom label[/trans]"] @@ -311,7 +311,7 @@ public function testLabelFormatName() $html = $this->renderLabel($view, null, ['label_format' => 'form.%name%']); $this->assertMatchesXpath($html, -'/label + '/label [@for="myform_myfield"] [.="[trans]form.myfield[/trans]"] ' @@ -327,7 +327,7 @@ public function testLabelFormatId() $html = $this->renderLabel($view, null, ['label_format' => 'form.%id%']); $this->assertMatchesXpath($html, -'/label + '/label [@for="myform_myfield"] [.="[trans]form.myform_myfield[/trans]"] ' @@ -345,7 +345,7 @@ public function testLabelFormatAsFormOption() $html = $this->renderLabel($view); $this->assertMatchesXpath($html, -'/label + '/label [@for="myform_myfield"] [.="[trans]form.myfield[/trans]"] ' @@ -363,7 +363,7 @@ public function testLabelFormatOverriddenOption() $html = $this->renderLabel($view); $this->assertMatchesXpath($html, -'/label + '/label [@for="myform_myfield"] [.="[trans]field.myfield[/trans]"] ' @@ -381,7 +381,7 @@ public function testLabelWithoutTranslationOnButton() $html = $this->renderWidget($view); $this->assertMatchesXpath($html, -'/button + '/button [@type="button"] [@name="myform[mybutton]"] [.="Mybutton"] @@ -398,7 +398,7 @@ public function testLabelFormatOnButton() $html = $this->renderWidget($view, ['label_format' => 'form.%name%']); $this->assertMatchesXpath($html, -'/button + '/button [@type="button"] [@name="myform[mybutton]"] [.="[trans]form.mybutton[/trans]"] @@ -415,7 +415,7 @@ public function testLabelFormatOnButtonId() $html = $this->renderWidget($view, ['label_format' => 'form.%id%']); $this->assertMatchesXpath($html, -'/button + '/button [@type="button"] [@name="myform[mybutton]"] [.="[trans]form.myform_mybutton[/trans]"] @@ -432,7 +432,7 @@ public function testHelp() $html = $this->renderHelp($view); $this->assertMatchesXpath($html, -'/*[self::div or self::p] + '/*[self::div or self::p] [@id="name_help"] [@class="help-text"] [.="[trans]Help text test![/trans]"] @@ -461,7 +461,7 @@ public function testHelpSetLinkFromWidget() $this->renderHelp($view); $this->assertMatchesXpath($html, -'//input + '//input [@aria-describedby="name_help"] ' ); @@ -477,7 +477,7 @@ public function testHelpNotSetNotLinkedFromWidget() $this->renderHelp($view); $this->assertMatchesXpath($html, -'//input + '//input [not(@aria-describedby)] ' ); @@ -492,7 +492,7 @@ public function testErrors() $html = $this->renderErrors($view); $this->assertMatchesXpath($html, -'/ul + '/ul [ ./li[.="[trans]Error 1[/trans]"] /following-sibling::li[.="[trans]Error 2[/trans]"] @@ -509,7 +509,7 @@ public function testOverrideWidgetBlock() $html = $this->renderWidget($form->createView()); $this->assertMatchesXpath($html, -'/div + '/div [ ./input [@type="text"] @@ -525,7 +525,7 @@ public function testCheckedCheckbox() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', true); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="checkbox"] [@name="name"] [@checked="checked"] @@ -539,7 +539,7 @@ public function testUncheckedCheckbox() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', false); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="checkbox"] [@name="name"] [not(@checked)] @@ -554,7 +554,7 @@ public function testCheckboxWithValue() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="checkbox"] [@name="name"] [@value="foo&bar"] @@ -583,7 +583,7 @@ public function testSingleChoice() // then the select element must have a placeholder label option." $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [not(@required)] [ @@ -605,7 +605,7 @@ public function testSelectWithSizeBiggerThanOneCanBeRequired() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [@required="required"] [@size="2"] @@ -624,7 +624,7 @@ public function testSingleChoiceWithoutTranslation() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [not(@required)] [ @@ -648,7 +648,7 @@ public function testSingleChoiceWithPlaceholderWithoutTranslation() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [not(@required)] [ @@ -671,7 +671,7 @@ public function testSingleChoiceAttributes() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [not(@required)] [ @@ -693,7 +693,7 @@ public function testSingleChoiceAttributesWithMainAttributes() ]); $this->assertWidgetMatchesXpath($form->createView(), ['attr' => ['class' => 'bar&baz']], -'/select + '/select [@name="name"] [@class="bar&baz"] [not(@required)] @@ -716,7 +716,7 @@ public function testSingleExpandedChoiceAttributesWithMainAttributes() ]); $this->assertWidgetMatchesXpath($form->createView(), ['attr' => ['class' => 'bar&baz']], -'/div + '/div [@class="bar&baz"] [ ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] @@ -742,7 +742,7 @@ public function testSingleChoiceWithPreferred() ]); $this->assertWidgetMatchesXpath($form->createView(), ['separator' => '-- sep --'], -'/select + '/select [@name="name"] [not(@required)] [ @@ -768,7 +768,7 @@ public function testSingleChoiceWithPreferredAndNoSeparator() ]); $this->assertWidgetMatchesXpath($form->createView(), ['separator' => null], -'/select + '/select [@name="name"] [not(@required)] [ @@ -793,7 +793,7 @@ public function testSingleChoiceWithPreferredAndBlankSeparator() ]); $this->assertWidgetMatchesXpath($form->createView(), ['separator' => ''], -'/select + '/select [@name="name"] [not(@required)] [ @@ -819,7 +819,7 @@ public function testChoiceWithOnlyPreferred() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [count(./option)=5] ' ); @@ -835,7 +835,7 @@ public function testSingleChoiceNonRequired() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [not(@required)] [ @@ -858,7 +858,7 @@ public function testSingleChoiceNonRequiredNoneSelected() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [not(@required)] [ @@ -882,7 +882,7 @@ public function testSingleChoiceNonRequiredWithPlaceholder() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [not(@required)] [ @@ -909,7 +909,7 @@ public function testSingleChoiceRequiredWithPlaceholder() // BlackBerry 10 browser. // See https://github.com/symfony/symfony/pull/7678 $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [@required="required"] [ @@ -935,7 +935,7 @@ public function testSingleChoiceRequiredWithPlaceholderViaView() // BlackBerry 10 browser. // See https://github.com/symfony/symfony/pull/7678 $this->assertWidgetMatchesXpath($form->createView(), ['placeholder' => ''], -'/select + '/select [@name="name"] [@required="required"] [ @@ -960,7 +960,7 @@ public function testSingleChoiceGrouped() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [./optgroup[@label="[trans]Group&1[/trans]"] [ @@ -988,7 +988,7 @@ public function testMultipleChoice() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name[]"] [@required="required"] [@multiple="multiple"] @@ -1012,7 +1012,7 @@ public function testMultipleChoiceAttributes() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name[]"] [@required="required"] [@multiple="multiple"] @@ -1035,7 +1035,7 @@ public function testMultipleChoiceSkipsPlaceholder() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name[]"] [@multiple="multiple"] [ @@ -1057,7 +1057,7 @@ public function testMultipleChoiceNonRequired() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name[]"] [@multiple="multiple"] [ @@ -1078,7 +1078,7 @@ public function testSingleChoiceExpanded() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] @@ -1102,7 +1102,7 @@ public function testSingleChoiceExpandedWithoutTranslation() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] /following-sibling::label[@for="name_0"][.="Choice&A"] @@ -1125,7 +1125,7 @@ public function testSingleChoiceExpandedAttributes() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] @@ -1149,7 +1149,7 @@ public function testSingleChoiceExpandedWithPlaceholder() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input[@type="radio"][@name="name"][@id="name_placeholder"][not(@checked)] /following-sibling::label[@for="name_placeholder"][.="[trans]Test&Me[/trans]"] @@ -1176,7 +1176,7 @@ public function testSingleChoiceExpandedWithPlaceholderWithoutTranslation() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input[@type="radio"][@name="name"][@id="name_placeholder"][not(@checked)] /following-sibling::label[@for="name_placeholder"][.="Placeholder&Not&Translated"] @@ -1200,7 +1200,7 @@ public function testSingleChoiceExpandedWithBooleanValue() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input[@type="radio"][@name="name"][@id="name_0"][@checked] /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] @@ -1223,7 +1223,7 @@ public function testMultipleChoiceExpanded() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input[@type="checkbox"][@name="name[]"][@id="name_0"][@checked][not(@required)] /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] @@ -1249,7 +1249,7 @@ public function testMultipleChoiceExpandedWithoutTranslation() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input[@type="checkbox"][@name="name[]"][@id="name_0"][@checked][not(@required)] /following-sibling::label[@for="name_0"][.="Choice&A"] @@ -1275,7 +1275,7 @@ public function testMultipleChoiceExpandedAttributes() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input[@type="checkbox"][@name="name[]"][@id="name_0"][@checked][not(@required)] /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] @@ -1295,7 +1295,7 @@ public function testCountry() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CountryType', 'AT'); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [./option[@value="AT"][@selected="selected"][.="Austria"]] [count(./option)>200] @@ -1311,7 +1311,7 @@ public function testCountryWithPlaceholder() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Select&Country[/trans]"]] [./option[@value="AT"][@selected="selected"][.="Austria"]] @@ -1328,7 +1328,7 @@ public function testDateTime() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./div [@id="name_date"] @@ -1368,7 +1368,7 @@ public function testDateTimeWithPlaceholderGlobal() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./div [@id="name_date"] @@ -1409,7 +1409,7 @@ public function testDateTimeWithHourAndMinute() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./div [@id="name_date"] @@ -1448,7 +1448,7 @@ public function testDateTimeWithSeconds() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./div [@id="name_date"] @@ -1491,7 +1491,7 @@ public function testDateTimeSingleText() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input [@type="date"] @@ -1518,7 +1518,7 @@ public function testDateTimeWithWidgetSingleText() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="datetime-local"] [@name="name"] [@value="2011-02-03T04:05:06"] @@ -1534,7 +1534,7 @@ public function testDateChoice() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./select [@id="name_month"] @@ -1561,7 +1561,7 @@ public function testDateChoiceWithPlaceholderGlobal() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./select [@id="name_month"] @@ -1588,7 +1588,7 @@ public function testDateChoiceWithPlaceholderOnYear() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./select [@id="name_month"] @@ -1613,7 +1613,7 @@ public function testDateText() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input [@id="name_month"] @@ -1641,7 +1641,7 @@ public function testDateSingleText() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="date"] [@name="name"] [@value="2011-02-03"] @@ -1668,7 +1668,7 @@ public function testBirthDay() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./select [@id="name_month"] @@ -1694,7 +1694,7 @@ public function testBirthDayWithPlaceholder() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./select [@id="name_month"] @@ -1719,7 +1719,7 @@ public function testEmail() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\EmailType', 'foo&bar'); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="email"] [@name="name"] [@value="foo&bar"] @@ -1735,7 +1735,7 @@ public function testEmailWithMaxLength() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="email"] [@name="name"] [@value="foo&bar"] @@ -1749,7 +1749,7 @@ public function testFile() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\FileType'); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="file"] ' ); @@ -1760,7 +1760,7 @@ public function testHidden() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\HiddenType', 'foo&bar'); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="hidden"] [@name="name"] [@value="foo&bar"] @@ -1775,7 +1775,7 @@ public function testDisabled() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="text"] [@name="name"] [@disabled="disabled"] @@ -1788,7 +1788,7 @@ public function testInteger() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\IntegerType', 123); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="number"] [@name="name"] [@value="123"] @@ -1803,7 +1803,7 @@ public function testIntegerTypeWithGroupingRendersAsTextInput() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="text"] [@name="name"] [@value="123"] @@ -1816,7 +1816,7 @@ public function testLanguage() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\LanguageType', 'de'); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [./option[@value="de"][@selected="selected"][.="German"]] [count(./option)>200] @@ -1829,7 +1829,7 @@ public function testLocale() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\LocaleType', 'de_AT'); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [./option[@value="de_AT"][@selected="selected"][.="German (Austria)"]] [count(./option)>200] @@ -1844,7 +1844,7 @@ public function testMoney() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="text"] [@name="name"] [@value="1234.56"] @@ -1858,7 +1858,7 @@ public function testNumber() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\NumberType', 1234.56); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="text"] [@name="name"] [@value="1234.56"] @@ -1875,7 +1875,7 @@ public function testRenderNumberWithHtml5NumberType() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="number"] [@name="name"] [@value="1234.56"] @@ -1888,7 +1888,7 @@ public function testPassword() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\PasswordType', 'foo&bar'); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="password"] [@name="name"] ' @@ -1903,7 +1903,7 @@ public function testPasswordSubmittedWithNotAlwaysEmpty() $form->submit('foo&bar'); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="password"] [@name="name"] [@value="foo&bar"] @@ -1918,7 +1918,7 @@ public function testPasswordWithMaxLength() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="password"] [@name="name"] [@maxlength="123"] @@ -1931,7 +1931,7 @@ public function testPercent() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\PercentType', 0.1, ['rounding_mode' => \NumberFormatter::ROUND_CEILING]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="text"] [@name="name"] [@value="10"] @@ -1946,7 +1946,7 @@ public function testPercentNoSymbol() $form = $this->factory->createNamed('name', PercentType::class, 0.1, ['symbol' => false, 'rounding_mode' => \NumberFormatter::ROUND_CEILING]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="text"] [@name="name"] [@value="10"] @@ -1961,7 +1961,7 @@ public function testPercentCustomSymbol() $form = $this->factory->createNamed('name', PercentType::class, 0.1, ['symbol' => '‱', 'rounding_mode' => \NumberFormatter::ROUND_CEILING]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="text"] [@name="name"] [@value="10"] @@ -1975,7 +1975,7 @@ public function testCheckedRadio() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RadioType', true); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="radio"] [@name="name"] [@checked="checked"] @@ -1989,7 +1989,7 @@ public function testUncheckedRadio() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RadioType', false); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="radio"] [@name="name"] [not(@checked)] @@ -2004,7 +2004,7 @@ public function testRadioWithValue() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="radio"] [@name="name"] [@value="foo&bar"] @@ -2017,7 +2017,7 @@ public function testRange() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RangeType', 42, ['attr' => ['min' => 5]]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="range"] [@name="name"] [@value="42"] @@ -2031,7 +2031,7 @@ public function testRangeWithMinMaxValues() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RangeType', 42, ['attr' => ['min' => 5, 'max' => 57]]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="range"] [@name="name"] [@value="42"] @@ -2048,7 +2048,7 @@ public function testTextarea() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/textarea + '/textarea [@name="name"] [not(@pattern)] [.="foo&bar"] @@ -2061,7 +2061,7 @@ public function testText() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', 'foo&bar'); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="text"] [@name="name"] [@value="foo&bar"] @@ -2077,7 +2077,7 @@ public function testTextWithMaxLength() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="text"] [@name="name"] [@value="foo&bar"] @@ -2091,7 +2091,7 @@ public function testSearch() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\SearchType', 'foo&bar'); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="search"] [@name="name"] [@value="foo&bar"] @@ -2108,7 +2108,7 @@ public function testTime() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./select [@id="name_hour"] @@ -2132,7 +2132,7 @@ public function testTimeWithSeconds() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./select [@id="name_hour"] @@ -2163,7 +2163,7 @@ public function testTimeText() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./input [@type="text"] @@ -2193,7 +2193,7 @@ public function testTimeSingleText() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="time"] [@name="name"] [@value="04:05"] @@ -2211,7 +2211,7 @@ public function testTimeWithPlaceholderGlobal() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./select [@id="name_hour"] @@ -2236,7 +2236,7 @@ public function testTimeWithPlaceholderOnYear() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/div + '/div [ ./select [@id="name_hour"] @@ -2269,7 +2269,7 @@ public function testTimezone() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TimezoneType', 'Europe/Vienna'); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [@name="name"] [not(@required)] [./option[@value="Europe/Vienna"][@selected="selected"][.="Europe / Vienna"]] @@ -2286,7 +2286,7 @@ public function testTimezoneWithPlaceholder() ]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/select + '/select [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Select&Timezone[/trans]"]] [count(./option)>201] ' @@ -2299,7 +2299,7 @@ public function testUrlWithDefaultProtocol() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\UrlType', $url, ['default_protocol' => 'http']); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="text"] [@name="name"] [@value="http://www.example.com?foo1=bar1&foo2=bar2"] @@ -2314,7 +2314,7 @@ public function testUrlWithoutDefaultProtocol() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\UrlType', $url, ['default_protocol' => null]); $this->assertWidgetMatchesXpath($form->createView(), [], -'/input + '/input [@type="url"] [@name="name"] [@value="http://www.example.com?foo1=bar1&foo2=bar2"] @@ -2417,7 +2417,7 @@ public function testStartTagForPutRequest() $html = $this->renderStart($form->createView()); $this->assertMatchesXpath($html.'', -'/form + '/form [./input[@type="hidden"][@name="_method"][@value="PUT"]] [@method="post"] [@action="http://example.com/directory"]' From a55e834a996f76e89068ba49977ada5f561e7c80 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault Date: Sun, 24 Jul 2022 17:47:09 +0200 Subject: [PATCH 054/208] [Form] Allow TranslatableInterface to the FormType help option --- CHANGELOG.md | 1 + Extension/Core/Type/FormType.php | 4 ++-- Tests/AbstractLayoutTest.php | 24 ++++++++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 588408aaf4..b5150a4c84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ CHANGELOG --- * Allow passing `TranslatableInterface` objects to the `ChoiceView` label +* Allow passing `TranslatableInterface` objects to the `help` option 6.1 --- diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index b2ad206236..efb61c739b 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -24,7 +24,7 @@ use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; -use Symfony\Component\Translation\TranslatableMessage; +use Symfony\Contracts\Translation\TranslatableInterface; class FormType extends BaseType { @@ -220,7 +220,7 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('label_attr', 'array'); $resolver->setAllowedTypes('action', 'string'); $resolver->setAllowedTypes('upload_max_size_message', ['callable']); - $resolver->setAllowedTypes('help', ['string', 'null', TranslatableMessage::class]); + $resolver->setAllowedTypes('help', ['string', 'null', TranslatableInterface::class]); $resolver->setAllowedTypes('help_attr', 'array'); $resolver->setAllowedTypes('help_html', 'bool'); $resolver->setAllowedTypes('is_empty_callback', ['null', 'callable']); diff --git a/Tests/AbstractLayoutTest.php b/Tests/AbstractLayoutTest.php index c093f4cdf0..58e853e111 100644 --- a/Tests/AbstractLayoutTest.php +++ b/Tests/AbstractLayoutTest.php @@ -20,6 +20,8 @@ use Symfony\Component\Form\Test\FormIntegrationTestCase; use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Symfony\Component\Translation\TranslatableMessage; +use Symfony\Contracts\Translation\TranslatableInterface; +use Symfony\Contracts\Translation\TranslatorInterface; abstract class AbstractLayoutTest extends FormIntegrationTestCase { @@ -2699,6 +2701,28 @@ public function testHelpWithTranslatableMessage() ); } + public function testHelpWithTranslatableInterface() + { + $message = new class() implements TranslatableInterface { + public function trans(TranslatorInterface $translator, string $locale = null): string + { + return $translator->trans('foo'); + } + }; + + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ + 'help' => $message, + ]); + $html = $this->renderHelp($form->createView()); + + $this->assertMatchesXpath($html, + '/* + [@id="name_help"] + [.="[trans]foo[/trans]"] +' + ); + } + public function testAttributesWithTranslationParameters() { $this->requiresFeatureSet(403); From 0fc271db683861b56b9320c5b08c338b1001ccdd Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Tue, 9 Aug 2022 11:43:52 +0200 Subject: [PATCH 055/208] clean up legacy test --- Tests/CompoundFormTest.php | 28 ---------------------------- 1 file changed, 28 deletions(-) diff --git a/Tests/CompoundFormTest.php b/Tests/CompoundFormTest.php index f45c261738..e5a4aeec33 100644 --- a/Tests/CompoundFormTest.php +++ b/Tests/CompoundFormTest.php @@ -16,7 +16,6 @@ use Symfony\Component\Form\Exception\AlreadySubmittedException; use Symfony\Component\Form\Extension\Core\DataAccessor\PropertyPathAccessor; use Symfony\Component\Form\Extension\Core\DataMapper\DataMapper; -use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; @@ -1080,33 +1079,6 @@ public function testFileUpload() $this->assertNull($this->form->get('bar')->getData()); } - /** - * @group legacy - */ - public function testMapDateTimeObjectsWithEmptyArrayDataUsingPropertyPathMapper() - { - $propertyAccessor = PropertyAccess::createPropertyAccessorBuilder() - ->enableExceptionOnInvalidIndex() - ->getPropertyAccessor(); - $form = $this->factory->createBuilder() - ->setDataMapper(new PropertyPathMapper($propertyAccessor)) - ->add('date', DateType::class, [ - 'auto_initialize' => false, - 'format' => 'dd/MM/yyyy', - 'html5' => false, - 'model_timezone' => 'UTC', - 'view_timezone' => 'UTC', - 'widget' => 'single_text', - ]) - ->getForm(); - - $form->submit([ - 'date' => '04/08/2022', - ]); - - $this->assertEquals(['date' => new \DateTime('2022-08-04', new \DateTimeZone('UTC'))], $form->getData()); - } - public function testMapDateTimeObjectsWithEmptyArrayDataUsingDataMapper() { $propertyAccessor = PropertyAccess::createPropertyAccessorBuilder() From 7dddf806060accc96763e74536c8e327e174ca12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Pineau?= Date: Thu, 25 Aug 2022 16:59:21 +0200 Subject: [PATCH 056/208] [CS] Remove @inheritdoc PHPDoc --- AbstractExtension.php | 15 -- AbstractRendererEngine.php | 12 -- AbstractType.php | 18 -- AbstractTypeExtension.php | 12 -- Button.php | 24 --- ButtonBuilder.php | 9 - CallbackTransformer.php | 6 - ChoiceList/ArrayChoiceList.php | 18 -- ChoiceList/Factory/Cache/ChoiceLoader.php | 9 - .../Factory/CachingFactoryDecorator.php | 9 - .../Factory/DefaultChoiceListFactory.php | 9 - .../Factory/PropertyAccessDecorator.php | 9 - ChoiceList/LazyChoiceList.php | 18 -- ChoiceList/Loader/AbstractChoiceLoader.php | 8 - .../Loader/FilterChoiceLoaderDecorator.php | 6 - .../Loader/IntlCallbackChoiceLoader.php | 6 - ChoiceList/View/ChoiceGroupView.php | 2 - Command/DebugCommand.php | 6 - Console/Descriptor/Descriptor.php | 3 - .../Core/DataAccessor/CallbackAccessor.php | 12 -- Extension/Core/DataAccessor/ChainAccessor.php | 12 -- .../DataAccessor/PropertyPathAccessor.php | 12 -- .../Core/DataMapper/CheckboxListMapper.php | 6 - Extension/Core/DataMapper/DataMapper.php | 6 - Extension/Core/DataMapper/RadioListMapper.php | 6 - .../DateTimeZoneToStringTransformer.php | 6 - .../IntegerToLocalizedStringTransformer.php | 3 - .../IntlTimeZoneToStringTransformer.php | 6 - Extension/Core/Type/BaseType.php | 9 - Extension/Core/Type/BirthdayType.php | 9 - Extension/Core/Type/ButtonType.php | 9 - Extension/Core/Type/CheckboxType.php | 12 -- Extension/Core/Type/ChoiceType.php | 15 -- Extension/Core/Type/CollectionType.php | 15 -- Extension/Core/Type/ColorType.php | 12 -- Extension/Core/Type/CountryType.php | 9 - Extension/Core/Type/CurrencyType.php | 9 - Extension/Core/Type/DateIntervalType.php | 12 -- Extension/Core/Type/DateTimeType.php | 12 -- Extension/Core/Type/DateType.php | 12 -- Extension/Core/Type/EmailType.php | 9 - Extension/Core/Type/FileType.php | 15 -- Extension/Core/Type/FormType.php | 18 -- Extension/Core/Type/HiddenType.php | 6 - Extension/Core/Type/IntegerType.php | 12 -- Extension/Core/Type/LanguageType.php | 9 - Extension/Core/Type/LocaleType.php | 9 - Extension/Core/Type/MoneyType.php | 12 -- Extension/Core/Type/NumberType.php | 12 -- Extension/Core/Type/PasswordType.php | 12 -- Extension/Core/Type/PercentType.php | 12 -- Extension/Core/Type/RadioType.php | 9 - Extension/Core/Type/RangeType.php | 9 - Extension/Core/Type/RepeatedType.php | 9 - Extension/Core/Type/ResetType.php | 6 - Extension/Core/Type/SearchType.php | 9 - Extension/Core/Type/SubmitType.php | 9 - Extension/Core/Type/TelType.php | 9 - Extension/Core/Type/TextType.php | 12 -- Extension/Core/Type/TextareaType.php | 9 - Extension/Core/Type/TimeType.php | 12 -- Extension/Core/Type/TimezoneType.php | 12 -- .../Type/TransformationFailureExtension.php | 3 - Extension/Core/Type/UlidType.php | 6 - Extension/Core/Type/UrlType.php | 15 -- Extension/Core/Type/UuidType.php | 6 - Extension/Core/Type/WeekType.php | 12 -- Extension/Csrf/CsrfExtension.php | 3 - Extension/Csrf/Type/FormTypeCsrfExtension.php | 6 - .../DataCollector/DataCollectorExtension.php | 3 - .../EventListener/DataCollectorListener.php | 3 - Extension/DataCollector/FormDataCollector.php | 30 --- Extension/DataCollector/FormDataExtractor.php | 12 -- .../Proxy/ResolvedTypeDataCollectorProxy.php | 30 --- .../ResolvedTypeFactoryDataCollectorProxy.php | 3 - .../Type/DataCollectorTypeExtension.php | 6 - .../DependencyInjectionExtension.php | 15 -- .../HttpFoundationRequestHandler.php | 6 - .../Type/FormTypeHttpFoundationExtension.php | 6 - Extension/Validator/Constraints/Form.php | 3 - .../Validator/Constraints/FormValidator.php | 3 - .../EventListener/ValidationListener.php | 3 - .../Validator/Type/BaseValidatorExtension.php | 3 - .../Type/FormTypeValidatorExtension.php | 9 - .../Type/RepeatedTypeValidatorExtension.php | 6 - .../Type/SubmitTypeValidatorExtension.php | 3 - .../Type/UploadValidatorExtension.php | 6 - Extension/Validator/ValidatorTypeGuesser.php | 12 -- .../ViolationMapper/ViolationMapper.php | 3 - .../ViolationMapper/ViolationPath.php | 18 -- Form.php | 93 ---------- FormBuilder.php | 26 --- FormConfigBuilder.php | 174 ------------------ FormFactory.php | 18 -- FormFactoryBuilder.php | 30 --- FormRegistry.php | 12 -- FormRenderer.php | 18 -- FormTypeGuesserChain.php | 12 -- NativeRequestHandler.php | 5 - PreloadedExtension.php | 15 -- ResolvedFormType.php | 30 --- ResolvedFormTypeFactory.php | 3 - ReversedTransformer.php | 6 - SubmitButton.php | 3 - Test/FormPerformanceTestCase.php | 3 - Tests/Fixtures/ChoiceSubType.php | 6 - Tests/Fixtures/ChoiceTypeExtension.php | 6 - Tests/Fixtures/LazyChoiceTypeExtension.php | 6 - Util/OrderedHashMapIterator.php | 15 -- 109 files changed, 1349 deletions(-) diff --git a/AbstractExtension.php b/AbstractExtension.php index 79d61e8bc0..6ba5624bd9 100644 --- a/AbstractExtension.php +++ b/AbstractExtension.php @@ -43,9 +43,6 @@ abstract class AbstractExtension implements FormExtensionInterface */ private bool $typeGuesserLoaded = false; - /** - * {@inheritdoc} - */ public function getType(string $name): FormTypeInterface { if (!isset($this->types)) { @@ -59,9 +56,6 @@ public function getType(string $name): FormTypeInterface return $this->types[$name]; } - /** - * {@inheritdoc} - */ public function hasType(string $name): bool { if (!isset($this->types)) { @@ -71,9 +65,6 @@ public function hasType(string $name): bool return isset($this->types[$name]); } - /** - * {@inheritdoc} - */ public function getTypeExtensions(string $name): array { if (!isset($this->typeExtensions)) { @@ -84,9 +75,6 @@ public function getTypeExtensions(string $name): array ?? []; } - /** - * {@inheritdoc} - */ public function hasTypeExtensions(string $name): bool { if (!isset($this->typeExtensions)) { @@ -96,9 +84,6 @@ public function hasTypeExtensions(string $name): bool return isset($this->typeExtensions[$name]) && \count($this->typeExtensions[$name]) > 0; } - /** - * {@inheritdoc} - */ public function getTypeGuesser(): ?FormTypeGuesserInterface { if (!$this->typeGuesserLoaded) { diff --git a/AbstractRendererEngine.php b/AbstractRendererEngine.php index ada182f57b..f79f1c1338 100644 --- a/AbstractRendererEngine.php +++ b/AbstractRendererEngine.php @@ -61,9 +61,6 @@ public function __construct(array $defaultThemes = []) $this->defaultThemes = $defaultThemes; } - /** - * {@inheritdoc} - */ public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true) { $cacheKey = $view->vars[self::CACHE_KEY_VAR]; @@ -78,9 +75,6 @@ public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = unset($this->resources[$cacheKey], $this->resourceHierarchyLevels[$cacheKey]); } - /** - * {@inheritdoc} - */ public function getResourceForBlockName(FormView $view, string $blockName): mixed { $cacheKey = $view->vars[self::CACHE_KEY_VAR]; @@ -92,9 +86,6 @@ public function getResourceForBlockName(FormView $view, string $blockName): mixe return $this->resources[$cacheKey][$blockName]; } - /** - * {@inheritdoc} - */ public function getResourceForBlockNameHierarchy(FormView $view, array $blockNameHierarchy, int $hierarchyLevel): mixed { $cacheKey = $view->vars[self::CACHE_KEY_VAR]; @@ -107,9 +98,6 @@ public function getResourceForBlockNameHierarchy(FormView $view, array $blockNam return $this->resources[$cacheKey][$blockName]; } - /** - * {@inheritdoc} - */ public function getResourceHierarchyLevel(FormView $view, array $blockNameHierarchy, int $hierarchyLevel): int|false { $cacheKey = $view->vars[self::CACHE_KEY_VAR]; diff --git a/AbstractType.php b/AbstractType.php index 3325b8bc27..da401930d7 100644 --- a/AbstractType.php +++ b/AbstractType.php @@ -20,45 +20,27 @@ */ abstract class AbstractType implements FormTypeInterface { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { } - /** - * {@inheritdoc} - */ public function finishView(FormView $view, FormInterface $form, array $options) { } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { } - /** - * {@inheritdoc} - */ public function getBlockPrefix() { return StringUtil::fqcnToBlockPrefix(static::class) ?: ''; } - /** - * {@inheritdoc} - */ public function getParent() { return FormType::class; diff --git a/AbstractTypeExtension.php b/AbstractTypeExtension.php index 9d369bf294..bcd408c170 100644 --- a/AbstractTypeExtension.php +++ b/AbstractTypeExtension.php @@ -18,30 +18,18 @@ */ abstract class AbstractTypeExtension implements FormTypeExtensionInterface { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { } - /** - * {@inheritdoc} - */ public function finishView(FormView $view, FormInterface $form, array $options) { } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { } diff --git a/Button.php b/Button.php index 7c80d03e34..58a77a7763 100644 --- a/Button.php +++ b/Button.php @@ -81,9 +81,6 @@ public function offsetUnset(mixed $offset): void throw new BadMethodCallException('Buttons cannot have children.'); } - /** - * {@inheritdoc} - */ public function setParent(FormInterface $parent = null): static { if ($this->submitted) { @@ -95,9 +92,6 @@ public function setParent(FormInterface $parent = null): static return $this; } - /** - * {@inheritdoc} - */ public function getParent(): ?FormInterface { return $this->parent; @@ -147,17 +141,11 @@ public function remove(string $name): static throw new BadMethodCallException('Buttons cannot have children.'); } - /** - * {@inheritdoc} - */ public function all(): array { return []; } - /** - * {@inheritdoc} - */ public function getErrors(bool $deep = false, bool $flatten = true): FormErrorIterator { return new FormErrorIterator($this, []); @@ -266,9 +254,6 @@ public function isRequired(): bool return false; } - /** - * {@inheritdoc} - */ public function isDisabled(): bool { if ($this->parent?->isDisabled()) { @@ -340,25 +325,16 @@ public function submit(array|string|null $submittedData, bool $clearMissing = tr return $this; } - /** - * {@inheritdoc} - */ public function getRoot(): FormInterface { return $this->parent ? $this->parent->getRoot() : $this; } - /** - * {@inheritdoc} - */ public function isRoot(): bool { return null === $this->parent; } - /** - * {@inheritdoc} - */ public function createView(FormView $parent = null): FormView { if (null === $parent && $this->parent) { diff --git a/ButtonBuilder.php b/ButtonBuilder.php index 7c8f186e12..387c3571fc 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -173,9 +173,6 @@ public function resetModelTransformers(): static throw new BadMethodCallException('Buttons do not support data transformers.'); } - /** - * {@inheritdoc} - */ public function setAttribute(string $name, mixed $value): static { $this->attributes[$name] = $value; @@ -183,9 +180,6 @@ public function setAttribute(string $name, mixed $value): static return $this; } - /** - * {@inheritdoc} - */ public function setAttributes(array $attributes): static { $this->attributes = $attributes; @@ -415,9 +409,6 @@ public function getEventDispatcher(): EventDispatcherInterface throw new BadMethodCallException('Buttons do not support event dispatching.'); } - /** - * {@inheritdoc} - */ public function getName(): string { return $this->name; diff --git a/CallbackTransformer.php b/CallbackTransformer.php index 8870526b8f..2a79b5b365 100644 --- a/CallbackTransformer.php +++ b/CallbackTransformer.php @@ -22,17 +22,11 @@ public function __construct(callable $transform, callable $reverseTransform) $this->reverseTransform = $reverseTransform(...); } - /** - * {@inheritdoc} - */ public function transform(mixed $data): mixed { return ($this->transform)($data); } - /** - * {@inheritdoc} - */ public function reverseTransform(mixed $data): mixed { return ($this->reverseTransform)($data); diff --git a/ChoiceList/ArrayChoiceList.php b/ChoiceList/ArrayChoiceList.php index 890ed4a978..a438ce2e10 100644 --- a/ChoiceList/ArrayChoiceList.php +++ b/ChoiceList/ArrayChoiceList.php @@ -90,41 +90,26 @@ public function __construct(iterable $choices, callable $value = null) $this->structuredValues = $structuredValues; } - /** - * {@inheritdoc} - */ public function getChoices(): array { return $this->choices; } - /** - * {@inheritdoc} - */ public function getValues(): array { return array_map('strval', array_keys($this->choices)); } - /** - * {@inheritdoc} - */ public function getStructuredValues(): array { return $this->structuredValues; } - /** - * {@inheritdoc} - */ public function getOriginalKeys(): array { return $this->originalKeys; } - /** - * {@inheritdoc} - */ public function getChoicesForValues(array $values): array { $choices = []; @@ -138,9 +123,6 @@ public function getChoicesForValues(array $values): array return $choices; } - /** - * {@inheritdoc} - */ public function getValuesForChoices(array $choices): array { $values = []; diff --git a/ChoiceList/Factory/Cache/ChoiceLoader.php b/ChoiceList/Factory/Cache/ChoiceLoader.php index 83b2ca0aa2..70c3f77e86 100644 --- a/ChoiceList/Factory/Cache/ChoiceLoader.php +++ b/ChoiceList/Factory/Cache/ChoiceLoader.php @@ -26,25 +26,16 @@ */ final class ChoiceLoader extends AbstractStaticOption implements ChoiceLoaderInterface { - /** - * {@inheritdoc} - */ public function loadChoiceList(callable $value = null): ChoiceListInterface { return $this->getOption()->loadChoiceList($value); } - /** - * {@inheritdoc} - */ public function loadChoicesForValues(array $values, callable $value = null): array { return $this->getOption()->loadChoicesForValues($values, $value); } - /** - * {@inheritdoc} - */ public function loadValuesForChoices(array $choices, callable $value = null): array { return $this->getOption()->loadValuesForChoices($choices, $value); diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index f5174bcfd5..62d1b71d9d 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -77,9 +77,6 @@ public function getDecoratedFactory(): ChoiceListFactoryInterface return $this->decoratedFactory; } - /** - * {@inheritdoc} - */ public function createListFromChoices(iterable $choices, mixed $value = null, mixed $filter = null): ChoiceListInterface { if ($choices instanceof \Traversable) { @@ -113,9 +110,6 @@ public function createListFromChoices(iterable $choices, mixed $value = null, mi return $this->lists[$hash]; } - /** - * {@inheritdoc} - */ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value = null, mixed $filter = null): ChoiceListInterface { $cache = true; @@ -151,9 +145,6 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value return $this->lists[$hash]; } - /** - * {@inheritdoc} - */ public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []): ChoiceListView { $cache = true; diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index 9ab806cbc5..0d39b590cf 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -30,9 +30,6 @@ */ class DefaultChoiceListFactory implements ChoiceListFactoryInterface { - /** - * {@inheritdoc} - */ public function createListFromChoices(iterable $choices, callable $value = null, callable $filter = null): ChoiceListInterface { if ($filter) { @@ -47,9 +44,6 @@ public function createListFromChoices(iterable $choices, callable $value = null, return new ArrayChoiceList($choices, $value); } - /** - * {@inheritdoc} - */ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $value = null, callable $filter = null): ChoiceListInterface { if ($filter) { @@ -59,9 +53,6 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $va return new LazyChoiceList($loader, $value); } - /** - * {@inheritdoc} - */ public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []): ChoiceListView { $preferredViews = []; diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index 3da57ecfbf..2f29bda726 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -55,9 +55,6 @@ public function getDecoratedFactory(): ChoiceListFactoryInterface return $this->decoratedFactory; } - /** - * {@inheritdoc} - */ public function createListFromChoices(iterable $choices, mixed $value = null, mixed $filter = null): ChoiceListInterface { if (\is_string($value)) { @@ -89,9 +86,6 @@ public function createListFromChoices(iterable $choices, mixed $value = null, mi return $this->decoratedFactory->createListFromChoices($choices, $value, $filter); } - /** - * {@inheritdoc} - */ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value = null, mixed $filter = null): ChoiceListInterface { if (\is_string($value)) { @@ -123,9 +117,6 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value return $this->decoratedFactory->createListFromLoader($loader, $value, $filter); } - /** - * {@inheritdoc} - */ public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []): ChoiceListView { $accessor = $this->propertyAccessor; diff --git a/ChoiceList/LazyChoiceList.php b/ChoiceList/LazyChoiceList.php index dd545430cf..b34d3708ab 100644 --- a/ChoiceList/LazyChoiceList.php +++ b/ChoiceList/LazyChoiceList.php @@ -51,49 +51,31 @@ public function __construct(ChoiceLoaderInterface $loader, callable $value = nul $this->value = null === $value ? null : $value(...); } - /** - * {@inheritdoc} - */ public function getChoices(): array { return $this->loader->loadChoiceList($this->value)->getChoices(); } - /** - * {@inheritdoc} - */ public function getValues(): array { return $this->loader->loadChoiceList($this->value)->getValues(); } - /** - * {@inheritdoc} - */ public function getStructuredValues(): array { return $this->loader->loadChoiceList($this->value)->getStructuredValues(); } - /** - * {@inheritdoc} - */ public function getOriginalKeys(): array { return $this->loader->loadChoiceList($this->value)->getOriginalKeys(); } - /** - * {@inheritdoc} - */ public function getChoicesForValues(array $values): array { return $this->loader->loadChoicesForValues($values, $this->value); } - /** - * {@inheritdoc} - */ public function getValuesForChoices(array $choices): array { return $this->loader->loadValuesForChoices($choices, $this->value); diff --git a/ChoiceList/Loader/AbstractChoiceLoader.php b/ChoiceList/Loader/AbstractChoiceLoader.php index 6aa2267a03..4554352d7a 100644 --- a/ChoiceList/Loader/AbstractChoiceLoader.php +++ b/ChoiceList/Loader/AbstractChoiceLoader.php @@ -23,17 +23,12 @@ abstract class AbstractChoiceLoader implements ChoiceLoaderInterface /** * @final - * - * {@inheritdoc} */ public function loadChoiceList(callable $value = null): ChoiceListInterface { return new ArrayChoiceList($this->choices ??= $this->loadChoices(), $value); } - /** - * {@inheritdoc} - */ public function loadChoicesForValues(array $values, callable $value = null): array { if (!$values) { @@ -43,9 +38,6 @@ public function loadChoicesForValues(array $values, callable $value = null): arr return $this->doLoadChoicesForValues($values, $value); } - /** - * {@inheritdoc} - */ public function loadValuesForChoices(array $choices, callable $value = null): array { if (!$choices) { diff --git a/ChoiceList/Loader/FilterChoiceLoaderDecorator.php b/ChoiceList/Loader/FilterChoiceLoaderDecorator.php index 02911b3d45..069941c1e2 100644 --- a/ChoiceList/Loader/FilterChoiceLoaderDecorator.php +++ b/ChoiceList/Loader/FilterChoiceLoaderDecorator.php @@ -52,17 +52,11 @@ protected function loadChoices(): iterable return $choices ?? []; } - /** - * {@inheritdoc} - */ public function loadChoicesForValues(array $values, callable $value = null): array { return array_filter($this->decoratedLoader->loadChoicesForValues($values, $value), $this->filter); } - /** - * {@inheritdoc} - */ public function loadValuesForChoices(array $choices, callable $value = null): array { return $this->decoratedLoader->loadValuesForChoices(array_filter($choices, $this->filter), $value); diff --git a/ChoiceList/Loader/IntlCallbackChoiceLoader.php b/ChoiceList/Loader/IntlCallbackChoiceLoader.php index a96b03ad34..448320f9d9 100644 --- a/ChoiceList/Loader/IntlCallbackChoiceLoader.php +++ b/ChoiceList/Loader/IntlCallbackChoiceLoader.php @@ -19,17 +19,11 @@ */ class IntlCallbackChoiceLoader extends CallbackChoiceLoader { - /** - * {@inheritdoc} - */ public function loadChoicesForValues(array $values, callable $value = null): array { return parent::loadChoicesForValues(array_filter($values), $value); } - /** - * {@inheritdoc} - */ public function loadValuesForChoices(array $choices, callable $value = null): array { $choices = array_filter($choices); diff --git a/ChoiceList/View/ChoiceGroupView.php b/ChoiceList/View/ChoiceGroupView.php index 1c692bb79b..453601a6f7 100644 --- a/ChoiceList/View/ChoiceGroupView.php +++ b/ChoiceList/View/ChoiceGroupView.php @@ -35,8 +35,6 @@ public function __construct(string $label, array $choices = []) } /** - * {@inheritdoc} - * * @return \Traversable */ public function getIterator(): \Traversable diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index d30a547ce8..159051046f 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -54,9 +54,6 @@ public function __construct(FormRegistryInterface $formRegistry, array $namespac $this->fileLinkFormatter = $fileLinkFormatter; } - /** - * {@inheritdoc} - */ protected function configure() { $this @@ -98,9 +95,6 @@ protected function configure() ; } - /** - * {@inheritdoc} - */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); diff --git a/Console/Descriptor/Descriptor.php b/Console/Descriptor/Descriptor.php index 975ae405f6..f6b09c2692 100644 --- a/Console/Descriptor/Descriptor.php +++ b/Console/Descriptor/Descriptor.php @@ -40,9 +40,6 @@ abstract class Descriptor implements DescriptorInterface protected $parents = []; protected $extensions = []; - /** - * {@inheritdoc} - */ public function describe(OutputInterface $output, ?object $object, array $options = []) { $this->output = $output instanceof OutputStyle ? $output : new SymfonyStyle(new ArrayInput([]), $output); diff --git a/Extension/Core/DataAccessor/CallbackAccessor.php b/Extension/Core/DataAccessor/CallbackAccessor.php index 617f7d692f..a7d5bb13fe 100644 --- a/Extension/Core/DataAccessor/CallbackAccessor.php +++ b/Extension/Core/DataAccessor/CallbackAccessor.php @@ -22,9 +22,6 @@ */ class CallbackAccessor implements DataAccessorInterface { - /** - * {@inheritdoc} - */ public function getValue(object|array $data, FormInterface $form): mixed { if (null === $getter = $form->getConfig()->getOption('getter')) { @@ -34,9 +31,6 @@ public function getValue(object|array $data, FormInterface $form): mixed return ($getter)($data, $form); } - /** - * {@inheritdoc} - */ public function setValue(object|array &$data, mixed $value, FormInterface $form): void { if (null === $setter = $form->getConfig()->getOption('setter')) { @@ -46,17 +40,11 @@ public function setValue(object|array &$data, mixed $value, FormInterface $form) ($setter)($data, $form->getData(), $form); } - /** - * {@inheritdoc} - */ public function isReadable(object|array $data, FormInterface $form): bool { return null !== $form->getConfig()->getOption('getter'); } - /** - * {@inheritdoc} - */ public function isWritable(object|array $data, FormInterface $form): bool { return null !== $form->getConfig()->getOption('setter'); diff --git a/Extension/Core/DataAccessor/ChainAccessor.php b/Extension/Core/DataAccessor/ChainAccessor.php index 46709b29ad..ac600f16f0 100644 --- a/Extension/Core/DataAccessor/ChainAccessor.php +++ b/Extension/Core/DataAccessor/ChainAccessor.php @@ -30,9 +30,6 @@ public function __construct(iterable $accessors) $this->accessors = $accessors; } - /** - * {@inheritdoc} - */ public function getValue(object|array $data, FormInterface $form): mixed { foreach ($this->accessors as $accessor) { @@ -44,9 +41,6 @@ public function getValue(object|array $data, FormInterface $form): mixed throw new AccessException('Unable to read from the given form data as no accessor in the chain is able to read the data.'); } - /** - * {@inheritdoc} - */ public function setValue(object|array &$data, mixed $value, FormInterface $form): void { foreach ($this->accessors as $accessor) { @@ -60,9 +54,6 @@ public function setValue(object|array &$data, mixed $value, FormInterface $form) throw new AccessException('Unable to write the given value as no accessor in the chain is able to set the data.'); } - /** - * {@inheritdoc} - */ public function isReadable(object|array $data, FormInterface $form): bool { foreach ($this->accessors as $accessor) { @@ -74,9 +65,6 @@ public function isReadable(object|array $data, FormInterface $form): bool return false; } - /** - * {@inheritdoc} - */ public function isWritable(object|array $data, FormInterface $form): bool { foreach ($this->accessors as $accessor) { diff --git a/Extension/Core/DataAccessor/PropertyPathAccessor.php b/Extension/Core/DataAccessor/PropertyPathAccessor.php index 57785a8967..85efa150f4 100644 --- a/Extension/Core/DataAccessor/PropertyPathAccessor.php +++ b/Extension/Core/DataAccessor/PropertyPathAccessor.php @@ -36,9 +36,6 @@ public function __construct(PropertyAccessorInterface $propertyAccessor = null) $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor(); } - /** - * {@inheritdoc} - */ public function getValue(object|array $data, FormInterface $form): mixed { if (null === $propertyPath = $form->getPropertyPath()) { @@ -48,9 +45,6 @@ public function getValue(object|array $data, FormInterface $form): mixed return $this->getPropertyValue($data, $propertyPath); } - /** - * {@inheritdoc} - */ public function setValue(object|array &$data, mixed $value, FormInterface $form): void { if (null === $propertyPath = $form->getPropertyPath()) { @@ -70,17 +64,11 @@ public function setValue(object|array &$data, mixed $value, FormInterface $form) } } - /** - * {@inheritdoc} - */ public function isReadable(object|array $data, FormInterface $form): bool { return null !== $form->getPropertyPath(); } - /** - * {@inheritdoc} - */ public function isWritable(object|array $data, FormInterface $form): bool { return null !== $form->getPropertyPath(); diff --git a/Extension/Core/DataMapper/CheckboxListMapper.php b/Extension/Core/DataMapper/CheckboxListMapper.php index 9ded60e830..f461e0e126 100644 --- a/Extension/Core/DataMapper/CheckboxListMapper.php +++ b/Extension/Core/DataMapper/CheckboxListMapper.php @@ -25,9 +25,6 @@ */ class CheckboxListMapper implements DataMapperInterface { - /** - * {@inheritdoc} - */ public function mapDataToForms(mixed $choices, \Traversable $checkboxes) { if (null === $choices) { @@ -44,9 +41,6 @@ public function mapDataToForms(mixed $choices, \Traversable $checkboxes) } } - /** - * {@inheritdoc} - */ public function mapFormsToData(\Traversable $checkboxes, mixed &$choices) { if (!\is_array($choices)) { diff --git a/Extension/Core/DataMapper/DataMapper.php b/Extension/Core/DataMapper/DataMapper.php index 58f6ff5e5a..0404af0844 100644 --- a/Extension/Core/DataMapper/DataMapper.php +++ b/Extension/Core/DataMapper/DataMapper.php @@ -35,9 +35,6 @@ public function __construct(DataAccessorInterface $dataAccessor = null) ]); } - /** - * {@inheritdoc} - */ public function mapDataToForms(mixed $data, \Traversable $forms): void { $empty = null === $data || [] === $data; @@ -57,9 +54,6 @@ public function mapDataToForms(mixed $data, \Traversable $forms): void } } - /** - * {@inheritdoc} - */ public function mapFormsToData(\Traversable $forms, mixed &$data): void { if (null === $data) { diff --git a/Extension/Core/DataMapper/RadioListMapper.php b/Extension/Core/DataMapper/RadioListMapper.php index ebf761c4dd..4ae0fc3c8f 100644 --- a/Extension/Core/DataMapper/RadioListMapper.php +++ b/Extension/Core/DataMapper/RadioListMapper.php @@ -25,9 +25,6 @@ */ class RadioListMapper implements DataMapperInterface { - /** - * {@inheritdoc} - */ public function mapDataToForms(mixed $choice, \Traversable $radios) { if (!\is_string($choice)) { @@ -40,9 +37,6 @@ public function mapDataToForms(mixed $choice, \Traversable $radios) } } - /** - * {@inheritdoc} - */ public function mapFormsToData(\Traversable $radios, mixed &$choice) { if (null !== $choice && !\is_string($choice)) { diff --git a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php index 645237363c..e6e575d769 100644 --- a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php @@ -28,9 +28,6 @@ public function __construct(bool $multiple = false) $this->multiple = $multiple; } - /** - * {@inheritdoc} - */ public function transform(mixed $dateTimeZone): mixed { if (null === $dateTimeZone) { @@ -52,9 +49,6 @@ public function transform(mixed $dateTimeZone): mixed return $dateTimeZone->getName(); } - /** - * {@inheritdoc} - */ public function reverseTransform(mixed $value): mixed { if (null === $value) { diff --git a/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php index ccf4701b90..db774a075c 100644 --- a/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php @@ -33,9 +33,6 @@ public function __construct(?bool $grouping = false, ?int $roundingMode = \Numbe parent::__construct(0, $grouping, $roundingMode, $locale); } - /** - * {@inheritdoc} - */ public function reverseTransform(mixed $value): int|float|null { $decimalSeparator = $this->getNumberFormatter()->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL); diff --git a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php index f158ecba2d..86849c4ea8 100644 --- a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php @@ -28,9 +28,6 @@ public function __construct(bool $multiple = false) $this->multiple = $multiple; } - /** - * {@inheritdoc} - */ public function transform(mixed $intlTimeZone): mixed { if (null === $intlTimeZone) { @@ -52,9 +49,6 @@ public function transform(mixed $intlTimeZone): mixed return $intlTimeZone->getID(); } - /** - * {@inheritdoc} - */ public function reverseTransform(mixed $value): mixed { if (null === $value) { diff --git a/Extension/Core/Type/BaseType.php b/Extension/Core/Type/BaseType.php index 4ac58bd2ac..8606802e12 100644 --- a/Extension/Core/Type/BaseType.php +++ b/Extension/Core/Type/BaseType.php @@ -28,18 +28,12 @@ */ abstract class BaseType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->setDisabled($options['disabled']); $builder->setAutoInitialize($options['auto_initialize']); } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $name = $form->getName(); @@ -118,9 +112,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/BirthdayType.php b/Extension/Core/Type/BirthdayType.php index 2a78e1d77c..1be317ebd3 100644 --- a/Extension/Core/Type/BirthdayType.php +++ b/Extension/Core/Type/BirthdayType.php @@ -16,9 +16,6 @@ class BirthdayType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -29,17 +26,11 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('years', 'array'); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return DateType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'birthday'; diff --git a/Extension/Core/Type/ButtonType.php b/Extension/Core/Type/ButtonType.php index 2fb77f9eda..ee39cee56b 100644 --- a/Extension/Core/Type/ButtonType.php +++ b/Extension/Core/Type/ButtonType.php @@ -21,25 +21,16 @@ */ class ButtonType extends BaseType implements ButtonTypeInterface { - /** - * {@inheritdoc} - */ public function getParent(): ?string { return null; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'button'; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); diff --git a/Extension/Core/Type/CheckboxType.php b/Extension/Core/Type/CheckboxType.php index 96c557d0a3..d513694a4c 100644 --- a/Extension/Core/Type/CheckboxType.php +++ b/Extension/Core/Type/CheckboxType.php @@ -20,9 +20,6 @@ class CheckboxType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { // Unlike in other types, where the data is NULL by default, it @@ -35,9 +32,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) $builder->addViewTransformer(new BooleanToStringTransformer($options['value'], $options['false_values'])); } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars = array_replace($view->vars, [ @@ -46,9 +40,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $emptyData = function (FormInterface $form, $viewData) { @@ -69,9 +60,6 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('false_values', 'array'); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'checkbox'; diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 3fc8707650..2dde39e8af 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -62,9 +62,6 @@ public function __construct(ChoiceListFactoryInterface $choiceListFactory = null $this->translator = $translator; } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $unknownValues = []; @@ -218,9 +215,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) }, 256); } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $choiceTranslationDomain = $options['choice_translation_domain']; @@ -277,9 +271,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function finishView(FormView $view, FormInterface $form, array $options) { if ($options['expanded']) { @@ -297,9 +288,6 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $emptyData = function (Options $options) { @@ -391,9 +379,6 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('group_by', ['null', 'callable', 'string', PropertyPath::class, GroupBy::class]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'choice'; diff --git a/Extension/Core/Type/CollectionType.php b/Extension/Core/Type/CollectionType.php index 4ec0f1be70..c310441cc7 100644 --- a/Extension/Core/Type/CollectionType.php +++ b/Extension/Core/Type/CollectionType.php @@ -21,9 +21,6 @@ class CollectionType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { if ($options['allow_add'] && $options['prototype']) { @@ -51,9 +48,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) $builder->addEventSubscriber($resizeListener); } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars = array_replace($view->vars, [ @@ -67,9 +61,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function finishView(FormView $view, FormInterface $form, array $options) { $prefixOffset = -2; @@ -101,9 +92,6 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $entryOptionsNormalizer = function (Options $options, $value) { @@ -131,9 +119,6 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('prototype_options', 'array'); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'collection'; diff --git a/Extension/Core/Type/ColorType.php b/Extension/Core/Type/ColorType.php index fb53d7fd03..26d670634b 100644 --- a/Extension/Core/Type/ColorType.php +++ b/Extension/Core/Type/ColorType.php @@ -33,9 +33,6 @@ public function __construct(TranslatorInterface $translator = null) $this->translator = $translator; } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { if (!$options['html5']) { @@ -62,9 +59,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) }); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -75,17 +69,11 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('html5', 'bool'); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'color'; diff --git a/Extension/Core/Type/CountryType.php b/Extension/Core/Type/CountryType.php index 8d5c6487d2..25aa652f5c 100644 --- a/Extension/Core/Type/CountryType.php +++ b/Extension/Core/Type/CountryType.php @@ -22,9 +22,6 @@ class CountryType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -50,17 +47,11 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('alpha3', 'bool'); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'country'; diff --git a/Extension/Core/Type/CurrencyType.php b/Extension/Core/Type/CurrencyType.php index fe7842fd26..435bc15709 100644 --- a/Extension/Core/Type/CurrencyType.php +++ b/Extension/Core/Type/CurrencyType.php @@ -22,9 +22,6 @@ class CurrencyType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -47,17 +44,11 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('choice_translation_locale', ['null', 'string']); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'currency'; diff --git a/Extension/Core/Type/DateIntervalType.php b/Extension/Core/Type/DateIntervalType.php index eeb43fc647..e745c1af04 100644 --- a/Extension/Core/Type/DateIntervalType.php +++ b/Extension/Core/Type/DateIntervalType.php @@ -43,9 +43,6 @@ class DateIntervalType extends AbstractType 'choice' => ChoiceType::class, ]; - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { if (!$options['with_years'] && !$options['with_months'] && !$options['with_weeks'] && !$options['with_days'] && !$options['with_hours'] && !$options['with_minutes'] && !$options['with_seconds']) { @@ -148,9 +145,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $vars = [ @@ -163,9 +157,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) $view->vars = array_replace($view->vars, $vars); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $compound = function (Options $options) { @@ -277,9 +268,6 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('labels', 'array'); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'dateinterval'; diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index dc1549a521..35022530e6 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -47,9 +47,6 @@ class DateTimeType extends AbstractType \IntlDateFormatter::SHORT, ]; - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $parts = ['year', 'month', 'day', 'hour']; @@ -202,9 +199,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['widget'] = $options['widget']; @@ -226,9 +220,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $compound = function (Options $options) { @@ -348,9 +339,6 @@ public function configureOptions(OptionsResolver $resolver) }); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'datetime'; diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index 1360ed450f..d88819ebd6 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -43,9 +43,6 @@ class DateType extends AbstractType 'choice' => ChoiceType::class, ]; - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $dateFormat = \is_int($options['format']) ? $options['format'] : self::DEFAULT_FORMAT; @@ -182,9 +179,6 @@ class_exists(\IntlTimeZone::class, false) ? \IntlTimeZone::createDefault() : nul } } - /** - * {@inheritdoc} - */ public function finishView(FormView $view, FormInterface $form, array $options) { $view->vars['widget'] = $options['widget']; @@ -222,9 +216,6 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $compound = function (Options $options) { @@ -333,9 +324,6 @@ public function configureOptions(OptionsResolver $resolver) }); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'date'; diff --git a/Extension/Core/Type/EmailType.php b/Extension/Core/Type/EmailType.php index 4284db1869..70e8c8a191 100644 --- a/Extension/Core/Type/EmailType.php +++ b/Extension/Core/Type/EmailType.php @@ -16,9 +16,6 @@ class EmailType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -26,17 +23,11 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'email'; diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index b99b734162..9e8e81394e 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -41,9 +41,6 @@ public function __construct(TranslatorInterface $translator = null) $this->translator = $translator; } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { // Ensure that submitted data is always an uploaded file or an array of some @@ -85,9 +82,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) }); } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { if ($options['multiple']) { @@ -101,17 +95,11 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } - /** - * {@inheritdoc} - */ public function finishView(FormView $view, FormInterface $form, array $options) { $view->vars['multipart'] = true; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $dataClass = null; @@ -135,9 +123,6 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'file'; diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index efb61c739b..451e7381d1 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -38,9 +38,6 @@ public function __construct(PropertyAccessorInterface $propertyAccessor = null) ])); } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); @@ -69,9 +66,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) $builder->setIsEmptyCallback($options['is_empty_callback']); } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { parent::buildView($view, $form, $options); @@ -122,9 +116,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } - /** - * {@inheritdoc} - */ public function finishView(FormView $view, FormInterface $form, array $options) { $multipart = false; @@ -139,9 +130,6 @@ public function finishView(FormView $view, FormInterface $form, array $options) $view->vars['multipart'] = $multipart; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); @@ -232,17 +220,11 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setInfo('setter', 'A callable that accepts three arguments (a reference to the view data, the submitted value and the current form field).'); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return null; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'form'; diff --git a/Extension/Core/Type/HiddenType.php b/Extension/Core/Type/HiddenType.php index b54ea01ca1..a69e172bc6 100644 --- a/Extension/Core/Type/HiddenType.php +++ b/Extension/Core/Type/HiddenType.php @@ -16,9 +16,6 @@ class HiddenType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -31,9 +28,6 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'hidden'; diff --git a/Extension/Core/Type/IntegerType.php b/Extension/Core/Type/IntegerType.php index 3d69448e34..49e37f7490 100644 --- a/Extension/Core/Type/IntegerType.php +++ b/Extension/Core/Type/IntegerType.php @@ -20,17 +20,11 @@ class IntegerType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addViewTransformer(new IntegerToLocalizedStringTransformer($options['grouping'], $options['rounding_mode'], !$options['grouping'] ? 'en' : null)); } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { if ($options['grouping']) { @@ -38,9 +32,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -62,9 +53,6 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'integer'; diff --git a/Extension/Core/Type/LanguageType.php b/Extension/Core/Type/LanguageType.php index b1184a4309..f875657eaa 100644 --- a/Extension/Core/Type/LanguageType.php +++ b/Extension/Core/Type/LanguageType.php @@ -23,9 +23,6 @@ class LanguageType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -74,17 +71,11 @@ public function configureOptions(OptionsResolver $resolver) }); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'language'; diff --git a/Extension/Core/Type/LocaleType.php b/Extension/Core/Type/LocaleType.php index b0cb9a8e00..d4adca1f59 100644 --- a/Extension/Core/Type/LocaleType.php +++ b/Extension/Core/Type/LocaleType.php @@ -22,9 +22,6 @@ class LocaleType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -47,17 +44,11 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('choice_translation_locale', ['null', 'string']); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'locale'; diff --git a/Extension/Core/Type/MoneyType.php b/Extension/Core/Type/MoneyType.php index cf6246acc8..e9ecd409eb 100644 --- a/Extension/Core/Type/MoneyType.php +++ b/Extension/Core/Type/MoneyType.php @@ -24,9 +24,6 @@ class MoneyType extends AbstractType { protected static $patterns = []; - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { // Values used in HTML5 number inputs should be formatted as in "1234.5", ie. 'en' format without grouping, @@ -42,9 +39,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['money_pattern'] = self::getPattern($options['currency']); @@ -54,9 +48,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -93,9 +84,6 @@ public function configureOptions(OptionsResolver $resolver) }); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'money'; diff --git a/Extension/Core/Type/NumberType.php b/Extension/Core/Type/NumberType.php index fd75f689d7..6d2d9eca2e 100644 --- a/Extension/Core/Type/NumberType.php +++ b/Extension/Core/Type/NumberType.php @@ -23,9 +23,6 @@ class NumberType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addViewTransformer(new NumberToLocalizedStringTransformer( @@ -40,9 +37,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { if ($options['html5']) { @@ -52,9 +46,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -90,9 +81,6 @@ public function configureOptions(OptionsResolver $resolver) }); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'number'; diff --git a/Extension/Core/Type/PasswordType.php b/Extension/Core/Type/PasswordType.php index cbb0d97787..495160361d 100644 --- a/Extension/Core/Type/PasswordType.php +++ b/Extension/Core/Type/PasswordType.php @@ -18,9 +18,6 @@ class PasswordType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { if ($options['always_empty'] || !$form->isSubmitted()) { @@ -28,9 +25,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -40,17 +34,11 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'password'; diff --git a/Extension/Core/Type/PercentType.php b/Extension/Core/Type/PercentType.php index 9b98f9b089..d006c6d5e1 100644 --- a/Extension/Core/Type/PercentType.php +++ b/Extension/Core/Type/PercentType.php @@ -20,9 +20,6 @@ class PercentType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addViewTransformer(new PercentToLocalizedStringTransformer( @@ -33,9 +30,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) )); } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['symbol'] = $options['symbol']; @@ -45,9 +39,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -78,9 +69,6 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('html5', 'bool'); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'percent'; diff --git a/Extension/Core/Type/RadioType.php b/Extension/Core/Type/RadioType.php index c668420c2c..d40f39106d 100644 --- a/Extension/Core/Type/RadioType.php +++ b/Extension/Core/Type/RadioType.php @@ -16,9 +16,6 @@ class RadioType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -26,17 +23,11 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return CheckboxType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'radio'; diff --git a/Extension/Core/Type/RangeType.php b/Extension/Core/Type/RangeType.php index e150323b10..857028c9c1 100644 --- a/Extension/Core/Type/RangeType.php +++ b/Extension/Core/Type/RangeType.php @@ -16,9 +16,6 @@ class RangeType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -26,17 +23,11 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'range'; diff --git a/Extension/Core/Type/RepeatedType.php b/Extension/Core/Type/RepeatedType.php index a511cf070e..fb55bf2940 100644 --- a/Extension/Core/Type/RepeatedType.php +++ b/Extension/Core/Type/RepeatedType.php @@ -18,9 +18,6 @@ class RepeatedType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { // Overwrite required option for child fields @@ -44,9 +41,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -65,9 +59,6 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('second_options', 'array'); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'repeated'; diff --git a/Extension/Core/Type/ResetType.php b/Extension/Core/Type/ResetType.php index 40801c0d09..9a53a3dc68 100644 --- a/Extension/Core/Type/ResetType.php +++ b/Extension/Core/Type/ResetType.php @@ -21,17 +21,11 @@ */ class ResetType extends AbstractType implements ButtonTypeInterface { - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ButtonType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'reset'; diff --git a/Extension/Core/Type/SearchType.php b/Extension/Core/Type/SearchType.php index e29ca152b3..76ed420118 100644 --- a/Extension/Core/Type/SearchType.php +++ b/Extension/Core/Type/SearchType.php @@ -16,9 +16,6 @@ class SearchType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -26,17 +23,11 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'search'; diff --git a/Extension/Core/Type/SubmitType.php b/Extension/Core/Type/SubmitType.php index 7f423668b1..dde4457652 100644 --- a/Extension/Core/Type/SubmitType.php +++ b/Extension/Core/Type/SubmitType.php @@ -33,26 +33,17 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefault('validate', true); $resolver->setAllowedTypes('validate', 'bool'); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ButtonType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'submit'; diff --git a/Extension/Core/Type/TelType.php b/Extension/Core/Type/TelType.php index 36ec764001..8ba7fd843b 100644 --- a/Extension/Core/Type/TelType.php +++ b/Extension/Core/Type/TelType.php @@ -16,9 +16,6 @@ class TelType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -26,17 +23,11 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'tel'; diff --git a/Extension/Core/Type/TextType.php b/Extension/Core/Type/TextType.php index 4bbd89efe7..dd019192bc 100644 --- a/Extension/Core/Type/TextType.php +++ b/Extension/Core/Type/TextType.php @@ -30,9 +30,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -40,26 +37,17 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'text'; } - /** - * {@inheritdoc} - */ public function transform(mixed $data): mixed { // Model data should not be transformed return $data; } - /** - * {@inheritdoc} - */ public function reverseTransform(mixed $data): mixed { return $data ?? ''; diff --git a/Extension/Core/Type/TextareaType.php b/Extension/Core/Type/TextareaType.php index 5aca850386..43d8e0eac4 100644 --- a/Extension/Core/Type/TextareaType.php +++ b/Extension/Core/Type/TextareaType.php @@ -17,26 +17,17 @@ class TextareaType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['pattern'] = null; unset($view->vars['attr']['pattern']); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'textarea'; diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 11f4c36e20..2b8bbb5010 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -34,9 +34,6 @@ class TimeType extends AbstractType 'choice' => ChoiceType::class, ]; - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $parts = ['hour']; @@ -212,9 +209,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars = array_replace($view->vars, [ @@ -239,9 +233,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $compound = function (Options $options) { @@ -374,9 +365,6 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('reference_date', ['null', \DateTimeInterface::class]); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'time'; diff --git a/Extension/Core/Type/TimezoneType.php b/Extension/Core/Type/TimezoneType.php index d9ef804fd7..edea6678e2 100644 --- a/Extension/Core/Type/TimezoneType.php +++ b/Extension/Core/Type/TimezoneType.php @@ -25,9 +25,6 @@ class TimezoneType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { if ('datetimezone' === $options['input']) { @@ -37,9 +34,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -91,17 +85,11 @@ public function configureOptions(OptionsResolver $resolver) }); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ChoiceType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'timezone'; diff --git a/Extension/Core/Type/TransformationFailureExtension.php b/Extension/Core/Type/TransformationFailureExtension.php index c73bd29582..4fb9cae664 100644 --- a/Extension/Core/Type/TransformationFailureExtension.php +++ b/Extension/Core/Type/TransformationFailureExtension.php @@ -35,9 +35,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * {@inheritdoc} - */ public static function getExtendedTypes(): iterable { return [FormType::class]; diff --git a/Extension/Core/Type/UlidType.php b/Extension/Core/Type/UlidType.php index abda5fd0b7..24eab77d8e 100644 --- a/Extension/Core/Type/UlidType.php +++ b/Extension/Core/Type/UlidType.php @@ -21,9 +21,6 @@ */ class UlidType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder @@ -31,9 +28,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/UrlType.php b/Extension/Core/Type/UrlType.php index 36aee7699f..313fbedbf5 100644 --- a/Extension/Core/Type/UrlType.php +++ b/Extension/Core/Type/UrlType.php @@ -20,9 +20,6 @@ class UrlType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { if (null !== $options['default_protocol']) { @@ -30,9 +27,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { if ($options['default_protocol']) { @@ -41,9 +35,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -54,17 +45,11 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('default_protocol', ['null', 'string']); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return TextType::class; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'url'; diff --git a/Extension/Core/Type/UuidType.php b/Extension/Core/Type/UuidType.php index f551d639a2..214d308689 100644 --- a/Extension/Core/Type/UuidType.php +++ b/Extension/Core/Type/UuidType.php @@ -21,9 +21,6 @@ */ class UuidType extends AbstractType { - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder @@ -31,9 +28,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/WeekType.php b/Extension/Core/Type/WeekType.php index 71f3146b7d..760bb880b1 100644 --- a/Extension/Core/Type/WeekType.php +++ b/Extension/Core/Type/WeekType.php @@ -28,9 +28,6 @@ class WeekType extends AbstractType 'choice' => ChoiceType::class, ]; - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { if ('string' === $options['input']) { @@ -83,9 +80,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['widget'] = $options['widget']; @@ -95,9 +89,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $compound = function (Options $options) { @@ -183,9 +174,6 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('weeks', 'int[]'); } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return 'week'; diff --git a/Extension/Csrf/CsrfExtension.php b/Extension/Csrf/CsrfExtension.php index 97228f56c9..026bed3604 100644 --- a/Extension/Csrf/CsrfExtension.php +++ b/Extension/Csrf/CsrfExtension.php @@ -33,9 +33,6 @@ public function __construct(CsrfTokenManagerInterface $tokenManager, TranslatorI $this->translationDomain = $translationDomain; } - /** - * {@inheritdoc} - */ protected function loadTypeExtensions(): array { return [ diff --git a/Extension/Csrf/Type/FormTypeCsrfExtension.php b/Extension/Csrf/Type/FormTypeCsrfExtension.php index ca3bf22dff..ec96dc6aed 100644 --- a/Extension/Csrf/Type/FormTypeCsrfExtension.php +++ b/Extension/Csrf/Type/FormTypeCsrfExtension.php @@ -86,9 +86,6 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -100,9 +97,6 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public static function getExtendedTypes(): iterable { return [FormType::class]; diff --git a/Extension/DataCollector/DataCollectorExtension.php b/Extension/DataCollector/DataCollectorExtension.php index cafd0ffc66..50b36bd67f 100644 --- a/Extension/DataCollector/DataCollectorExtension.php +++ b/Extension/DataCollector/DataCollectorExtension.php @@ -28,9 +28,6 @@ public function __construct(FormDataCollectorInterface $dataCollector) $this->dataCollector = $dataCollector; } - /** - * {@inheritdoc} - */ protected function loadTypeExtensions(): array { return [ diff --git a/Extension/DataCollector/EventListener/DataCollectorListener.php b/Extension/DataCollector/EventListener/DataCollectorListener.php index dbc36123c7..be30912c7c 100644 --- a/Extension/DataCollector/EventListener/DataCollectorListener.php +++ b/Extension/DataCollector/EventListener/DataCollectorListener.php @@ -31,9 +31,6 @@ public function __construct(FormDataCollectorInterface $dataCollector) $this->dataCollector = $dataCollector; } - /** - * {@inheritdoc} - */ public static function getSubscribedEvents(): array { return [ diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index f4640f1ff0..525d8ffecc 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -89,17 +89,11 @@ public function reset() ]; } - /** - * {@inheritdoc} - */ public function associateFormWithView(FormInterface $form, FormView $view) { $this->formsByView[spl_object_hash($view)] = spl_object_hash($form); } - /** - * {@inheritdoc} - */ public function collectConfiguration(FormInterface $form) { $hash = spl_object_hash($form); @@ -118,9 +112,6 @@ public function collectConfiguration(FormInterface $form) } } - /** - * {@inheritdoc} - */ public function collectDefaultData(FormInterface $form) { $hash = spl_object_hash($form); @@ -140,9 +131,6 @@ public function collectDefaultData(FormInterface $form) } } - /** - * {@inheritdoc} - */ public function collectSubmittedData(FormInterface $form) { $hash = spl_object_hash($form); @@ -174,9 +162,6 @@ public function collectSubmittedData(FormInterface $form) } } - /** - * {@inheritdoc} - */ public function collectViewVariables(FormView $view) { $hash = spl_object_hash($view); @@ -195,33 +180,21 @@ public function collectViewVariables(FormView $view) } } - /** - * {@inheritdoc} - */ public function buildPreliminaryFormTree(FormInterface $form) { $this->data['forms'][$form->getName()] = &$this->recursiveBuildPreliminaryFormTree($form, $this->data['forms_by_hash']); } - /** - * {@inheritdoc} - */ public function buildFinalFormTree(FormInterface $form, FormView $view) { $this->data['forms'][$form->getName()] = &$this->recursiveBuildFinalFormTree($form, $view, $this->data['forms_by_hash']); } - /** - * {@inheritdoc} - */ public function getName(): string { return 'form'; } - /** - * {@inheritdoc} - */ public function getData(): array|Data { return $this->data; @@ -243,9 +216,6 @@ public function __sleep(): array return parent::__sleep(); } - /** - * {@inheritdoc} - */ protected function getCasters(): array { return parent::getCasters() + [ diff --git a/Extension/DataCollector/FormDataExtractor.php b/Extension/DataCollector/FormDataExtractor.php index e9a54df8fe..028e8c06d0 100644 --- a/Extension/DataCollector/FormDataExtractor.php +++ b/Extension/DataCollector/FormDataExtractor.php @@ -22,9 +22,6 @@ */ class FormDataExtractor implements FormDataExtractorInterface { - /** - * {@inheritdoc} - */ public function extractConfiguration(FormInterface $form): array { $data = [ @@ -50,9 +47,6 @@ public function extractConfiguration(FormInterface $form): array return $data; } - /** - * {@inheritdoc} - */ public function extractDefaultData(FormInterface $form): array { $data = [ @@ -73,9 +67,6 @@ public function extractDefaultData(FormInterface $form): array return $data; } - /** - * {@inheritdoc} - */ public function extractSubmittedData(FormInterface $form): array { $data = [ @@ -132,9 +123,6 @@ public function extractSubmittedData(FormInterface $form): array return $data; } - /** - * {@inheritdoc} - */ public function extractViewVariables(FormView $view): array { $data = [ diff --git a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php index 7563e778e8..d273fbbc75 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php @@ -36,41 +36,26 @@ public function __construct(ResolvedFormTypeInterface $proxiedType, FormDataColl $this->dataCollector = $dataCollector; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return $this->proxiedType->getBlockPrefix(); } - /** - * {@inheritdoc} - */ public function getParent(): ?ResolvedFormTypeInterface { return $this->proxiedType->getParent(); } - /** - * {@inheritdoc} - */ public function getInnerType(): FormTypeInterface { return $this->proxiedType->getInnerType(); } - /** - * {@inheritdoc} - */ public function getTypeExtensions(): array { return $this->proxiedType->getTypeExtensions(); } - /** - * {@inheritdoc} - */ public function createBuilder(FormFactoryInterface $factory, string $name, array $options = []): FormBuilderInterface { $builder = $this->proxiedType->createBuilder($factory, $name, $options); @@ -81,33 +66,21 @@ public function createBuilder(FormFactoryInterface $factory, string $name, array return $builder; } - /** - * {@inheritdoc} - */ public function createView(FormInterface $form, FormView $parent = null): FormView { return $this->proxiedType->createView($form, $parent); } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $this->proxiedType->buildForm($builder, $options); } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $this->proxiedType->buildView($view, $form, $options); } - /** - * {@inheritdoc} - */ public function finishView(FormView $view, FormInterface $form, array $options) { $this->proxiedType->finishView($view, $form, $options); @@ -132,9 +105,6 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function getOptionsResolver(): OptionsResolver { return $this->proxiedType->getOptionsResolver(); diff --git a/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php index 835a7e879a..eea5bfd4ae 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php @@ -33,9 +33,6 @@ public function __construct(ResolvedFormTypeFactoryInterface $proxiedFactory, Fo $this->dataCollector = $dataCollector; } - /** - * {@inheritdoc} - */ public function createResolvedType(FormTypeInterface $type, array $typeExtensions, ResolvedFormTypeInterface $parent = null): ResolvedFormTypeInterface { return new ResolvedTypeDataCollectorProxy( diff --git a/Extension/DataCollector/Type/DataCollectorTypeExtension.php b/Extension/DataCollector/Type/DataCollectorTypeExtension.php index 73f8a214fa..d014f0e457 100644 --- a/Extension/DataCollector/Type/DataCollectorTypeExtension.php +++ b/Extension/DataCollector/Type/DataCollectorTypeExtension.php @@ -32,17 +32,11 @@ public function __construct(FormDataCollectorInterface $dataCollector) $this->listener = new DataCollectorListener($dataCollector); } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventSubscriber($this->listener); } - /** - * {@inheritdoc} - */ public static function getExtendedTypes(): iterable { return [FormType::class]; diff --git a/Extension/DependencyInjection/DependencyInjectionExtension.php b/Extension/DependencyInjection/DependencyInjectionExtension.php index 5fe0371df7..0b978d693d 100644 --- a/Extension/DependencyInjection/DependencyInjectionExtension.php +++ b/Extension/DependencyInjection/DependencyInjectionExtension.php @@ -36,9 +36,6 @@ public function __construct(ContainerInterface $typeContainer, array $typeExtens $this->guesserServices = $guesserServices; } - /** - * {@inheritdoc} - */ public function getType(string $name): FormTypeInterface { if (!$this->typeContainer->has($name)) { @@ -48,17 +45,11 @@ public function getType(string $name): FormTypeInterface return $this->typeContainer->get($name); } - /** - * {@inheritdoc} - */ public function hasType(string $name): bool { return $this->typeContainer->has($name); } - /** - * {@inheritdoc} - */ public function getTypeExtensions(string $name): array { $extensions = []; @@ -82,17 +73,11 @@ public function getTypeExtensions(string $name): array return $extensions; } - /** - * {@inheritdoc} - */ public function hasTypeExtensions(string $name): bool { return isset($this->typeExtensionServices[$name]); } - /** - * {@inheritdoc} - */ public function getTypeGuesser(): ?FormTypeGuesserInterface { if (!$this->guesserLoaded) { diff --git a/Extension/HttpFoundation/HttpFoundationRequestHandler.php b/Extension/HttpFoundation/HttpFoundationRequestHandler.php index 17317c780f..3b1aaebf02 100644 --- a/Extension/HttpFoundation/HttpFoundationRequestHandler.php +++ b/Extension/HttpFoundation/HttpFoundationRequestHandler.php @@ -35,9 +35,6 @@ public function __construct(ServerParams $serverParams = null) $this->serverParams = $serverParams ?? new ServerParams(); } - /** - * {@inheritdoc} - */ public function handleRequest(FormInterface $form, mixed $request = null) { if (!$request instanceof Request) { @@ -109,9 +106,6 @@ public function handleRequest(FormInterface $form, mixed $request = null) $form->submit($data, 'PATCH' !== $method); } - /** - * {@inheritdoc} - */ public function isFileUpload(mixed $data): bool { return $data instanceof File; diff --git a/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php b/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php index 3d283d0e4e..9a5ae66618 100644 --- a/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php +++ b/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php @@ -29,17 +29,11 @@ public function __construct(RequestHandlerInterface $requestHandler = null) $this->requestHandler = $requestHandler ?? new HttpFoundationRequestHandler(); } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->setRequestHandler($this->requestHandler); } - /** - * {@inheritdoc} - */ public static function getExtendedTypes(): iterable { return [FormType::class]; diff --git a/Extension/Validator/Constraints/Form.php b/Extension/Validator/Constraints/Form.php index 694281ddd1..6dec01be22 100644 --- a/Extension/Validator/Constraints/Form.php +++ b/Extension/Validator/Constraints/Form.php @@ -31,9 +31,6 @@ class Form extends Constraint */ protected static $errorNames = self::ERROR_NAMES; - /** - * {@inheritdoc} - */ public function getTargets(): string|array { return self::CLASS_CONSTRAINT; diff --git a/Extension/Validator/Constraints/FormValidator.php b/Extension/Validator/Constraints/FormValidator.php index 3b5b699ce3..ada84f14bf 100644 --- a/Extension/Validator/Constraints/FormValidator.php +++ b/Extension/Validator/Constraints/FormValidator.php @@ -29,9 +29,6 @@ class FormValidator extends ConstraintValidator */ private \SplObjectStorage $resolvedGroups; - /** - * {@inheritdoc} - */ public function validate(mixed $form, Constraint $formConstraint) { if (!$formConstraint instanceof Form) { diff --git a/Extension/Validator/EventListener/ValidationListener.php b/Extension/Validator/EventListener/ValidationListener.php index 3d010b77c5..2963d6f7b0 100644 --- a/Extension/Validator/EventListener/ValidationListener.php +++ b/Extension/Validator/EventListener/ValidationListener.php @@ -26,9 +26,6 @@ class ValidationListener implements EventSubscriberInterface private ValidatorInterface $validator; private ViolationMapperInterface $violationMapper; - /** - * {@inheritdoc} - */ public static function getSubscribedEvents(): array { return [FormEvents::POST_SUBMIT => 'validateForm']; diff --git a/Extension/Validator/Type/BaseValidatorExtension.php b/Extension/Validator/Type/BaseValidatorExtension.php index 0e9e2a9d7e..9366a20f89 100644 --- a/Extension/Validator/Type/BaseValidatorExtension.php +++ b/Extension/Validator/Type/BaseValidatorExtension.php @@ -24,9 +24,6 @@ */ abstract class BaseValidatorExtension extends AbstractTypeExtension { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { // Make sure that validation groups end up as null, closure or array diff --git a/Extension/Validator/Type/FormTypeValidatorExtension.php b/Extension/Validator/Type/FormTypeValidatorExtension.php index 40fe64df40..26653dc998 100644 --- a/Extension/Validator/Type/FormTypeValidatorExtension.php +++ b/Extension/Validator/Type/FormTypeValidatorExtension.php @@ -37,17 +37,11 @@ public function __construct(ValidatorInterface $validator, bool $legacyErrorMess $this->violationMapper = new ViolationMapper($formRenderer, $translator); } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventSubscriber(new ValidationListener($this->validator, $this->violationMapper)); } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); @@ -69,9 +63,6 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setNormalizer('constraints', $constraintsNormalizer); } - /** - * {@inheritdoc} - */ public static function getExtendedTypes(): iterable { return [FormType::class]; diff --git a/Extension/Validator/Type/RepeatedTypeValidatorExtension.php b/Extension/Validator/Type/RepeatedTypeValidatorExtension.php index 4bda0b27d1..664a3edae2 100644 --- a/Extension/Validator/Type/RepeatedTypeValidatorExtension.php +++ b/Extension/Validator/Type/RepeatedTypeValidatorExtension.php @@ -21,9 +21,6 @@ */ class RepeatedTypeValidatorExtension extends AbstractTypeExtension { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { // Map errors to the first field @@ -36,9 +33,6 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public static function getExtendedTypes(): iterable { return [RepeatedType::class]; diff --git a/Extension/Validator/Type/SubmitTypeValidatorExtension.php b/Extension/Validator/Type/SubmitTypeValidatorExtension.php index ea273d0ad9..8efae7d52e 100644 --- a/Extension/Validator/Type/SubmitTypeValidatorExtension.php +++ b/Extension/Validator/Type/SubmitTypeValidatorExtension.php @@ -18,9 +18,6 @@ */ class SubmitTypeValidatorExtension extends BaseValidatorExtension { - /** - * {@inheritdoc} - */ public static function getExtendedTypes(): iterable { return [SubmitType::class]; diff --git a/Extension/Validator/Type/UploadValidatorExtension.php b/Extension/Validator/Type/UploadValidatorExtension.php index b5ddecd99d..14f6c8f2d8 100644 --- a/Extension/Validator/Type/UploadValidatorExtension.php +++ b/Extension/Validator/Type/UploadValidatorExtension.php @@ -32,9 +32,6 @@ public function __construct(TranslatorInterface $translator, string $translation $this->translationDomain = $translationDomain; } - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $translator = $this->translator; @@ -46,9 +43,6 @@ public function configureOptions(OptionsResolver $resolver) }); } - /** - * {@inheritdoc} - */ public static function getExtendedTypes(): iterable { return [FormType::class]; diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index 5eba3a291a..46738b401e 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -64,9 +64,6 @@ public function __construct(MetadataFactoryInterface $metadataFactory) $this->metadataFactory = $metadataFactory; } - /** - * {@inheritdoc} - */ public function guessType(string $class, string $property): ?TypeGuess { return $this->guess($class, $property, function (Constraint $constraint) { @@ -74,9 +71,6 @@ public function guessType(string $class, string $property): ?TypeGuess }); } - /** - * {@inheritdoc} - */ public function guessRequired(string $class, string $property): ?ValueGuess { return $this->guess($class, $property, function (Constraint $constraint) { @@ -86,9 +80,6 @@ public function guessRequired(string $class, string $property): ?ValueGuess }, false); } - /** - * {@inheritdoc} - */ public function guessMaxLength(string $class, string $property): ?ValueGuess { return $this->guess($class, $property, function (Constraint $constraint) { @@ -96,9 +87,6 @@ public function guessMaxLength(string $class, string $property): ?ValueGuess }); } - /** - * {@inheritdoc} - */ public function guessPattern(string $class, string $property): ?ValueGuess { return $this->guess($class, $property, function (Constraint $constraint) { diff --git a/Extension/Validator/ViolationMapper/ViolationMapper.php b/Extension/Validator/ViolationMapper/ViolationMapper.php index 7f6b88d6c4..961d5df140 100644 --- a/Extension/Validator/ViolationMapper/ViolationMapper.php +++ b/Extension/Validator/ViolationMapper/ViolationMapper.php @@ -38,9 +38,6 @@ public function __construct(FormRendererInterface $formRenderer = null, Translat $this->translator = $translator; } - /** - * {@inheritdoc} - */ public function mapViolation(ConstraintViolation $violation, FormInterface $form, bool $allowNonSynchronized = false) { $this->allowNonSynchronized = $allowNonSynchronized; diff --git a/Extension/Validator/ViolationMapper/ViolationPath.php b/Extension/Validator/ViolationMapper/ViolationPath.php index fe68518ab1..19fc582bed 100644 --- a/Extension/Validator/ViolationMapper/ViolationPath.php +++ b/Extension/Validator/ViolationMapper/ViolationPath.php @@ -101,17 +101,11 @@ public function __toString(): string return $this->pathAsString; } - /** - * {@inheritdoc} - */ public function getLength(): int { return $this->length; } - /** - * {@inheritdoc} - */ public function getParent(): ?PropertyPathInterface { if ($this->length <= 1) { @@ -130,17 +124,11 @@ public function getParent(): ?PropertyPathInterface return $parent; } - /** - * {@inheritdoc} - */ public function getElements(): array { return $this->elements; } - /** - * {@inheritdoc} - */ public function getElement(int $index): string { if (!isset($this->elements[$index])) { @@ -150,9 +138,6 @@ public function getElement(int $index): string return $this->elements[$index]; } - /** - * {@inheritdoc} - */ public function isProperty(int $index): bool { if (!isset($this->isIndex[$index])) { @@ -162,9 +147,6 @@ public function isProperty(int $index): bool return !$this->isIndex[$index]; } - /** - * {@inheritdoc} - */ public function isIndex(int $index): bool { if (!isset($this->isIndex[$index])) { diff --git a/Form.php b/Form.php index 88d60a140e..b2b96a0a1f 100644 --- a/Form.php +++ b/Form.php @@ -165,25 +165,16 @@ public function __clone() } } - /** - * {@inheritdoc} - */ public function getConfig(): FormConfigInterface { return $this->config; } - /** - * {@inheritdoc} - */ public function getName(): string { return $this->name; } - /** - * {@inheritdoc} - */ public function getPropertyPath(): ?PropertyPathInterface { if ($this->propertyPath || $this->propertyPath = $this->config->getPropertyPath()) { @@ -209,9 +200,6 @@ public function getPropertyPath(): ?PropertyPathInterface return $this->propertyPath; } - /** - * {@inheritdoc} - */ public function isRequired(): bool { if (null === $this->parent || $this->parent->isRequired()) { @@ -221,9 +209,6 @@ public function isRequired(): bool return false; } - /** - * {@inheritdoc} - */ public function isDisabled(): bool { if (null === $this->parent || !$this->parent->isDisabled()) { @@ -233,9 +218,6 @@ public function isDisabled(): bool return true; } - /** - * {@inheritdoc} - */ public function setParent(FormInterface $parent = null): static { if ($this->submitted) { @@ -251,33 +233,21 @@ public function setParent(FormInterface $parent = null): static return $this; } - /** - * {@inheritdoc} - */ public function getParent(): ?FormInterface { return $this->parent; } - /** - * {@inheritdoc} - */ public function getRoot(): FormInterface { return $this->parent ? $this->parent->getRoot() : $this; } - /** - * {@inheritdoc} - */ public function isRoot(): bool { return null === $this->parent; } - /** - * {@inheritdoc} - */ public function setData(mixed $modelData): static { // If the form is submitted while disabled, it is set to submitted, but the data is not @@ -357,9 +327,6 @@ public function setData(mixed $modelData): static return $this; } - /** - * {@inheritdoc} - */ public function getData(): mixed { if ($this->inheritData) { @@ -381,9 +348,6 @@ public function getData(): mixed return $this->modelData; } - /** - * {@inheritdoc} - */ public function getNormData(): mixed { if ($this->inheritData) { @@ -405,9 +369,6 @@ public function getNormData(): mixed return $this->normData; } - /** - * {@inheritdoc} - */ public function getViewData(): mixed { if ($this->inheritData) { @@ -429,17 +390,11 @@ public function getViewData(): mixed return $this->viewData; } - /** - * {@inheritdoc} - */ public function getExtraData(): array { return $this->extraData; } - /** - * {@inheritdoc} - */ public function initialize(): static { if (null !== $this->parent) { @@ -456,9 +411,6 @@ public function initialize(): static return $this; } - /** - * {@inheritdoc} - */ public function handleRequest(mixed $request = null): static { $this->config->getRequestHandler()->handleRequest($this, $request); @@ -466,9 +418,6 @@ public function handleRequest(mixed $request = null): static return $this; } - /** - * {@inheritdoc} - */ public function submit(mixed $submittedData, bool $clearMissing = true): static { if ($this->submitted) { @@ -645,9 +594,6 @@ public function submit(mixed $submittedData, bool $clearMissing = true): static return $this; } - /** - * {@inheritdoc} - */ public function addError(FormError $error): static { if (null === $error->getOrigin()) { @@ -663,33 +609,21 @@ public function addError(FormError $error): static return $this; } - /** - * {@inheritdoc} - */ public function isSubmitted(): bool { return $this->submitted; } - /** - * {@inheritdoc} - */ public function isSynchronized(): bool { return null === $this->transformationFailure; } - /** - * {@inheritdoc} - */ public function getTransformationFailure(): ?Exception\TransformationFailedException { return $this->transformationFailure; } - /** - * {@inheritdoc} - */ public function isEmpty(): bool { foreach ($this->children as $child) { @@ -709,9 +643,6 @@ public function isEmpty(): bool ($this->modelData instanceof \Traversable && 0 === iterator_count($this->modelData)); } - /** - * {@inheritdoc} - */ public function isValid(): bool { if (!$this->submitted) { @@ -737,9 +668,6 @@ public function getClickedButton(): FormInterface|ClickableInterface|null return $this->parent && method_exists($this->parent, 'getClickedButton') ? $this->parent->getClickedButton() : null; } - /** - * {@inheritdoc} - */ public function getErrors(bool $deep = false, bool $flatten = true): FormErrorIterator { $errors = $this->errors; @@ -771,9 +699,6 @@ public function getErrors(bool $deep = false, bool $flatten = true): FormErrorIt return new FormErrorIterator($this, $errors); } - /** - * {@inheritdoc} - */ public function clearErrors(bool $deep = false): static { $this->errors = []; @@ -790,17 +715,11 @@ public function clearErrors(bool $deep = false): static return $this; } - /** - * {@inheritdoc} - */ public function all(): array { return iterator_to_array($this->children); } - /** - * {@inheritdoc} - */ public function add(FormInterface|string $child, string $type = null, array $options = []): static { if ($this->submitted) { @@ -865,9 +784,6 @@ public function add(FormInterface|string $child, string $type = null, array $opt return $this; } - /** - * {@inheritdoc} - */ public function remove(string $name): static { if ($this->submitted) { @@ -885,17 +801,11 @@ public function remove(string $name): static return $this; } - /** - * {@inheritdoc} - */ public function has(string $name): bool { return isset($this->children[$name]); } - /** - * {@inheritdoc} - */ public function get(string $name): FormInterface { if (isset($this->children[$name])) { @@ -973,9 +883,6 @@ public function count(): int return \count($this->children); } - /** - * {@inheritdoc} - */ public function createView(FormView $parent = null): FormView { if (null === $parent && $this->parent) { diff --git a/FormBuilder.php b/FormBuilder.php index 9864235cfb..c6215635ec 100644 --- a/FormBuilder.php +++ b/FormBuilder.php @@ -45,9 +45,6 @@ public function __construct(?string $name, ?string $dataClass, EventDispatcherIn $this->setFormFactory($factory); } - /** - * {@inheritdoc} - */ public function add(FormBuilderInterface|string $child, string $type = null, array $options = []): static { if ($this->locked) { @@ -74,9 +71,6 @@ public function add(FormBuilderInterface|string $child, string $type = null, arr return $this; } - /** - * {@inheritdoc} - */ public function create(string $name, string $type = null, array $options = []): FormBuilderInterface { if ($this->locked) { @@ -94,9 +88,6 @@ public function create(string $name, string $type = null, array $options = []): return $this->getFormFactory()->createBuilderForProperty($this->getDataClass(), $name, null, $options); } - /** - * {@inheritdoc} - */ public function get(string $name): FormBuilderInterface { if ($this->locked) { @@ -114,9 +105,6 @@ public function get(string $name): FormBuilderInterface throw new InvalidArgumentException(sprintf('The child with the name "%s" does not exist.', $name)); } - /** - * {@inheritdoc} - */ public function remove(string $name): static { if ($this->locked) { @@ -128,9 +116,6 @@ public function remove(string $name): static return $this; } - /** - * {@inheritdoc} - */ public function has(string $name): bool { if ($this->locked) { @@ -140,9 +125,6 @@ public function has(string $name): bool return isset($this->unresolvedChildren[$name]) || isset($this->children[$name]); } - /** - * {@inheritdoc} - */ public function all(): array { if ($this->locked) { @@ -163,9 +145,6 @@ public function count(): int return \count($this->children); } - /** - * {@inheritdoc} - */ public function getFormConfig(): FormConfigInterface { /** @var $config self */ @@ -177,9 +156,6 @@ public function getFormConfig(): FormConfigInterface return $config; } - /** - * {@inheritdoc} - */ public function getForm(): FormInterface { if ($this->locked) { @@ -204,8 +180,6 @@ public function getForm(): FormInterface } /** - * {@inheritdoc} - * * @return \Traversable */ public function getIterator(): \Traversable diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 4a03594e0d..094bb88463 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -84,9 +84,6 @@ public function __construct(?string $name, ?string $dataClass, EventDispatcherIn $this->options = $options; } - /** - * {@inheritdoc} - */ public function addEventListener(string $eventName, callable $listener, int $priority = 0): static { if ($this->locked) { @@ -98,9 +95,6 @@ public function addEventListener(string $eventName, callable $listener, int $pri return $this; } - /** - * {@inheritdoc} - */ public function addEventSubscriber(EventSubscriberInterface $subscriber): static { if ($this->locked) { @@ -112,9 +106,6 @@ public function addEventSubscriber(EventSubscriberInterface $subscriber): static return $this; } - /** - * {@inheritdoc} - */ public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false): static { if ($this->locked) { @@ -130,9 +121,6 @@ public function addViewTransformer(DataTransformerInterface $viewTransformer, bo return $this; } - /** - * {@inheritdoc} - */ public function resetViewTransformers(): static { if ($this->locked) { @@ -144,9 +132,6 @@ public function resetViewTransformers(): static return $this; } - /** - * {@inheritdoc} - */ public function addModelTransformer(DataTransformerInterface $modelTransformer, bool $forceAppend = false): static { if ($this->locked) { @@ -162,9 +147,6 @@ public function addModelTransformer(DataTransformerInterface $modelTransformer, return $this; } - /** - * {@inheritdoc} - */ public function resetModelTransformers(): static { if ($this->locked) { @@ -176,9 +158,6 @@ public function resetModelTransformers(): static return $this; } - /** - * {@inheritdoc} - */ public function getEventDispatcher(): EventDispatcherInterface { if ($this->locked && !$this->dispatcher instanceof ImmutableEventDispatcher) { @@ -188,169 +167,106 @@ public function getEventDispatcher(): EventDispatcherInterface return $this->dispatcher; } - /** - * {@inheritdoc} - */ public function getName(): string { return $this->name; } - /** - * {@inheritdoc} - */ public function getPropertyPath(): ?PropertyPathInterface { return $this->propertyPath; } - /** - * {@inheritdoc} - */ public function getMapped(): bool { return $this->mapped; } - /** - * {@inheritdoc} - */ public function getByReference(): bool { return $this->byReference; } - /** - * {@inheritdoc} - */ public function getInheritData(): bool { return $this->inheritData; } - /** - * {@inheritdoc} - */ public function getCompound(): bool { return $this->compound; } - /** - * {@inheritdoc} - */ public function getType(): ResolvedFormTypeInterface { return $this->type; } - /** - * {@inheritdoc} - */ public function getViewTransformers(): array { return $this->viewTransformers; } - /** - * {@inheritdoc} - */ public function getModelTransformers(): array { return $this->modelTransformers; } - /** - * {@inheritdoc} - */ public function getDataMapper(): ?DataMapperInterface { return $this->dataMapper; } - /** - * {@inheritdoc} - */ public function getRequired(): bool { return $this->required; } - /** - * {@inheritdoc} - */ public function getDisabled(): bool { return $this->disabled; } - /** - * {@inheritdoc} - */ public function getErrorBubbling(): bool { return $this->errorBubbling; } - /** - * {@inheritdoc} - */ public function getEmptyData(): mixed { return $this->emptyData; } - /** - * {@inheritdoc} - */ public function getAttributes(): array { return $this->attributes; } - /** - * {@inheritdoc} - */ public function hasAttribute(string $name): bool { return \array_key_exists($name, $this->attributes); } - /** - * {@inheritdoc} - */ public function getAttribute(string $name, mixed $default = null): mixed { return \array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default; } - /** - * {@inheritdoc} - */ public function getData(): mixed { return $this->data; } - /** - * {@inheritdoc} - */ public function getDataClass(): ?string { return $this->dataClass; } - /** - * {@inheritdoc} - */ public function getDataLocked(): bool { return $this->dataLocked; } - /** - * {@inheritdoc} - */ public function getFormFactory(): FormFactoryInterface { if (!isset($this->formFactory)) { @@ -360,73 +276,46 @@ public function getFormFactory(): FormFactoryInterface return $this->formFactory; } - /** - * {@inheritdoc} - */ public function getAction(): string { return $this->action; } - /** - * {@inheritdoc} - */ public function getMethod(): string { return $this->method; } - /** - * {@inheritdoc} - */ public function getRequestHandler(): RequestHandlerInterface { return $this->requestHandler ??= self::$nativeRequestHandler ??= new NativeRequestHandler(); } - /** - * {@inheritdoc} - */ public function getAutoInitialize(): bool { return $this->autoInitialize; } - /** - * {@inheritdoc} - */ public function getOptions(): array { return $this->options; } - /** - * {@inheritdoc} - */ public function hasOption(string $name): bool { return \array_key_exists($name, $this->options); } - /** - * {@inheritdoc} - */ public function getOption(string $name, mixed $default = null): mixed { return \array_key_exists($name, $this->options) ? $this->options[$name] : $default; } - /** - * {@inheritdoc} - */ public function getIsEmptyCallback(): ?callable { return $this->isEmptyCallback; } - /** - * {@inheritdoc} - */ public function setAttribute(string $name, mixed $value): static { if ($this->locked) { @@ -438,9 +327,6 @@ public function setAttribute(string $name, mixed $value): static return $this; } - /** - * {@inheritdoc} - */ public function setAttributes(array $attributes): static { if ($this->locked) { @@ -452,9 +338,6 @@ public function setAttributes(array $attributes): static return $this; } - /** - * {@inheritdoc} - */ public function setDataMapper(DataMapperInterface $dataMapper = null): static { if ($this->locked) { @@ -466,9 +349,6 @@ public function setDataMapper(DataMapperInterface $dataMapper = null): static return $this; } - /** - * {@inheritdoc} - */ public function setDisabled(bool $disabled): static { if ($this->locked) { @@ -480,9 +360,6 @@ public function setDisabled(bool $disabled): static return $this; } - /** - * {@inheritdoc} - */ public function setEmptyData(mixed $emptyData): static { if ($this->locked) { @@ -494,9 +371,6 @@ public function setEmptyData(mixed $emptyData): static return $this; } - /** - * {@inheritdoc} - */ public function setErrorBubbling(bool $errorBubbling): static { if ($this->locked) { @@ -508,9 +382,6 @@ public function setErrorBubbling(bool $errorBubbling): static return $this; } - /** - * {@inheritdoc} - */ public function setRequired(bool $required): static { if ($this->locked) { @@ -522,9 +393,6 @@ public function setRequired(bool $required): static return $this; } - /** - * {@inheritdoc} - */ public function setPropertyPath(string|PropertyPathInterface|null $propertyPath): static { if ($this->locked) { @@ -540,9 +408,6 @@ public function setPropertyPath(string|PropertyPathInterface|null $propertyPath) return $this; } - /** - * {@inheritdoc} - */ public function setMapped(bool $mapped): static { if ($this->locked) { @@ -554,9 +419,6 @@ public function setMapped(bool $mapped): static return $this; } - /** - * {@inheritdoc} - */ public function setByReference(bool $byReference): static { if ($this->locked) { @@ -568,9 +430,6 @@ public function setByReference(bool $byReference): static return $this; } - /** - * {@inheritdoc} - */ public function setInheritData(bool $inheritData): static { if ($this->locked) { @@ -582,9 +441,6 @@ public function setInheritData(bool $inheritData): static return $this; } - /** - * {@inheritdoc} - */ public function setCompound(bool $compound): static { if ($this->locked) { @@ -596,9 +452,6 @@ public function setCompound(bool $compound): static return $this; } - /** - * {@inheritdoc} - */ public function setType(ResolvedFormTypeInterface $type): static { if ($this->locked) { @@ -610,9 +463,6 @@ public function setType(ResolvedFormTypeInterface $type): static return $this; } - /** - * {@inheritdoc} - */ public function setData(mixed $data): static { if ($this->locked) { @@ -624,9 +474,6 @@ public function setData(mixed $data): static return $this; } - /** - * {@inheritdoc} - */ public function setDataLocked(bool $locked): static { if ($this->locked) { @@ -638,9 +485,6 @@ public function setDataLocked(bool $locked): static return $this; } - /** - * {@inheritdoc} - */ public function setFormFactory(FormFactoryInterface $formFactory) { if ($this->locked) { @@ -652,9 +496,6 @@ public function setFormFactory(FormFactoryInterface $formFactory) return $this; } - /** - * {@inheritdoc} - */ public function setAction(string $action): static { if ($this->locked) { @@ -666,9 +507,6 @@ public function setAction(string $action): static return $this; } - /** - * {@inheritdoc} - */ public function setMethod(string $method): static { if ($this->locked) { @@ -680,9 +518,6 @@ public function setMethod(string $method): static return $this; } - /** - * {@inheritdoc} - */ public function setRequestHandler(RequestHandlerInterface $requestHandler): static { if ($this->locked) { @@ -694,9 +529,6 @@ public function setRequestHandler(RequestHandlerInterface $requestHandler): stat return $this; } - /** - * {@inheritdoc} - */ public function setAutoInitialize(bool $initialize): static { if ($this->locked) { @@ -708,9 +540,6 @@ public function setAutoInitialize(bool $initialize): static return $this; } - /** - * {@inheritdoc} - */ public function getFormConfig(): FormConfigInterface { if ($this->locked) { @@ -724,9 +553,6 @@ public function getFormConfig(): FormConfigInterface return $config; } - /** - * {@inheritdoc} - */ public function setIsEmptyCallback(?callable $isEmptyCallback): static { $this->isEmptyCallback = null === $isEmptyCallback ? null : $isEmptyCallback(...); diff --git a/FormFactory.php b/FormFactory.php index 1b76273995..9e1234f831 100644 --- a/FormFactory.php +++ b/FormFactory.php @@ -23,41 +23,26 @@ public function __construct(FormRegistryInterface $registry) $this->registry = $registry; } - /** - * {@inheritdoc} - */ public function create(string $type = FormType::class, mixed $data = null, array $options = []): FormInterface { return $this->createBuilder($type, $data, $options)->getForm(); } - /** - * {@inheritdoc} - */ public function createNamed(string $name, string $type = FormType::class, mixed $data = null, array $options = []): FormInterface { return $this->createNamedBuilder($name, $type, $data, $options)->getForm(); } - /** - * {@inheritdoc} - */ public function createForProperty(string $class, string $property, mixed $data = null, array $options = []): FormInterface { return $this->createBuilderForProperty($class, $property, $data, $options)->getForm(); } - /** - * {@inheritdoc} - */ public function createBuilder(string $type = FormType::class, mixed $data = null, array $options = []): FormBuilderInterface { return $this->createNamedBuilder($this->registry->getType($type)->getBlockPrefix(), $type, $data, $options); } - /** - * {@inheritdoc} - */ public function createNamedBuilder(string $name, string $type = FormType::class, mixed $data = null, array $options = []): FormBuilderInterface { if (null !== $data && !\array_key_exists('data', $options)) { @@ -75,9 +60,6 @@ public function createNamedBuilder(string $name, string $type = FormType::class, return $builder; } - /** - * {@inheritdoc} - */ public function createBuilderForProperty(string $class, string $property, mixed $data = null, array $options = []): FormBuilderInterface { if (null === $guesser = $this->registry->getTypeGuesser()) { diff --git a/FormFactoryBuilder.php b/FormFactoryBuilder.php index 0ad58a660e..42b8dec9f4 100644 --- a/FormFactoryBuilder.php +++ b/FormFactoryBuilder.php @@ -49,9 +49,6 @@ public function __construct(bool $forceCoreExtension = false) $this->forceCoreExtension = $forceCoreExtension; } - /** - * {@inheritdoc} - */ public function setResolvedTypeFactory(ResolvedFormTypeFactoryInterface $resolvedTypeFactory): static { $this->resolvedTypeFactory = $resolvedTypeFactory; @@ -59,9 +56,6 @@ public function setResolvedTypeFactory(ResolvedFormTypeFactoryInterface $resolve return $this; } - /** - * {@inheritdoc} - */ public function addExtension(FormExtensionInterface $extension): static { $this->extensions[] = $extension; @@ -69,9 +63,6 @@ public function addExtension(FormExtensionInterface $extension): static return $this; } - /** - * {@inheritdoc} - */ public function addExtensions(array $extensions): static { $this->extensions = array_merge($this->extensions, $extensions); @@ -79,9 +70,6 @@ public function addExtensions(array $extensions): static return $this; } - /** - * {@inheritdoc} - */ public function addType(FormTypeInterface $type): static { $this->types[] = $type; @@ -89,9 +77,6 @@ public function addType(FormTypeInterface $type): static return $this; } - /** - * {@inheritdoc} - */ public function addTypes(array $types): static { foreach ($types as $type) { @@ -101,9 +86,6 @@ public function addTypes(array $types): static return $this; } - /** - * {@inheritdoc} - */ public function addTypeExtension(FormTypeExtensionInterface $typeExtension): static { foreach ($typeExtension::getExtendedTypes() as $extendedType) { @@ -113,9 +95,6 @@ public function addTypeExtension(FormTypeExtensionInterface $typeExtension): sta return $this; } - /** - * {@inheritdoc} - */ public function addTypeExtensions(array $typeExtensions): static { foreach ($typeExtensions as $typeExtension) { @@ -125,9 +104,6 @@ public function addTypeExtensions(array $typeExtensions): static return $this; } - /** - * {@inheritdoc} - */ public function addTypeGuesser(FormTypeGuesserInterface $typeGuesser): static { $this->typeGuessers[] = $typeGuesser; @@ -135,9 +111,6 @@ public function addTypeGuesser(FormTypeGuesserInterface $typeGuesser): static return $this; } - /** - * {@inheritdoc} - */ public function addTypeGuessers(array $typeGuessers): static { $this->typeGuessers = array_merge($this->typeGuessers, $typeGuessers); @@ -145,9 +118,6 @@ public function addTypeGuessers(array $typeGuessers): static return $this; } - /** - * {@inheritdoc} - */ public function getFormFactory(): FormFactoryInterface { $extensions = $this->extensions; diff --git a/FormRegistry.php b/FormRegistry.php index 5453c6d356..07420507db 100644 --- a/FormRegistry.php +++ b/FormRegistry.php @@ -54,9 +54,6 @@ public function __construct(array $extensions, ResolvedFormTypeFactoryInterface $this->resolvedTypeFactory = $resolvedTypeFactory; } - /** - * {@inheritdoc} - */ public function getType(string $name): ResolvedFormTypeInterface { if (!isset($this->types[$name])) { @@ -118,9 +115,6 @@ private function resolveType(FormTypeInterface $type): ResolvedFormTypeInterface } } - /** - * {@inheritdoc} - */ public function hasType(string $name): bool { if (isset($this->types[$name])) { @@ -136,9 +130,6 @@ public function hasType(string $name): bool return true; } - /** - * {@inheritdoc} - */ public function getTypeGuesser(): ?FormTypeGuesserInterface { if (false === $this->guesser) { @@ -158,9 +149,6 @@ public function getTypeGuesser(): ?FormTypeGuesserInterface return $this->guesser; } - /** - * {@inheritdoc} - */ public function getExtensions(): array { return $this->extensions; diff --git a/FormRenderer.php b/FormRenderer.php index ab8ff1aa3b..12c7c0dddd 100644 --- a/FormRenderer.php +++ b/FormRenderer.php @@ -37,25 +37,16 @@ public function __construct(FormRendererEngineInterface $engine, CsrfTokenManage $this->csrfTokenManager = $csrfTokenManager; } - /** - * {@inheritdoc} - */ public function getEngine(): FormRendererEngineInterface { return $this->engine; } - /** - * {@inheritdoc} - */ public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true) { $this->engine->setTheme($view, $themes, $useDefaultThemes); } - /** - * {@inheritdoc} - */ public function renderCsrfToken(string $tokenId): string { if (null === $this->csrfTokenManager) { @@ -65,9 +56,6 @@ public function renderCsrfToken(string $tokenId): string return $this->csrfTokenManager->getToken($tokenId)->getValue(); } - /** - * {@inheritdoc} - */ public function renderBlock(FormView $view, string $blockName, array $variables = []): string { $resource = $this->engine->getResourceForBlockName($view, $blockName); @@ -124,9 +112,6 @@ public function renderBlock(FormView $view, string $blockName, array $variables return $html; } - /** - * {@inheritdoc} - */ public function searchAndRenderBlock(FormView $view, string $blockNameSuffix, array $variables = []): string { $renderOnlyOnce = 'row' === $blockNameSuffix || 'widget' === $blockNameSuffix; @@ -277,9 +262,6 @@ public function searchAndRenderBlock(FormView $view, string $blockNameSuffix, ar return $html; } - /** - * {@inheritdoc} - */ public function humanize(string $text): string { return ucfirst(strtolower(trim(preg_replace(['/([A-Z])/', '/[_\s]+/'], ['_$1', ' '], $text)))); diff --git a/FormTypeGuesserChain.php b/FormTypeGuesserChain.php index 1ce69d8d3d..7d8f617f7b 100644 --- a/FormTypeGuesserChain.php +++ b/FormTypeGuesserChain.php @@ -43,9 +43,6 @@ public function __construct(iterable $guessers) $this->guessers = array_merge([], ...$tmpGuessers); } - /** - * {@inheritdoc} - */ public function guessType(string $class, string $property): ?TypeGuess { return $this->guess(function ($guesser) use ($class, $property) { @@ -53,9 +50,6 @@ public function guessType(string $class, string $property): ?TypeGuess }); } - /** - * {@inheritdoc} - */ public function guessRequired(string $class, string $property): ?ValueGuess { return $this->guess(function ($guesser) use ($class, $property) { @@ -63,9 +57,6 @@ public function guessRequired(string $class, string $property): ?ValueGuess }); } - /** - * {@inheritdoc} - */ public function guessMaxLength(string $class, string $property): ?ValueGuess { return $this->guess(function ($guesser) use ($class, $property) { @@ -73,9 +64,6 @@ public function guessMaxLength(string $class, string $property): ?ValueGuess }); } - /** - * {@inheritdoc} - */ public function guessPattern(string $class, string $property): ?ValueGuess { return $this->guess(function ($guesser) use ($class, $property) { diff --git a/NativeRequestHandler.php b/NativeRequestHandler.php index 679c190e4a..cf193398c8 100644 --- a/NativeRequestHandler.php +++ b/NativeRequestHandler.php @@ -40,8 +40,6 @@ public function __construct(ServerParams $params = null) } /** - * {@inheritdoc} - * * @throws Exception\UnexpectedTypeException If the $request is not null */ public function handleRequest(FormInterface $form, mixed $request = null) @@ -124,9 +122,6 @@ public function handleRequest(FormInterface $form, mixed $request = null) $form->submit($data, 'PATCH' !== $method); } - /** - * {@inheritdoc} - */ public function isFileUpload(mixed $data): bool { // POST data will always be strings or arrays of strings. Thus, we can be sure diff --git a/PreloadedExtension.php b/PreloadedExtension.php index 3c0ae26e89..5590eda370 100644 --- a/PreloadedExtension.php +++ b/PreloadedExtension.php @@ -40,9 +40,6 @@ public function __construct(array $types, array $typeExtensions, FormTypeGuesser } } - /** - * {@inheritdoc} - */ public function getType(string $name): FormTypeInterface { if (!isset($this->types[$name])) { @@ -52,34 +49,22 @@ public function getType(string $name): FormTypeInterface return $this->types[$name]; } - /** - * {@inheritdoc} - */ public function hasType(string $name): bool { return isset($this->types[$name]); } - /** - * {@inheritdoc} - */ public function getTypeExtensions(string $name): array { return $this->typeExtensions[$name] ?? []; } - /** - * {@inheritdoc} - */ public function hasTypeExtensions(string $name): bool { return !empty($this->typeExtensions[$name]); } - /** - * {@inheritdoc} - */ public function getTypeGuesser(): ?FormTypeGuesserInterface { return $this->typeGuesser; diff --git a/ResolvedFormType.php b/ResolvedFormType.php index 884d538a44..af794a3b7c 100644 --- a/ResolvedFormType.php +++ b/ResolvedFormType.php @@ -50,41 +50,26 @@ public function __construct(FormTypeInterface $innerType, array $typeExtensions $this->parent = $parent; } - /** - * {@inheritdoc} - */ public function getBlockPrefix(): string { return $this->innerType->getBlockPrefix(); } - /** - * {@inheritdoc} - */ public function getParent(): ?ResolvedFormTypeInterface { return $this->parent; } - /** - * {@inheritdoc} - */ public function getInnerType(): FormTypeInterface { return $this->innerType; } - /** - * {@inheritdoc} - */ public function getTypeExtensions(): array { return $this->typeExtensions; } - /** - * {@inheritdoc} - */ public function createBuilder(FormFactoryInterface $factory, string $name, array $options = []): FormBuilderInterface { try { @@ -102,17 +87,11 @@ public function createBuilder(FormFactoryInterface $factory, string $name, array return $builder; } - /** - * {@inheritdoc} - */ public function createView(FormInterface $form, FormView $parent = null): FormView { return $this->newView($parent); } - /** - * {@inheritdoc} - */ public function buildForm(FormBuilderInterface $builder, array $options) { $this->parent?->buildForm($builder, $options); @@ -124,9 +103,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * {@inheritdoc} - */ public function buildView(FormView $view, FormInterface $form, array $options) { $this->parent?->buildView($view, $form, $options); @@ -138,9 +114,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function finishView(FormView $view, FormInterface $form, array $options) { $this->parent?->finishView($view, $form, $options); @@ -153,9 +126,6 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } - /** - * {@inheritdoc} - */ public function getOptionsResolver(): OptionsResolver { if (!isset($this->optionsResolver)) { diff --git a/ResolvedFormTypeFactory.php b/ResolvedFormTypeFactory.php index 48f62bad32..fd7c4521b2 100644 --- a/ResolvedFormTypeFactory.php +++ b/ResolvedFormTypeFactory.php @@ -16,9 +16,6 @@ */ class ResolvedFormTypeFactory implements ResolvedFormTypeFactoryInterface { - /** - * {@inheritdoc} - */ public function createResolvedType(FormTypeInterface $type, array $typeExtensions, ResolvedFormTypeInterface $parent = null): ResolvedFormTypeInterface { return new ResolvedFormType($type, $typeExtensions, $parent); diff --git a/ReversedTransformer.php b/ReversedTransformer.php index d2a835ba90..8572672369 100644 --- a/ReversedTransformer.php +++ b/ReversedTransformer.php @@ -28,17 +28,11 @@ public function __construct(DataTransformerInterface $reversedTransformer) $this->reversedTransformer = $reversedTransformer; } - /** - * {@inheritdoc} - */ public function transform(mixed $value): mixed { return $this->reversedTransformer->reverseTransform($value); } - /** - * {@inheritdoc} - */ public function reverseTransform(mixed $value): mixed { return $this->reversedTransformer->transform($value); diff --git a/SubmitButton.php b/SubmitButton.php index bc7e1c3f7f..37ce141d27 100644 --- a/SubmitButton.php +++ b/SubmitButton.php @@ -20,9 +20,6 @@ class SubmitButton extends Button implements ClickableInterface { private bool $clicked = false; - /** - * {@inheritdoc} - */ public function isClicked(): bool { return $this->clicked; diff --git a/Test/FormPerformanceTestCase.php b/Test/FormPerformanceTestCase.php index 2547e871cc..16894bea0c 100644 --- a/Test/FormPerformanceTestCase.php +++ b/Test/FormPerformanceTestCase.php @@ -30,9 +30,6 @@ abstract class FormPerformanceTestCase extends FormIntegrationTestCase */ protected $maxRunningTime = 0; - /** - * {@inheritdoc} - */ protected function runTest() { $s = microtime(true); diff --git a/Tests/Fixtures/ChoiceSubType.php b/Tests/Fixtures/ChoiceSubType.php index 5058bf6a6f..d67f0b96ac 100644 --- a/Tests/Fixtures/ChoiceSubType.php +++ b/Tests/Fixtures/ChoiceSubType.php @@ -20,9 +20,6 @@ */ class ChoiceSubType extends AbstractType { - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(['expanded' => true]); @@ -34,9 +31,6 @@ public function configureOptions(OptionsResolver $resolver) }); } - /** - * {@inheritdoc} - */ public function getParent(): ?string { return ChoiceType::class; diff --git a/Tests/Fixtures/ChoiceTypeExtension.php b/Tests/Fixtures/ChoiceTypeExtension.php index 34242c5b69..1751531d19 100644 --- a/Tests/Fixtures/ChoiceTypeExtension.php +++ b/Tests/Fixtures/ChoiceTypeExtension.php @@ -18,9 +18,6 @@ class ChoiceTypeExtension extends AbstractTypeExtension { public static $extendedType; - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefault('choices', [ @@ -29,9 +26,6 @@ public function configureOptions(OptionsResolver $resolver) ]); } - /** - * {@inheritdoc} - */ public static function getExtendedTypes(): iterable { return [self::$extendedType]; diff --git a/Tests/Fixtures/LazyChoiceTypeExtension.php b/Tests/Fixtures/LazyChoiceTypeExtension.php index 20fe789cd7..b04eb61721 100644 --- a/Tests/Fixtures/LazyChoiceTypeExtension.php +++ b/Tests/Fixtures/LazyChoiceTypeExtension.php @@ -19,9 +19,6 @@ class LazyChoiceTypeExtension extends AbstractTypeExtension { public static $extendedType; - /** - * {@inheritdoc} - */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefault('choice_loader', ChoiceList::lazy($this, function () { @@ -32,9 +29,6 @@ public function configureOptions(OptionsResolver $resolver) })); } - /** - * {@inheritdoc} - */ public static function getExtendedTypes(): iterable { return [self::$extendedType]; diff --git a/Util/OrderedHashMapIterator.php b/Util/OrderedHashMapIterator.php index b3cdf5e571..e1335fefa6 100644 --- a/Util/OrderedHashMapIterator.php +++ b/Util/OrderedHashMapIterator.php @@ -78,17 +78,11 @@ public function __destruct() array_splice($this->managedCursors, $this->cursorId, 1); } - /** - * {@inheritdoc} - */ public function current(): mixed { return $this->current; } - /** - * {@inheritdoc} - */ public function next(): void { ++$this->cursor; @@ -102,9 +96,6 @@ public function next(): void } } - /** - * {@inheritdoc} - */ public function key(): mixed { if (null === $this->key) { @@ -114,17 +105,11 @@ public function key(): mixed return $this->key; } - /** - * {@inheritdoc} - */ public function valid(): bool { return null !== $this->key; } - /** - * {@inheritdoc} - */ public function rewind(): void { $this->cursor = 0; From 3be9604b0d960ae2e48a1fcc5d22c62959856e50 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault Date: Tue, 23 Aug 2022 21:46:41 +0200 Subject: [PATCH 057/208] Remove usage of empty function when possible --- ChoiceList/Factory/DefaultChoiceListFactory.php | 2 +- Extension/Core/DataTransformer/ArrayToPartsTransformer.php | 2 +- FormRegistry.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index 9ab806cbc5..132ac300bd 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -71,7 +71,7 @@ public function createView(ChoiceListInterface $list, array|callable $preferredC $keys = $list->getOriginalKeys(); if (!\is_callable($preferredChoices)) { - if (empty($preferredChoices)) { + if (!$preferredChoices) { $preferredChoices = null; } else { // make sure we have keys that reflect order diff --git a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php index 4dbb8272a8..c02b46dc10 100644 --- a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php +++ b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php @@ -39,7 +39,7 @@ public function transform(mixed $array): mixed $result = []; foreach ($this->partMapping as $partKey => $originalKeys) { - if (empty($array)) { + if (!$array) { $result[$partKey] = null; } else { $result[$partKey] = array_intersect_key($array, array_flip($originalKeys)); diff --git a/FormRegistry.php b/FormRegistry.php index 5453c6d356..84912de301 100644 --- a/FormRegistry.php +++ b/FormRegistry.php @@ -152,7 +152,7 @@ public function getTypeGuesser(): ?FormTypeGuesserInterface } } - $this->guesser = !empty($guessers) ? new FormTypeGuesserChain($guessers) : null; + $this->guesser = $guessers ? new FormTypeGuesserChain($guessers) : null; } return $this->guesser; From 6c27f0a63a1472a401c109701070ac19b6e47367 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois-Xavier=20de=20Guillebon?= Date: Fri, 26 Aug 2022 16:19:22 +0200 Subject: [PATCH 058/208] Replace get_class() calls by ::class --- AbstractExtension.php | 2 +- Command/DebugCommand.php | 2 +- Console/Descriptor/Descriptor.php | 2 +- .../DependencyInjection/DependencyInjectionExtension.php | 2 +- Extension/Validator/ValidatorTypeGuesser.php | 8 ++++---- FormRegistry.php | 2 +- PreloadedExtension.php | 2 +- Tests/Command/DebugCommandTest.php | 2 +- Tests/Extension/Core/DataMapper/DataMapperTest.php | 2 +- .../Extension/Validator/Constraints/FormValidatorTest.php | 2 +- .../Validator/Type/FormTypeValidatorExtensionTest.php | 2 +- 11 files changed, 14 insertions(+), 14 deletions(-) diff --git a/AbstractExtension.php b/AbstractExtension.php index 6ba5624bd9..5d3c1a8480 100644 --- a/AbstractExtension.php +++ b/AbstractExtension.php @@ -137,7 +137,7 @@ private function initTypes() throw new UnexpectedTypeException($type, FormTypeInterface::class); } - $this->types[\get_class($type)] = $type; + $this->types[$type::class] = $type; } } diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index 159051046f..afa283bbd5 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -204,7 +204,7 @@ private function getCoreTypes(): array $coreExtension = new CoreExtension(); $loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes'); $coreTypes = $loadTypesRefMethod->invoke($coreExtension); - $coreTypes = array_map(function (FormTypeInterface $type) { return \get_class($type); }, $coreTypes); + $coreTypes = array_map(function (FormTypeInterface $type) { return $type::class; }, $coreTypes); sort($coreTypes); return $coreTypes; diff --git a/Console/Descriptor/Descriptor.php b/Console/Descriptor/Descriptor.php index f6b09c2692..ad28cb67de 100644 --- a/Console/Descriptor/Descriptor.php +++ b/Console/Descriptor/Descriptor.php @@ -198,7 +198,7 @@ private function collectTypeExtensionsOptions(ResolvedFormTypeInterface $type, O foreach ($type->getTypeExtensions() as $extension) { $inheritedOptions = $optionsResolver->getDefinedOptions(); $extension->configureOptions($optionsResolver); - $this->extensions[\get_class($extension)] = array_diff($optionsResolver->getDefinedOptions(), $inheritedOptions); + $this->extensions[$extension::class] = array_diff($optionsResolver->getDefinedOptions(), $inheritedOptions); } } } diff --git a/Extension/DependencyInjection/DependencyInjectionExtension.php b/Extension/DependencyInjection/DependencyInjectionExtension.php index 0b978d693d..d7c9346889 100644 --- a/Extension/DependencyInjection/DependencyInjectionExtension.php +++ b/Extension/DependencyInjection/DependencyInjectionExtension.php @@ -65,7 +65,7 @@ public function getTypeExtensions(string $name): array // validate the result of getExtendedTypes() to ensure it is consistent with the service definition if (!\in_array($name, $extendedTypes, true)) { - throw new InvalidArgumentException(sprintf('The extended type "%s" specified for the type extension class "%s" does not match any of the actual extended types (["%s"]).', $name, \get_class($extension), implode('", "', $extendedTypes))); + throw new InvalidArgumentException(sprintf('The extended type "%s" specified for the type extension class "%s" does not match any of the actual extended types (["%s"]).', $name, $extension::class, implode('", "', $extendedTypes))); } } } diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index 46738b401e..6fb47884d2 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -99,7 +99,7 @@ public function guessPattern(string $class, string $property): ?ValueGuess */ public function guessTypeForConstraint(Constraint $constraint): ?TypeGuess { - switch (\get_class($constraint)) { + switch ($constraint::class) { case Type::class: switch ($constraint->type) { case 'array': @@ -190,7 +190,7 @@ public function guessTypeForConstraint(Constraint $constraint): ?TypeGuess */ public function guessRequiredForConstraint(Constraint $constraint): ?ValueGuess { - return match (\get_class($constraint)) { + return match ($constraint::class) { NotNull::class, NotBlank::class, IsTrue::class => new ValueGuess(true, Guess::HIGH_CONFIDENCE), @@ -203,7 +203,7 @@ public function guessRequiredForConstraint(Constraint $constraint): ?ValueGuess */ public function guessMaxLengthForConstraint(Constraint $constraint): ?ValueGuess { - switch (\get_class($constraint)) { + switch ($constraint::class) { case Length::class: if (is_numeric($constraint->max)) { return new ValueGuess($constraint->max, Guess::HIGH_CONFIDENCE); @@ -231,7 +231,7 @@ public function guessMaxLengthForConstraint(Constraint $constraint): ?ValueGuess */ public function guessPatternForConstraint(Constraint $constraint): ?ValueGuess { - switch (\get_class($constraint)) { + switch ($constraint::class) { case Length::class: if (is_numeric($constraint->min)) { return new ValueGuess(sprintf('.{%s,}', (string) $constraint->min), Guess::LOW_CONFIDENCE); diff --git a/FormRegistry.php b/FormRegistry.php index a22624f367..ab3f55f9fb 100644 --- a/FormRegistry.php +++ b/FormRegistry.php @@ -90,7 +90,7 @@ public function getType(string $name): ResolvedFormTypeInterface private function resolveType(FormTypeInterface $type): ResolvedFormTypeInterface { $parentType = $type->getParent(); - $fqcn = \get_class($type); + $fqcn = $type::class; if (isset($this->checkedTypes[$fqcn])) { $types = implode(' > ', array_merge(array_keys($this->checkedTypes), [$fqcn])); diff --git a/PreloadedExtension.php b/PreloadedExtension.php index 5590eda370..c8e628d2d2 100644 --- a/PreloadedExtension.php +++ b/PreloadedExtension.php @@ -36,7 +36,7 @@ public function __construct(array $types, array $typeExtensions, FormTypeGuesser $this->typeGuesser = $typeGuesser; foreach ($types as $type) { - $this->types[\get_class($type)] = $type; + $this->types[$type::class] = $type; } } diff --git a/Tests/Command/DebugCommandTest.php b/Tests/Command/DebugCommandTest.php index 6a4c8552be..d0037bbfbd 100644 --- a/Tests/Command/DebugCommandTest.php +++ b/Tests/Command/DebugCommandTest.php @@ -263,7 +263,7 @@ private function getCoreTypes(): array $coreExtension = new CoreExtension(); $loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes'); $coreTypes = $loadTypesRefMethod->invoke($coreExtension); - $coreTypes = array_map(function (FormTypeInterface $type) { return \get_class($type); }, $coreTypes); + $coreTypes = array_map(function (FormTypeInterface $type) { return $type::class; }, $coreTypes); sort($coreTypes); return $coreTypes; diff --git a/Tests/Extension/Core/DataMapper/DataMapperTest.php b/Tests/Extension/Core/DataMapper/DataMapperTest.php index 1b625dc139..b39572ed80 100644 --- a/Tests/Extension/Core/DataMapper/DataMapperTest.php +++ b/Tests/Extension/Core/DataMapper/DataMapperTest.php @@ -334,7 +334,7 @@ public function testMapFormsToDataDoesNotChangeEqualDateTimeInstance($date) $article['publishedAt'] = $publishedAtValue; $propertyPath = new PropertyPath('[publishedAt]'); - $config = new FormConfigBuilder('publishedAt', \get_class($publishedAt), $this->dispatcher); + $config = new FormConfigBuilder('publishedAt', $publishedAt::class, $this->dispatcher); $config->setByReference(false); $config->setPropertyPath($propertyPath); $config->setData($publishedAt); diff --git a/Tests/Extension/Validator/Constraints/FormValidatorTest.php b/Tests/Extension/Validator/Constraints/FormValidatorTest.php index af8f048e54..e5b0d736b0 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorTest.php @@ -736,7 +736,7 @@ private function getForm($name = 'name', $dataClass = null, array $options = []) private function getCompoundForm($data, array $options = []) { - return $this->getBuilder('name', \is_object($data) ? \get_class($data) : null, $options) + return $this->getBuilder('name', \is_object($data) ? $data::class : null, $options) ->setData($data) ->setCompound(true) ->setDataMapper(new DataMapper()) diff --git a/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php index 9b0c9d1481..30db508520 100644 --- a/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php @@ -113,7 +113,7 @@ public function testManyFieldsGroupSequenceWithConstraintsOption() return $formMetadata; } - return new ClassMetadata(\is_string($classOrObject) ? $classOrObject : \get_class($classOrObject)); + return new ClassMetadata(\is_string($classOrObject) ? $classOrObject : $classOrObject::class); }) ; From 588268002ac704383f262edbafc0cb1a4ab359e1 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 2 Sep 2022 16:55:07 +0200 Subject: [PATCH 059/208] CS fixes --- Tests/Extension/Core/Type/EnumTypeTest.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Tests/Extension/Core/Type/EnumTypeTest.php b/Tests/Extension/Core/Type/EnumTypeTest.php index f571d631b4..9eb89442ea 100644 --- a/Tests/Extension/Core/Type/EnumTypeTest.php +++ b/Tests/Extension/Core/Type/EnumTypeTest.php @@ -91,13 +91,13 @@ public function provideSingleSubmitData(): iterable yield 'string backed' => [ Suit::class, - (Suit::Spades)->value, + Suit::Spades->value, Suit::Spades, ]; yield 'integer backed' => [ Number::class, - (string) (Number::Two)->value, + (string) Number::Two->value, Number::Two, ]; } @@ -131,7 +131,7 @@ public function testSubmitNull($expected = null, $norm = null, $view = null) public function testSubmitNullUsesDefaultEmptyData($emptyData = 'empty', $expectedData = null) { - $emptyData = (Suit::Hearts)->value; + $emptyData = Suit::Hearts->value; $form = $this->factory->create($this->getTestedType(), null, [ 'class' => Suit::class, @@ -151,7 +151,7 @@ public function testSubmitMultipleChoiceWithEmptyData() 'multiple' => true, 'expanded' => false, 'class' => Suit::class, - 'empty_data' => [(Suit::Diamonds)->value], + 'empty_data' => [Suit::Diamonds->value], ]); $form->submit(null); @@ -165,7 +165,7 @@ public function testSubmitSingleChoiceExpandedWithEmptyData() 'multiple' => false, 'expanded' => true, 'class' => Suit::class, - 'empty_data' => (Suit::Hearts)->value, + 'empty_data' => Suit::Hearts->value, ]); $form->submit(null); @@ -179,7 +179,7 @@ public function testSubmitMultipleChoiceExpandedWithEmptyData() 'multiple' => true, 'expanded' => true, 'class' => Suit::class, - 'empty_data' => [(Suit::Spades)->value], + 'empty_data' => [Suit::Spades->value], ]); $form->submit(null); @@ -233,13 +233,13 @@ public function provideMultiSubmitData(): iterable yield 'string backed' => [ Suit::class, - [(Suit::Hearts)->value, (Suit::Spades)->value], + [Suit::Hearts->value, Suit::Spades->value], [Suit::Hearts, Suit::Spades], ]; yield 'integer backed' => [ Number::class, - [(string) (Number::Two)->value, (string) (Number::Three)->value], + [(string) Number::Two->value, (string) Number::Three->value], [Number::Two, Number::Three], ]; } From c140d5294768293776d6b7685e7019a4dd95790d Mon Sep 17 00:00:00 2001 From: Matthias Pigulla Date: Thu, 8 Sep 2022 14:58:12 +0200 Subject: [PATCH 060/208] Remove `size` FormView variable --- Extension/Core/Type/FormType.php | 1 - 1 file changed, 1 deletion(-) diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index 451e7381d1..7b5cffe821 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -103,7 +103,6 @@ public function buildView(FormView $view, FormInterface $form, array $options) 'value' => $form->getViewData(), 'data' => $form->getNormData(), 'required' => $form->isRequired(), - 'size' => null, 'label_attr' => $options['label_attr'], 'help' => $options['help'], 'help_attr' => $options['help_attr'], From 9c0b5ef932e40c4b51abe218103d3c3d9fd9a1db Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 12 Sep 2022 10:52:12 +0200 Subject: [PATCH 061/208] Add a few more ??= --- .../Core/EventListener/MergeCollectionListenerTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php b/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php index 0be62fa153..4cb0970aba 100644 --- a/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php +++ b/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php @@ -34,7 +34,7 @@ abstract protected function getBuilder($name = 'name'); protected function getForm($name = 'name', $propertyPath = null) { - $propertyPath = $propertyPath ?: $name; + $propertyPath ??= $name; return $this->getBuilder($name)->setAttribute('property_path', $propertyPath)->getForm(); } From edbf33681a4bfa69cae6e889b7f8f77ef1e6f359 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 12 Sep 2022 14:32:45 +0200 Subject: [PATCH 062/208] Remove all "nullable-by-default-value" setters --- Button.php | 3 +++ ButtonBuilder.php | 4 ++++ CHANGELOG.md | 7 +++++-- Exception/TransformationFailedException.php | 3 +++ Form.php | 4 ++++ FormConfigBuilder.php | 3 +++ FormConfigBuilderInterface.php | 2 +- FormInterface.php | 2 +- 8 files changed, 24 insertions(+), 4 deletions(-) diff --git a/Button.php b/Button.php index 58a77a7763..00373b3770 100644 --- a/Button.php +++ b/Button.php @@ -83,6 +83,9 @@ public function offsetUnset(mixed $offset): void public function setParent(FormInterface $parent = null): static { + if (1 > \func_num_args()) { + trigger_deprecation('symfony/form', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__); + } if ($this->submitted) { throw new AlreadySubmittedException('You cannot set the parent of a submitted button.'); } diff --git a/ButtonBuilder.php b/ButtonBuilder.php index 387c3571fc..bfba1d6cd0 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -194,6 +194,10 @@ public function setAttributes(array $attributes): static */ public function setDataMapper(DataMapperInterface $dataMapper = null): static { + if (1 > \func_num_args()) { + trigger_deprecation('symfony/form', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__); + } + throw new BadMethodCallException('Buttons do not support data mappers.'); } diff --git a/CHANGELOG.md b/CHANGELOG.md index b5150a4c84..2475b005be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,11 @@ CHANGELOG 6.2 --- -* Allow passing `TranslatableInterface` objects to the `ChoiceView` label -* Allow passing `TranslatableInterface` objects to the `help` option + * Allow passing `TranslatableInterface` objects to the `ChoiceView` label + * Allow passing `TranslatableInterface` objects to the `help` option + * Deprecate calling `Button/Form::setParent()`, `ButtonBuilder/FormConfigBuilder::setDataMapper()`, `TransformationFailedException::setInvalidMessage()` without arguments + * Change the signature of `FormConfigBuilderInterface::setDataMapper()` to `setDataMapper(?DataMapperInterface)` + * Change the signature of `FormInterface::setParent()` to `setParent(?self)` 6.1 --- diff --git a/Exception/TransformationFailedException.php b/Exception/TransformationFailedException.php index e34a6e5ec7..409b51517a 100644 --- a/Exception/TransformationFailedException.php +++ b/Exception/TransformationFailedException.php @@ -36,6 +36,9 @@ public function __construct(string $message = '', int $code = 0, \Throwable $pre */ public function setInvalidMessage(string $invalidMessage = null, array $invalidMessageParameters = []): void { + if (1 > \func_num_args()) { + trigger_deprecation('symfony/form', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__); + } $this->invalidMessage = $invalidMessage; $this->invalidMessageParameters = $invalidMessageParameters; } diff --git a/Form.php b/Form.php index b2b96a0a1f..4b63480242 100644 --- a/Form.php +++ b/Form.php @@ -220,6 +220,10 @@ public function isDisabled(): bool public function setParent(FormInterface $parent = null): static { + if (1 > \func_num_args()) { + trigger_deprecation('symfony/form', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__); + } + if ($this->submitted) { throw new AlreadySubmittedException('You cannot set the parent of a submitted form.'); } diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 094bb88463..e18db7ed8e 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -340,6 +340,9 @@ public function setAttributes(array $attributes): static public function setDataMapper(DataMapperInterface $dataMapper = null): static { + if (1 > \func_num_args()) { + trigger_deprecation('symfony/form', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__); + } if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); } diff --git a/FormConfigBuilderInterface.php b/FormConfigBuilderInterface.php index a0858c7d3f..84f40d3711 100644 --- a/FormConfigBuilderInterface.php +++ b/FormConfigBuilderInterface.php @@ -100,7 +100,7 @@ public function setAttributes(array $attributes): static; * * @return $this */ - public function setDataMapper(DataMapperInterface $dataMapper = null): static; + public function setDataMapper(?DataMapperInterface $dataMapper): static; /** * Sets whether the form is disabled. diff --git a/FormInterface.php b/FormInterface.php index 292984215d..a66cf420c9 100644 --- a/FormInterface.php +++ b/FormInterface.php @@ -34,7 +34,7 @@ interface FormInterface extends \ArrayAccess, \Traversable, \Countable * @throws Exception\LogicException when trying to set a parent for a form with * an empty name */ - public function setParent(self $parent = null): static; + public function setParent(?self $parent): static; /** * Returns the parent form. From 8778f5e060d6790417e03ade619bd0caf6fe6a13 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Sun, 28 Aug 2022 16:09:15 +0200 Subject: [PATCH 063/208] [Form] Add generics to DataTransformerInterface --- DataTransformerInterface.php | 11 +++++++---- .../Core/DataTransformer/ArrayToPartsTransformer.php | 2 ++ .../Core/DataTransformer/BaseDateTimeTransformer.php | 4 ++++ .../DataTransformer/BooleanToStringTransformer.php | 2 ++ .../Core/DataTransformer/ChoiceToValueTransformer.php | 2 ++ .../DataTransformer/ChoicesToValuesTransformer.php | 2 ++ .../DateIntervalToArrayTransformer.php | 2 ++ .../DateIntervalToStringTransformer.php | 2 ++ .../DateTimeImmutableToDateTimeTransformer.php | 2 ++ .../DataTransformer/DateTimeToArrayTransformer.php | 2 ++ .../DateTimeToHtml5LocalDateTimeTransformer.php | 8 +++++--- .../DateTimeToLocalizedStringTransformer.php | 4 +++- .../DataTransformer/DateTimeToRfc3339Transformer.php | 2 ++ .../DataTransformer/DateTimeToStringTransformer.php | 2 ++ .../DateTimeToTimestampTransformer.php | 2 ++ .../DateTimeZoneToStringTransformer.php | 2 ++ .../IntlTimeZoneToStringTransformer.php | 2 ++ .../NumberToLocalizedStringTransformer.php | 2 ++ .../PercentToLocalizedStringTransformer.php | 2 ++ .../Core/DataTransformer/StringToFloatTransformer.php | 3 +++ .../Core/DataTransformer/UlidToStringTransformer.php | 2 ++ .../Core/DataTransformer/UuidToStringTransformer.php | 2 ++ .../DataTransformer/ValueToDuplicatesTransformer.php | 2 ++ .../Core/DataTransformer/WeekToArrayTransformer.php | 2 ++ 24 files changed, 60 insertions(+), 8 deletions(-) diff --git a/DataTransformerInterface.php b/DataTransformerInterface.php index 8495905e17..edb3f83c0b 100644 --- a/DataTransformerInterface.php +++ b/DataTransformerInterface.php @@ -17,6 +17,9 @@ * Transforms a value between different representations. * * @author Bernhard Schussek + * + * @template TValue + * @template TTransformedValue */ interface DataTransformerInterface { @@ -53,9 +56,9 @@ interface DataTransformerInterface * of the first data transformer outputs NULL, the second must be able to * process that value. * - * @param mixed $value The value in the original representation + * @param TValue|null $value The value in the original representation * - * @return mixed + * @return TTransformedValue|null * * @throws TransformationFailedException when the transformation fails */ @@ -82,9 +85,9 @@ public function transform(mixed $value); * By convention, reverseTransform() should return NULL if an empty string * is passed. * - * @param mixed $value The value in the transformed representation + * @param TTransformedValue|null $value The value in the transformed representation * - * @return mixed + * @return TValue|null * * @throws TransformationFailedException when the transformation fails */ diff --git a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php index c02b46dc10..2035eb0873 100644 --- a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php +++ b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php @@ -16,6 +16,8 @@ /** * @author Bernhard Schussek + * + * @implements DataTransformerInterface */ class ArrayToPartsTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/BaseDateTimeTransformer.php b/Extension/Core/DataTransformer/BaseDateTimeTransformer.php index 142f4894e1..c6ff9cd1ae 100644 --- a/Extension/Core/DataTransformer/BaseDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/BaseDateTimeTransformer.php @@ -14,6 +14,10 @@ use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Exception\InvalidArgumentException; +/** + * @template TTransformedValue + * @implements DataTransformerInterface<\DateTimeInterface, TTransformedValue> + */ abstract class BaseDateTimeTransformer implements DataTransformerInterface { protected static $formats = [ diff --git a/Extension/Core/DataTransformer/BooleanToStringTransformer.php b/Extension/Core/DataTransformer/BooleanToStringTransformer.php index 1e6d902447..e91bdb4dbf 100644 --- a/Extension/Core/DataTransformer/BooleanToStringTransformer.php +++ b/Extension/Core/DataTransformer/BooleanToStringTransformer.php @@ -20,6 +20,8 @@ * * @author Bernhard Schussek * @author Florian Eckerstorfer + * + * @implements DataTransformerInterface */ class BooleanToStringTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php index f7b0798224..f9411528ac 100644 --- a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php +++ b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php @@ -17,6 +17,8 @@ /** * @author Bernhard Schussek + * + * @implements DataTransformerInterface */ class ChoiceToValueTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php index e2f1f2f22d..f284ff34f9 100644 --- a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php +++ b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php @@ -17,6 +17,8 @@ /** * @author Bernhard Schussek + * + * @implements DataTransformerInterface */ class ChoicesToValuesTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php index 69431db90d..8638e4a842 100644 --- a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php @@ -19,6 +19,8 @@ * Transforms between a normalized date interval and an interval string/array. * * @author Steffen Roßkamp + * + * @implements DataTransformerInterface<\DateInterval, array> */ class DateIntervalToArrayTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php index 41d6f6f2b3..4160f8f34c 100644 --- a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php @@ -19,6 +19,8 @@ * Transforms between a date string and a DateInterval object. * * @author Steffen Roßkamp + * + * @implements DataTransformerInterface<\DateInterval, string> */ class DateIntervalToStringTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php b/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php index 5726147dbb..3f285b4a3d 100644 --- a/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeImmutableToDateTimeTransformer.php @@ -18,6 +18,8 @@ * Transforms between a DateTimeImmutable object and a DateTime object. * * @author Valentin Udaltsov + * + * @implements DataTransformerInterface<\DateTimeImmutable, \DateTime> */ final class DateTimeImmutableToDateTimeTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php index e44c623d00..1f48aed1ad 100644 --- a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php @@ -18,6 +18,8 @@ * * @author Bernhard Schussek * @author Florian Eckerstorfer + * + * @extends BaseDateTimeTransformer */ class DateTimeToArrayTransformer extends BaseDateTimeTransformer { diff --git a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php index 25e82f359b..40cd1b89df 100644 --- a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php @@ -17,6 +17,8 @@ * @author Franz Wilding * @author Bernhard Schussek * @author Fred Cox + * + * @extends BaseDateTimeTransformer */ class DateTimeToHtml5LocalDateTimeTransformer extends BaseDateTimeTransformer { @@ -29,7 +31,7 @@ class DateTimeToHtml5LocalDateTimeTransformer extends BaseDateTimeTransformer * input is an RFC3339 date followed by 'T', followed by an RFC3339 time. * https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-local-date-and-time-string * - * @param \DateTime|\DateTimeInterface $dateTime A DateTime object + * @param \DateTimeInterface $dateTime * * @throws TransformationFailedException If the given value is not an * instance of \DateTime or \DateTimeInterface @@ -40,8 +42,8 @@ public function transform(mixed $dateTime): string return ''; } - if (!$dateTime instanceof \DateTime && !$dateTime instanceof \DateTimeInterface) { - throw new TransformationFailedException('Expected a \DateTime or \DateTimeInterface.'); + if (!$dateTime instanceof \DateTimeInterface) { + throw new TransformationFailedException('Expected a \DateTimeInterface.'); } if ($this->inputTimezone !== $this->outputTimezone) { diff --git a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php index 2c1b6c3931..5e4011d1a7 100644 --- a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php @@ -19,6 +19,8 @@ * * @author Bernhard Schussek * @author Florian Eckerstorfer + * + * @extends BaseDateTimeTransformer */ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer { @@ -95,7 +97,7 @@ public function transform(mixed $dateTime): string /** * Transforms a localized date string/array into a normalized date. * - * @param string|array $value Localized date string/array + * @param string $value Localized date string * * @throws TransformationFailedException if the given value is not a string, * if the date could not be parsed diff --git a/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php b/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php index 7b222e3f21..63f12b1f17 100644 --- a/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php +++ b/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php @@ -15,6 +15,8 @@ /** * @author Bernhard Schussek + * + * @extends BaseDateTimeTransformer */ class DateTimeToRfc3339Transformer extends BaseDateTimeTransformer { diff --git a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php index 6e68b5ebe1..e34086e689 100644 --- a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php @@ -18,6 +18,8 @@ * * @author Bernhard Schussek * @author Florian Eckerstorfer + * + * @extends BaseDateTimeTransformer */ class DateTimeToStringTransformer extends BaseDateTimeTransformer { diff --git a/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php b/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php index 9edf5d0638..33c1b1d599 100644 --- a/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php @@ -18,6 +18,8 @@ * * @author Bernhard Schussek * @author Florian Eckerstorfer + * + * @extends BaseDateTimeTransformer */ class DateTimeToTimestampTransformer extends BaseDateTimeTransformer { diff --git a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php index e6e575d769..f7bda17511 100644 --- a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php @@ -18,6 +18,8 @@ * Transforms between a timezone identifier string and a DateTimeZone object. * * @author Roland Franssen + * + * @implements DataTransformerInterface<\DateTimeZone|array<\DateTimeZone>, string|array> */ class DateTimeZoneToStringTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php index 86849c4ea8..d379164a7a 100644 --- a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php @@ -18,6 +18,8 @@ * Transforms between a timezone identifier string and a IntlTimeZone object. * * @author Roland Franssen + * + * @implements DataTransformerInterface<\IntlTimeZone|array<\IntlTimeZone>, string|array> */ class IntlTimeZoneToStringTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index b5b43d5acf..5ab33b4c94 100644 --- a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -20,6 +20,8 @@ * * @author Bernhard Schussek * @author Florian Eckerstorfer + * + * @implements DataTransformerInterface */ class NumberToLocalizedStringTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index 9f252af5b9..123235bbec 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -20,6 +20,8 @@ * * @author Bernhard Schussek * @author Florian Eckerstorfer + * + * @implements DataTransformerInterface */ class PercentToLocalizedStringTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/StringToFloatTransformer.php b/Extension/Core/DataTransformer/StringToFloatTransformer.php index 4e04ab6d9e..09b5e51faf 100644 --- a/Extension/Core/DataTransformer/StringToFloatTransformer.php +++ b/Extension/Core/DataTransformer/StringToFloatTransformer.php @@ -14,6 +14,9 @@ use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Exception\TransformationFailedException; +/** + * @implements DataTransformerInterface + */ class StringToFloatTransformer implements DataTransformerInterface { private ?int $scale; diff --git a/Extension/Core/DataTransformer/UlidToStringTransformer.php b/Extension/Core/DataTransformer/UlidToStringTransformer.php index c9cf32a2d5..7ace73ad09 100644 --- a/Extension/Core/DataTransformer/UlidToStringTransformer.php +++ b/Extension/Core/DataTransformer/UlidToStringTransformer.php @@ -19,6 +19,8 @@ * Transforms between a ULID string and a Ulid object. * * @author Pavel Dyakonov + * + * @implements DataTransformerInterface */ class UlidToStringTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/UuidToStringTransformer.php b/Extension/Core/DataTransformer/UuidToStringTransformer.php index 392ee0b5dd..4fd6378e09 100644 --- a/Extension/Core/DataTransformer/UuidToStringTransformer.php +++ b/Extension/Core/DataTransformer/UuidToStringTransformer.php @@ -19,6 +19,8 @@ * Transforms between a UUID string and a Uuid object. * * @author Pavel Dyakonov + * + * @implements DataTransformerInterface */ class UuidToStringTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php index 11b03c5544..2399abf73c 100644 --- a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php +++ b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php @@ -16,6 +16,8 @@ /** * @author Bernhard Schussek + * + * @implements DataTransformerInterface */ class ValueToDuplicatesTransformer implements DataTransformerInterface { diff --git a/Extension/Core/DataTransformer/WeekToArrayTransformer.php b/Extension/Core/DataTransformer/WeekToArrayTransformer.php index 1cdafb19a3..c10bc735f6 100644 --- a/Extension/Core/DataTransformer/WeekToArrayTransformer.php +++ b/Extension/Core/DataTransformer/WeekToArrayTransformer.php @@ -18,6 +18,8 @@ * Transforms between an ISO 8601 week date string and an array. * * @author Damien Fayet + * + * @implements DataTransformerInterface */ class WeekToArrayTransformer implements DataTransformerInterface { From a728bf5ef689b3e8c2c1bb7e353f19a3f09b63b1 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Sat, 17 Sep 2022 12:44:52 +0200 Subject: [PATCH 064/208] fix type for choices --- Extension/Core/DataTransformer/ChoiceToValueTransformer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php index f9411528ac..daec9d7195 100644 --- a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php +++ b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php @@ -18,7 +18,7 @@ /** * @author Bernhard Schussek * - * @implements DataTransformerInterface + * @implements DataTransformerInterface */ class ChoiceToValueTransformer implements DataTransformerInterface { From 89788ef2c4edd6e107930726e1b3801e211289eb Mon Sep 17 00:00:00 2001 From: tigitz Date: Wed, 21 Sep 2022 21:07:39 +0200 Subject: [PATCH 065/208] Convert switch cases to match expression --- Console/Descriptor/Descriptor.php | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/Console/Descriptor/Descriptor.php b/Console/Descriptor/Descriptor.php index ad28cb67de..3441d017b1 100644 --- a/Console/Descriptor/Descriptor.php +++ b/Console/Descriptor/Descriptor.php @@ -44,19 +44,12 @@ public function describe(OutputInterface $output, ?object $object, array $option { $this->output = $output instanceof OutputStyle ? $output : new SymfonyStyle(new ArrayInput([]), $output); - switch (true) { - case null === $object: - $this->describeDefaults($options); - break; - case $object instanceof ResolvedFormTypeInterface: - $this->describeResolvedFormType($object, $options); - break; - case $object instanceof OptionsResolver: - $this->describeOption($object, $options); - break; - default: - throw new \InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object))); - } + match (true) { + null === $object => $this->describeDefaults($options), + $object instanceof ResolvedFormTypeInterface => $this->describeResolvedFormType($object, $options), + $object instanceof OptionsResolver => $this->describeOption($object, $options), + default => throw new \InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object))), + }; } abstract protected function describeDefaults(array $options); From 1ed57f220df372e5e74ec77e9345803db5469af9 Mon Sep 17 00:00:00 2001 From: Felix Soedjede Date: Wed, 7 Sep 2022 13:52:32 +0200 Subject: [PATCH 066/208] feature #34483 - Allow optional property accesses --- Extension/Validator/ViolationMapper/ViolationPath.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Extension/Validator/ViolationMapper/ViolationPath.php b/Extension/Validator/ViolationMapper/ViolationPath.php index 19fc582bed..a597dcb139 100644 --- a/Extension/Validator/ViolationMapper/ViolationPath.php +++ b/Extension/Validator/ViolationMapper/ViolationPath.php @@ -156,6 +156,11 @@ public function isIndex(int $index): bool return $this->isIndex[$index]; } + public function isNullSafe(int $index): bool + { + return false; + } + /** * Returns whether an element maps directly to a form. * From 33bae57b73c190d3d976e62059e993af2b30251a Mon Sep 17 00:00:00 2001 From: tigitz Date: Fri, 30 Sep 2022 22:34:56 +0200 Subject: [PATCH 067/208] Leverage First-class callable syntax --- Extension/DataCollector/FormDataCollector.php | 2 +- .../Factory/DefaultChoiceListFactoryTest.php | 22 +++++++++---------- .../Constraints/FormValidatorTest.php | 4 ++-- .../Type/BaseValidatorExtensionTest.php | 2 +- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index 525d8ffecc..0a9145c624 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -235,7 +235,7 @@ protected function getCasters(): array Caster::PREFIX_VIRTUAL.'type_class' => new ClassStub(\get_class($f->getConfig()->getType()->getInnerType())), ]; }, - FormView::class => [StubCaster::class, 'cutInternals'], + FormView::class => StubCaster::cutInternals(...), ConstraintViolationInterface::class => function (ConstraintViolationInterface $v, array $a) { return [ Caster::PREFIX_VIRTUAL.'root' => $v->getRoot(), diff --git a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index ab26d4cbe3..054739c8cc 100644 --- a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -141,7 +141,7 @@ public function testCreateFromChoicesFlatValuesAsCallable() { $list = $this->factory->createListFromChoices( ['A' => $this->obj1, 'B' => $this->obj2, 'C' => $this->obj3, 'D' => $this->obj4], - [$this, 'getValue'] + $this->getValue(...) ); $this->assertObjectListWithCustomValues($list); @@ -186,7 +186,7 @@ public function testCreateFromChoicesGroupedValuesAsCallable() 'Group 1' => ['A' => $this->obj1, 'B' => $this->obj2], 'Group 2' => ['C' => $this->obj3, 'D' => $this->obj4], ], - [$this, 'getValue'] + $this->getValue(...) ); $this->assertObjectListWithCustomValues($list); @@ -335,7 +335,7 @@ public function testCreateViewFlatPreferredChoiceGroupsSameOrder() [$this->obj4, $this->obj2, $this->obj1, $this->obj3], null, // label null, // index - [$this, 'getGroup'] + $this->getGroup(...) ); $preferredLabels = array_map(static function (ChoiceGroupView $groupView): array { @@ -380,7 +380,7 @@ public function testCreateViewFlatPreferredChoicesAsCallable() { $view = $this->factory->createView( $this->list, - [$this, 'isPreferred'] + $this->isPreferred(...) ); $this->assertFlatView($view); @@ -430,7 +430,7 @@ public function testCreateViewFlatLabelAsCallable() $view = $this->factory->createView( $this->list, [$this->obj2, $this->obj3], - [$this, 'getLabel'] + $this->getLabel(...) ); $this->assertFlatView($view); @@ -486,7 +486,7 @@ public function testCreateViewFlatIndexAsCallable() $this->list, [$this->obj2, $this->obj3], null, // label - [$this, 'getFormIndex'] + $this->getFormIndex(...) ); $this->assertFlatViewWithCustomIndices($view); @@ -580,7 +580,7 @@ public function testCreateViewFlatGroupByAsCallable() [$this->obj2, $this->obj3], null, // label null, // index - [$this, 'getGroup'] + $this->getGroup(...) ); $this->assertGroupedView($view); @@ -593,7 +593,7 @@ public function testCreateViewFlatGroupByAsCallableReturnsArray() [], null, // label null, // index - [$this, 'getGroupArray'] + $this->getGroupArray(...) ); $this->assertGroupedViewWithChoiceDuplication($view); @@ -606,7 +606,7 @@ public function testCreateViewFlatGroupByObjectThatCanBeCastToString() [$this->obj2, $this->obj3], null, // label null, // index - [$this, 'getGroupAsObject'] + $this->getGroupAsObject(...) ); $this->assertGroupedView($view); @@ -699,7 +699,7 @@ public function testCreateViewFlatAttrAsCallable() null, // label null, // index null, // group - [$this, 'getAttr'] + $this->getAttr(...) ); $this->assertFlatViewWithAttr($view); @@ -837,7 +837,7 @@ public function testCreateViewFlatlabelTranslationParametersAsCallable() null, // index null, // group null, // attr - [$this, 'getlabelTranslationParameters'] + $this->getlabelTranslationParameters(...) ); $this->assertFlatViewWithlabelTranslationParameters($view); diff --git a/Tests/Extension/Validator/Constraints/FormValidatorTest.php b/Tests/Extension/Validator/Constraints/FormValidatorTest.php index e5b0d736b0..b5ab6588cb 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorTest.php @@ -423,7 +423,7 @@ public function testHandleGroupSequenceValidationGroups() public function testHandleCallbackValidationGroups() { $object = new \stdClass(); - $options = ['validation_groups' => [$this, 'getValidationGroups']]; + $options = ['validation_groups' => $this->getValidationGroups(...)]; $form = $this->getCompoundForm($object, $options); $form->submit([]); @@ -543,7 +543,7 @@ public function testUseInheritedCallbackValidationGroup() { $object = new \stdClass(); - $parentOptions = ['validation_groups' => [$this, 'getValidationGroups']]; + $parentOptions = ['validation_groups' => $this->getValidationGroups(...)]; $parent = $this->getBuilder('parent', null, $parentOptions) ->setCompound(true) ->setDataMapper(new DataMapper()) diff --git a/Tests/Extension/Validator/Type/BaseValidatorExtensionTest.php b/Tests/Extension/Validator/Type/BaseValidatorExtensionTest.php index 7062ed53d3..4b69dfe886 100644 --- a/Tests/Extension/Validator/Type/BaseValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/BaseValidatorExtensionTest.php @@ -57,7 +57,7 @@ public function testValidationGroupsCanBeSetToFalse() public function testValidationGroupsCanBeSetToCallback() { $form = $this->createForm([ - 'validation_groups' => [$this, 'testValidationGroupsCanBeSetToCallback'], + 'validation_groups' => $this->testValidationGroupsCanBeSetToCallback(...), ]); $this->assertIsCallable($form->getConfig()->getOption('validation_groups')); From c417f150f85dc56069d2a1dfc21e1d13ba452604 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20ALFAIATE?= Date: Sun, 1 May 2022 23:06:30 +0700 Subject: [PATCH 068/208] [Form] Add hash_mapping option to PasswordType --- CHANGELOG.md | 1 + .../EventListener/PasswordHasherListener.php | 82 ++++++++++ .../PasswordHasherExtension.php | 36 +++++ .../Type/FormTypePasswordHasherExtension.php | 39 +++++ .../PasswordTypePasswordHasherExtension.php | 54 +++++++ ...asswordTypePasswordHasherExtensionTest.php | 145 ++++++++++++++++++ Tests/Fixtures/User.php | 31 ++++ composer.json | 2 + 8 files changed, 390 insertions(+) create mode 100644 Extension/PasswordHasher/EventListener/PasswordHasherListener.php create mode 100644 Extension/PasswordHasher/PasswordHasherExtension.php create mode 100644 Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php create mode 100644 Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php create mode 100644 Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php create mode 100644 Tests/Fixtures/User.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 2475b005be..68622612e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ CHANGELOG * Deprecate calling `Button/Form::setParent()`, `ButtonBuilder/FormConfigBuilder::setDataMapper()`, `TransformationFailedException::setInvalidMessage()` without arguments * Change the signature of `FormConfigBuilderInterface::setDataMapper()` to `setDataMapper(?DataMapperInterface)` * Change the signature of `FormInterface::setParent()` to `setParent(?self)` + * Add `PasswordHasherExtension` with support for `hash_property_path` option in `PasswordType` 6.1 --- diff --git a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php new file mode 100644 index 0000000000..c9cf0d4a34 --- /dev/null +++ b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Extension\PasswordHasher\EventListener; + +use Symfony\Component\Form\Exception\InvalidConfigurationException; +use Symfony\Component\Form\Extension\Core\Type\RepeatedType; +use Symfony\Component\Form\FormEvent; +use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; +use Symfony\Component\PropertyAccess\PropertyAccess; +use Symfony\Component\PropertyAccess\PropertyAccessorInterface; +use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; + +/** + * @author Sébastien Alfaiate + */ +class PasswordHasherListener +{ + private array $passwords = []; + + public function __construct( + private UserPasswordHasherInterface $passwordHasher, + private ?PropertyAccessorInterface $propertyAccessor = null, + ) { + $this->propertyAccessor ??= PropertyAccess::createPropertyAccessor(); + } + + public function registerPassword(FormEvent $event) + { + $form = $event->getForm(); + $parentForm = $form->getParent(); + $mapped = $form->getConfig()->getMapped(); + + if ($parentForm && $parentForm->getConfig()->getType()->getInnerType() instanceof RepeatedType) { + $mapped = $parentForm->getConfig()->getMapped(); + $parentForm = $parentForm->getParent(); + } + + if ($mapped) { + throw new InvalidConfigurationException('The "hash_property_path" option cannot be used on mapped field.'); + } + + if (!($user = $parentForm?->getData()) || !$user instanceof PasswordAuthenticatedUserInterface) { + throw new InvalidConfigurationException(sprintf('The "hash_property_path" option only supports "%s" objects, "%s" given.', PasswordAuthenticatedUserInterface::class, get_debug_type($user))); + } + + $this->passwords[] = [ + 'user' => $user, + 'property_path' => $form->getConfig()->getOption('hash_property_path'), + 'password' => $event->getData(), + ]; + } + + public function hashPasswords(FormEvent $event) + { + $form = $event->getForm(); + + if (!$form->isRoot()) { + return; + } + + if ($form->isValid()) { + foreach ($this->passwords as $password) { + $this->propertyAccessor->setValue( + $password['user'], + $password['property_path'], + $this->passwordHasher->hashPassword($password['user'], $password['password']) + ); + } + } + + $this->passwords = []; + } +} diff --git a/Extension/PasswordHasher/PasswordHasherExtension.php b/Extension/PasswordHasher/PasswordHasherExtension.php new file mode 100644 index 0000000000..b9675c2153 --- /dev/null +++ b/Extension/PasswordHasher/PasswordHasherExtension.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Extension\PasswordHasher; + +use Symfony\Component\Form\AbstractExtension; +use Symfony\Component\Form\Extension\PasswordHasher\EventListener\PasswordHasherListener; + +/** + * Integrates the PasswordHasher component with the Form library. + * + * @author Sébastien Alfaiate + */ +class PasswordHasherExtension extends AbstractExtension +{ + public function __construct( + private PasswordHasherListener $passwordHasherListener, + ) { + } + + protected function loadTypeExtensions(): array + { + return [ + new Type\FormTypePasswordHasherExtension($this->passwordHasherListener), + new Type\PasswordTypePasswordHasherExtension($this->passwordHasherListener), + ]; + } +} diff --git a/Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php b/Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php new file mode 100644 index 0000000000..7294ee5f02 --- /dev/null +++ b/Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Extension\PasswordHasher\Type; + +use Symfony\Component\Form\AbstractTypeExtension; +use Symfony\Component\Form\Extension\Core\Type\FormType; +use Symfony\Component\Form\Extension\PasswordHasher\EventListener\PasswordHasherListener; +use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\Form\FormEvents; + +/** + * @author Sébastien Alfaiate + */ +class FormTypePasswordHasherExtension extends AbstractTypeExtension +{ + public function __construct( + private PasswordHasherListener $passwordHasherListener, + ) { + } + + public function buildForm(FormBuilderInterface $builder, array $options) + { + $builder->addEventListener(FormEvents::POST_SUBMIT, [$this->passwordHasherListener, 'hashPasswords']); + } + + public static function getExtendedTypes(): iterable + { + return [FormType::class]; + } +} diff --git a/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php b/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php new file mode 100644 index 0000000000..e75a6e9ff2 --- /dev/null +++ b/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Extension\PasswordHasher\Type; + +use Symfony\Component\Form\AbstractTypeExtension; +use Symfony\Component\Form\Extension\Core\Type\PasswordType; +use Symfony\Component\Form\Extension\PasswordHasher\EventListener\PasswordHasherListener; +use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\Form\FormEvents; +use Symfony\Component\OptionsResolver\OptionsResolver; +use Symfony\Component\PropertyAccess\PropertyPath; + +/** + * @author Sébastien Alfaiate + */ +class PasswordTypePasswordHasherExtension extends AbstractTypeExtension +{ + public function __construct( + private PasswordHasherListener $passwordHasherListener, + ) { + } + + public function buildForm(FormBuilderInterface $builder, array $options) + { + if ($options['hash_property_path']) { + $builder->addEventListener(FormEvents::POST_SUBMIT, [$this->passwordHasherListener, 'registerPassword']); + } + } + + public function configureOptions(OptionsResolver $resolver) + { + $resolver->setDefaults([ + 'hash_property_path' => null, + ]); + + $resolver->setAllowedTypes('hash_property_path', ['null', 'string', PropertyPath::class]); + + $resolver->setInfo('hash_property_path', 'A valid PropertyAccess syntax where the hashed password will be set.'); + } + + public static function getExtendedTypes(): iterable + { + return [PasswordType::class]; + } +} diff --git a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php new file mode 100644 index 0000000000..75b2f99257 --- /dev/null +++ b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php @@ -0,0 +1,145 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Tests\Extension\PasswordHasher\Type; + +use PHPUnit\Framework\MockObject\MockObject; +use Symfony\Component\Form\Exception\InvalidConfigurationException; +use Symfony\Component\Form\Extension\PasswordHasher\EventListener\PasswordHasherListener; +use Symfony\Component\Form\Extension\PasswordHasher\PasswordHasherExtension; +use Symfony\Component\Form\Test\TypeTestCase; +use Symfony\Component\Form\Tests\Fixtures\User; +use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher; +use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; +use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; + +class PasswordTypePasswordHasherExtensionTest extends TypeTestCase +{ + /** + * @var MockObject&UserPasswordHasherInterface + */ + protected $passwordHasher; + + protected function setUp(): void + { + if (!interface_exists(PasswordAuthenticatedUserInterface::class)) { + $this->markTestSkipped('PasswordAuthenticatedUserInterface not available.'); + } + + $this->passwordHasher = $this->createMock(UserPasswordHasher::class); + + parent::setUp(); + } + + protected function getExtensions() + { + return array_merge(parent::getExtensions(), [ + new PasswordHasherExtension(new PasswordHasherListener($this->passwordHasher)), + ]); + } + + public function testPasswordHashSuccess() + { + $user = new User(); + + $plainPassword = 'PlainPassword'; + $hashedPassword = 'HashedPassword'; + + $this->passwordHasher + ->expects($this->once()) + ->method('hashPassword') + ->with($user, $plainPassword) + ->willReturn($hashedPassword) + ; + + $this->assertNull($user->getPassword()); + + $form = $this->factory + ->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', $user) + ->add('plainPassword', 'Symfony\Component\Form\Extension\Core\Type\PasswordType', [ + 'hash_property_path' => 'password', + 'mapped' => false, + ]) + ->getForm() + ; + + $form->submit(['plainPassword' => $plainPassword]); + + $this->assertTrue($form->isValid()); + $this->assertSame($user->getPassword(), $hashedPassword); + } + + public function testPasswordHashOnInvalidForm() + { + $user = new User(); + + $this->passwordHasher + ->expects($this->never()) + ->method('hashPassword') + ; + + $this->assertNull($user->getPassword()); + + $form = $this->factory + ->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', $user) + ->add('plainPassword', 'Symfony\Component\Form\Extension\Core\Type\PasswordType', [ + 'hash_property_path' => 'password', + 'mapped' => false, + ]) + ->add('integer', 'Symfony\Component\Form\Extension\Core\Type\IntegerType', [ + 'mapped' => false, + ]) + ->getForm() + ; + + $form->submit([ + 'plainPassword' => 'PlainPassword', + 'integer' => 'text', + ]); + + $this->assertFalse($form->isValid()); + $this->assertNull($user->getPassword()); + } + + public function testPasswordHashOnInvalidData() + { + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('The "hash_property_path" option only supports "Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface" objects, "array" given.'); + + $form = $this->factory + ->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', []) + ->add('plainPassword', 'Symfony\Component\Form\Extension\Core\Type\PasswordType', [ + 'hash_property_path' => 'password', + 'mapped' => false, + ]) + ->getForm() + ; + + $form->submit(['plainPassword' => 'PlainPassword']); + } + + public function testPasswordHashOnMappedFieldForbidden() + { + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('The "hash_property_path" option cannot be used on mapped field.'); + + $form = $this->factory + ->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', new User()) + ->add('password', 'Symfony\Component\Form\Extension\Core\Type\PasswordType', [ + 'hash_property_path' => 'password', + 'mapped' => true, + ]) + ->getForm() + ; + + $form->submit(['password' => 'PlainPassword']); + } +} diff --git a/Tests/Fixtures/User.php b/Tests/Fixtures/User.php new file mode 100644 index 0000000000..486311ee6c --- /dev/null +++ b/Tests/Fixtures/User.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Tests\Fixtures; + +use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; + +class User implements PasswordAuthenticatedUserInterface +{ + private $password; + + public function getPassword(): ?string + { + return $this->password; + } + + public function setPassword(string $password): self + { + $this->password = $password; + + return $this; + } +} diff --git a/composer.json b/composer.json index 05193a2f0c..60f07fdded 100644 --- a/composer.json +++ b/composer.json @@ -37,6 +37,7 @@ "symfony/http-foundation": "^5.4|^6.0", "symfony/http-kernel": "^5.4|^6.0", "symfony/intl": "^5.4|^6.0", + "symfony/security-core": "^6.2", "symfony/security-csrf": "^5.4|^6.0", "symfony/translation": "^5.4|^6.0", "symfony/var-dumper": "^5.4|^6.0", @@ -56,6 +57,7 @@ }, "suggest": { "symfony/validator": "For form validation.", + "symfony/security-core": "For hashing users passwords.", "symfony/security-csrf": "For protecting forms against CSRF attacks.", "symfony/twig-bridge": "For templating with Twig." }, From 2d867d640e5b3986230d0bf6379f05a1981462b8 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 1 Nov 2022 22:49:27 +0100 Subject: [PATCH 069/208] Use ??= more --- ChoiceList/Factory/DefaultChoiceListFactory.php | 4 +--- Console/Descriptor/TextDescriptor.php | 4 +--- Extension/Core/DataMapper/CheckboxListMapper.php | 6 +----- .../Core/DataTransformer/ArrayToPartsTransformer.php | 6 +----- .../DateTimeToLocalizedStringTransformer.php | 9 ++------- .../PercentToLocalizedStringTransformer.php | 4 +--- .../Core/EventListener/MergeCollectionListener.php | 6 +----- Extension/Core/EventListener/ResizeFormListener.php | 12 ++---------- Extension/Core/Type/BaseType.php | 4 +--- .../Validator/ViolationMapper/ViolationMapper.php | 4 ++-- Form.php | 6 +----- .../Validator/ViolationMapper/ViolationPathTest.php | 4 +--- 12 files changed, 15 insertions(+), 54 deletions(-) diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index f1449b7dca..ef37699341 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -74,9 +74,7 @@ public function createView(ChoiceListInterface $list, array|callable $preferredC } // The names are generated from an incrementing integer by default - if (null === $index) { - $index = 0; - } + $index ??= 0; // If $groupBy is a callable returning a string // choices are added to the group with the name returned by the callable. diff --git a/Console/Descriptor/TextDescriptor.php b/Console/Descriptor/TextDescriptor.php index 497167ddd7..439526af75 100644 --- a/Console/Descriptor/TextDescriptor.php +++ b/Console/Descriptor/TextDescriptor.php @@ -194,9 +194,7 @@ private function normalizeAndSortOptionsColumns(array $options): array private function formatClassLink(string $class, string $text = null): string { - if (null === $text) { - $text = $class; - } + $text ??= $class; if ('' === $fileLink = $this->getFileLink($class)) { return $text; diff --git a/Extension/Core/DataMapper/CheckboxListMapper.php b/Extension/Core/DataMapper/CheckboxListMapper.php index f461e0e126..2345138112 100644 --- a/Extension/Core/DataMapper/CheckboxListMapper.php +++ b/Extension/Core/DataMapper/CheckboxListMapper.php @@ -27,11 +27,7 @@ class CheckboxListMapper implements DataMapperInterface { public function mapDataToForms(mixed $choices, \Traversable $checkboxes) { - if (null === $choices) { - $choices = []; - } - - if (!\is_array($choices)) { + if (!\is_array($choices ??= [])) { throw new UnexpectedTypeException($choices, 'array'); } diff --git a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php index 2035eb0873..9256c0a094 100644 --- a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php +++ b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php @@ -30,11 +30,7 @@ public function __construct(array $partMapping) public function transform(mixed $array): mixed { - if (null === $array) { - $array = []; - } - - if (!\is_array($array)) { + if (!\is_array($array ??= [])) { throw new TransformationFailedException('Expected an array.'); } diff --git a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php index 5e4011d1a7..22a5d41b5f 100644 --- a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php @@ -45,13 +45,8 @@ public function __construct(string $inputTimezone = null, string $outputTimezone { parent::__construct($inputTimezone, $outputTimezone); - if (null === $dateFormat) { - $dateFormat = \IntlDateFormatter::MEDIUM; - } - - if (null === $timeFormat) { - $timeFormat = \IntlDateFormatter::SHORT; - } + $dateFormat ??= \IntlDateFormatter::MEDIUM; + $timeFormat ??= \IntlDateFormatter::SHORT; if (!\in_array($dateFormat, self::$formats, true)) { throw new UnexpectedTypeException($dateFormat, implode('", "', self::$formats)); diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index 123235bbec..7bea4d227c 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -48,9 +48,7 @@ class PercentToLocalizedStringTransformer implements DataTransformerInterface */ public function __construct(int $scale = null, string $type = null, int $roundingMode = \NumberFormatter::ROUND_HALFUP, bool $html5Format = false) { - if (null === $type) { - $type = self::FRACTIONAL; - } + $type ??= self::FRACTIONAL; if (!\in_array($type, self::$types, true)) { throw new UnexpectedTypeException($type, implode('", "', self::$types)); diff --git a/Extension/Core/EventListener/MergeCollectionListener.php b/Extension/Core/EventListener/MergeCollectionListener.php index 37046e9b69..4f77342f90 100644 --- a/Extension/Core/EventListener/MergeCollectionListener.php +++ b/Extension/Core/EventListener/MergeCollectionListener.php @@ -44,11 +44,7 @@ public static function getSubscribedEvents(): array public function onSubmit(FormEvent $event) { $dataToMergeInto = $event->getForm()->getNormData(); - $data = $event->getData(); - - if (null === $data) { - $data = []; - } + $data = $event->getData() ?? []; if (!\is_array($data) && !($data instanceof \Traversable && $data instanceof \ArrayAccess)) { throw new UnexpectedTypeException($data, 'array or (\Traversable and \ArrayAccess)'); diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index c5258469c3..a524e15574 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -53,11 +53,7 @@ public static function getSubscribedEvents(): array public function preSetData(FormEvent $event) { $form = $event->getForm(); - $data = $event->getData(); - - if (null === $data) { - $data = []; - } + $data = $event->getData() ?? []; if (!\is_array($data) && !($data instanceof \Traversable && $data instanceof \ArrayAccess)) { throw new UnexpectedTypeException($data, 'array or (\Traversable and \ArrayAccess)'); @@ -109,16 +105,12 @@ public function preSubmit(FormEvent $event) public function onSubmit(FormEvent $event) { $form = $event->getForm(); - $data = $event->getData(); + $data = $event->getData() ?? []; // At this point, $data is an array or an array-like object that already contains the // new entries, which were added by the data mapper. The data mapper ignores existing // entries, so we need to manually unset removed entries in the collection. - if (null === $data) { - $data = []; - } - if (!\is_array($data) && !($data instanceof \Traversable && $data instanceof \ArrayAccess)) { throw new UnexpectedTypeException($data, 'array or (\Traversable and \ArrayAccess)'); } diff --git a/Extension/Core/Type/BaseType.php b/Extension/Core/Type/BaseType.php index 8606802e12..86b55ebe83 100644 --- a/Extension/Core/Type/BaseType.php +++ b/Extension/Core/Type/BaseType.php @@ -54,9 +54,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) $uniqueBlockPrefix = '_'.$blockName; } - if (null === $translationDomain) { - $translationDomain = $view->parent->vars['translation_domain']; - } + $translationDomain ??= $view->parent->vars['translation_domain']; $labelTranslationParameters = array_merge($view->parent->vars['label_translation_parameters'], $labelTranslationParameters); $attrTranslationParameters = array_merge($view->parent->vars['attr_translation_parameters'], $attrTranslationParameters); diff --git a/Extension/Validator/ViolationMapper/ViolationMapper.php b/Extension/Validator/ViolationMapper/ViolationMapper.php index 961d5df140..e6bcd29fea 100644 --- a/Extension/Validator/ViolationMapper/ViolationMapper.php +++ b/Extension/Validator/ViolationMapper/ViolationMapper.php @@ -176,8 +176,8 @@ public function mapViolation(ConstraintViolation $violation, FormInterface $form if (false !== $label) { if (null === $label && null !== $this->formRenderer) { $label = $this->formRenderer->humanize($scope->getName()); - } elseif (null === $label) { - $label = $scope->getName(); + } else { + $label ??= $scope->getName(); } if (null !== $this->translator) { diff --git a/Form.php b/Form.php index 4b63480242..7acf8c7251 100644 --- a/Form.php +++ b/Form.php @@ -488,11 +488,7 @@ public function submit(mixed $submittedData, bool $clearMissing = true): static // since forms without children may also be compound. // (think of empty collection forms) if ($this->config->getCompound()) { - if (null === $submittedData) { - $submittedData = []; - } - - if (!\is_array($submittedData)) { + if (!\is_array($submittedData ??= [])) { throw new TransformationFailedException('Compound forms expect an array or NULL on submission.'); } diff --git a/Tests/Extension/Validator/ViolationMapper/ViolationPathTest.php b/Tests/Extension/Validator/ViolationMapper/ViolationPathTest.php index 7b9dec34c2..9412c723d7 100644 --- a/Tests/Extension/Validator/ViolationMapper/ViolationPathTest.php +++ b/Tests/Extension/Validator/ViolationMapper/ViolationPathTest.php @@ -89,9 +89,7 @@ public function providePaths() */ public function testCreatePath($string, $entries, $slicedPath = null) { - if (null === $slicedPath) { - $slicedPath = $string; - } + $slicedPath ??= $string; $path = new ViolationPath($string); From e8e70624470a0b0869b42dbee514cfaa865c0f75 Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Wed, 2 Nov 2022 16:08:11 +0100 Subject: [PATCH 070/208] Fix the DataTransformerInterface generic types to support the patcher --- DataTransformerInterface.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/DataTransformerInterface.php b/DataTransformerInterface.php index edb3f83c0b..85fb99d218 100644 --- a/DataTransformerInterface.php +++ b/DataTransformerInterface.php @@ -58,7 +58,9 @@ interface DataTransformerInterface * * @param TValue|null $value The value in the original representation * - * @return TTransformedValue|null + * @return mixed + * + * @psalm-return TTransformedValue|null * * @throws TransformationFailedException when the transformation fails */ @@ -87,7 +89,9 @@ public function transform(mixed $value); * * @param TTransformedValue|null $value The value in the transformed representation * - * @return TValue|null + * @return mixed + * + * @psalm-return TValue|null * * @throws TransformationFailedException when the transformation fails */ From a084c352f6b7e7bd41c5cd42e682ea07ccca4c14 Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Thu, 27 Oct 2022 11:20:07 +0200 Subject: [PATCH 071/208] [Validator] Add the type for ConstraintValidatorTestCase::createValidator --- Tests/Extension/Validator/Constraints/FormValidatorTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Tests/Extension/Validator/Constraints/FormValidatorTest.php b/Tests/Extension/Validator/Constraints/FormValidatorTest.php index b5ab6588cb..1097f4f079 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorTest.php @@ -30,6 +30,7 @@ use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Constraints\Valid; +use Symfony\Component\Validator\ConstraintValidatorInterface; use Symfony\Component\Validator\Context\ExecutionContext; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; use Symfony\Component\Validator\Validation; @@ -714,7 +715,7 @@ public function testCauseForNotAllowedExtraFieldsIsTheFormConstraint() $this->assertSame($constraint, $context->getViolations()->get(0)->getConstraint()); } - protected function createValidator() + protected function createValidator(): ConstraintValidatorInterface { return new FormValidator(); } From c6405b824d87a48870749d23aa910c19d6a669b5 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 9 Nov 2022 14:47:29 +0100 Subject: [PATCH 072/208] [Validator] Improve return types in tests --- Tests/Extension/Validator/Constraints/FormValidatorTest.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Tests/Extension/Validator/Constraints/FormValidatorTest.php b/Tests/Extension/Validator/Constraints/FormValidatorTest.php index 1097f4f079..c614a1ac18 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorTest.php @@ -30,7 +30,6 @@ use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Constraints\Valid; -use Symfony\Component\Validator\ConstraintValidatorInterface; use Symfony\Component\Validator\Context\ExecutionContext; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; use Symfony\Component\Validator\Validation; @@ -715,7 +714,7 @@ public function testCauseForNotAllowedExtraFieldsIsTheFormConstraint() $this->assertSame($constraint, $context->getViolations()->get(0)->getConstraint()); } - protected function createValidator(): ConstraintValidatorInterface + protected function createValidator(): FormValidator { return new FormValidator(); } From 2877c2cf1afea424d1b728ed8b85c21d8b54c3c5 Mon Sep 17 00:00:00 2001 From: Christopher Hertel Date: Wed, 16 Nov 2022 19:12:38 +0100 Subject: [PATCH 073/208] add better docs for FormTypeExtensionInterface --- FormTypeExtensionInterface.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/FormTypeExtensionInterface.php b/FormTypeExtensionInterface.php index 6810f0ae91..3c7b46ce9c 100644 --- a/FormTypeExtensionInterface.php +++ b/FormTypeExtensionInterface.php @@ -24,6 +24,8 @@ interface FormTypeExtensionInterface * This method is called after the extended type has built the form to * further modify it. * + * @param array $options + * * @see FormTypeInterface::buildForm() */ public function buildForm(FormBuilderInterface $builder, array $options); @@ -34,6 +36,8 @@ public function buildForm(FormBuilderInterface $builder, array $options); * This method is called after the extended type has built the view to * further modify it. * + * @param array $options + * * @see FormTypeInterface::buildView() */ public function buildView(FormView $view, FormInterface $form, array $options); @@ -44,6 +48,8 @@ public function buildView(FormView $view, FormInterface $form, array $options); * This method is called after the extended type has finished the view to * further modify it. * + * @param array $options + * * @see FormTypeInterface::finishView() */ public function finishView(FormView $view, FormInterface $form, array $options); From bfa6dd3b3cca5c9719ecd807e34580adcf93b441 Mon Sep 17 00:00:00 2001 From: Jordane Vaspard Date: Sat, 26 Nov 2022 15:28:56 +0100 Subject: [PATCH 074/208] [Form] Call getChoicesForValues() once, to prevent several SQL queries --- Extension/Core/Type/ChoiceType.php | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 2dde39e8af..65692faeb4 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -144,11 +144,10 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } } else { - foreach ($data as $value) { - if ($choiceList->getChoicesForValues([$value])) { - $knownValues[] = $value; - unset($unknownValues[$value]); - } + foreach ($choiceList->getChoicesForValues($data) as $index => $choice) { + $value = $data[$index]; + $knownValues[] = $value; + unset($unknownValues[$value]); } } From 3e1fac2b7a91aa28afdf4bee20ec466849b2d5cf Mon Sep 17 00:00:00 2001 From: tigitz Date: Fri, 30 Sep 2022 23:29:24 +0200 Subject: [PATCH 075/208] Leverage class name literal on object --- Command/DebugCommand.php | 2 +- Console/Descriptor/Descriptor.php | 2 +- Console/Descriptor/JsonDescriptor.php | 2 +- Console/Descriptor/TextDescriptor.php | 4 ++-- Extension/Core/Type/FormType.php | 2 +- Extension/Csrf/Type/FormTypeCsrfExtension.php | 4 ++-- Extension/DataCollector/FormDataCollector.php | 2 +- Extension/DataCollector/FormDataExtractor.php | 2 +- Tests/Fixtures/TestExtension.php | 2 +- Tests/FormFactoryBuilderTest.php | 2 +- 10 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index afa283bbd5..0aadd4347a 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -122,7 +122,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $object = $resolvedType->getOptionsResolver(); if (!$object->isDefined($option)) { - $message = sprintf('Option "%s" is not defined in "%s".', $option, \get_class($resolvedType->getInnerType())); + $message = sprintf('Option "%s" is not defined in "%s".', $option, $resolvedType->getInnerType()::class); if ($alternatives = $this->findAlternatives($option, $object->getDefinedOptions())) { if (1 === \count($alternatives)) { diff --git a/Console/Descriptor/Descriptor.php b/Console/Descriptor/Descriptor.php index 3441d017b1..43edf13d35 100644 --- a/Console/Descriptor/Descriptor.php +++ b/Console/Descriptor/Descriptor.php @@ -169,7 +169,7 @@ protected function filterOptionsByDeprecated(ResolvedFormTypeInterface $type) private function getParentOptionsResolver(ResolvedFormTypeInterface $type): OptionsResolver { - $this->parents[$class = \get_class($type->getInnerType())] = []; + $this->parents[$class = $type->getInnerType()::class] = []; if (null !== $type->getParent()) { $optionsResolver = clone $this->getParentOptionsResolver($type->getParent()); diff --git a/Console/Descriptor/JsonDescriptor.php b/Console/Descriptor/JsonDescriptor.php index d40561e468..92d600389f 100644 --- a/Console/Descriptor/JsonDescriptor.php +++ b/Console/Descriptor/JsonDescriptor.php @@ -51,7 +51,7 @@ protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedF $this->sortOptions($formOptions); $data = [ - 'class' => \get_class($resolvedFormType->getInnerType()), + 'class' => $resolvedFormType->getInnerType()::class, 'block_prefix' => $resolvedFormType->getInnerType()->getBlockPrefix(), 'options' => $formOptions, 'parent_types' => $this->parents, diff --git a/Console/Descriptor/TextDescriptor.php b/Console/Descriptor/TextDescriptor.php index 439526af75..53151574bd 100644 --- a/Console/Descriptor/TextDescriptor.php +++ b/Console/Descriptor/TextDescriptor.php @@ -84,7 +84,7 @@ protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedF 'extension' => 'Extension options', ], $formOptions); - $this->output->title(sprintf('%s (Block prefix: "%s")', \get_class($resolvedFormType->getInnerType()), $resolvedFormType->getInnerType()->getBlockPrefix())); + $this->output->title(sprintf('%s (Block prefix: "%s")', $resolvedFormType->getInnerType()::class, $resolvedFormType->getInnerType()->getBlockPrefix())); if ($formOptions) { $this->output->table($tableHeaders, $this->buildTableRows($tableHeaders, $formOptions)); @@ -135,7 +135,7 @@ protected function describeOption(OptionsResolver $optionsResolver, array $optio } array_pop($rows); - $this->output->title(sprintf('%s (%s)', \get_class($options['type']), $options['option'])); + $this->output->title(sprintf('%s (%s)', $options['type']::class, $options['option'])); $this->output->table([], $rows); } diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index 7b5cffe821..e7ae6373ba 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -135,7 +135,7 @@ public function configureOptions(OptionsResolver $resolver) // Derive "data_class" option from passed "data" object $dataClass = function (Options $options) { - return isset($options['data']) && \is_object($options['data']) ? \get_class($options['data']) : null; + return isset($options['data']) && \is_object($options['data']) ? $options['data']::class : null; }; // Derive "empty_data" closure from "data_class" option diff --git a/Extension/Csrf/Type/FormTypeCsrfExtension.php b/Extension/Csrf/Type/FormTypeCsrfExtension.php index ec96dc6aed..bb0d04f509 100644 --- a/Extension/Csrf/Type/FormTypeCsrfExtension.php +++ b/Extension/Csrf/Type/FormTypeCsrfExtension.php @@ -58,7 +58,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) ->addEventSubscriber(new CsrfValidationListener( $options['csrf_field_name'], $options['csrf_token_manager'], - $options['csrf_token_id'] ?: ($builder->getName() ?: \get_class($builder->getType()->getInnerType())), + $options['csrf_token_id'] ?: ($builder->getName() ?: $builder->getType()->getInnerType()::class), $options['csrf_message'], $this->translator, $this->translationDomain, @@ -74,7 +74,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) { if ($options['csrf_protection'] && !$view->parent && $options['compound']) { $factory = $form->getConfig()->getFormFactory(); - $tokenId = $options['csrf_token_id'] ?: ($form->getName() ?: \get_class($form->getConfig()->getType()->getInnerType())); + $tokenId = $options['csrf_token_id'] ?: ($form->getName() ?: $form->getConfig()->getType()->getInnerType()::class); $data = (string) $options['csrf_token_manager']->getToken($tokenId); $csrfForm = $factory->createNamed($options['csrf_field_name'], HiddenType::class, $data, [ diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index 0a9145c624..0fca88069b 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -232,7 +232,7 @@ protected function getCasters(): array FormInterface::class => function (FormInterface $f, array $a) { return [ Caster::PREFIX_VIRTUAL.'name' => $f->getName(), - Caster::PREFIX_VIRTUAL.'type_class' => new ClassStub(\get_class($f->getConfig()->getType()->getInnerType())), + Caster::PREFIX_VIRTUAL.'type_class' => new ClassStub($f->getConfig()->getType()->getInnerType()::class), ]; }, FormView::class => StubCaster::cutInternals(...), diff --git a/Extension/DataCollector/FormDataExtractor.php b/Extension/DataCollector/FormDataExtractor.php index 028e8c06d0..158cf32109 100644 --- a/Extension/DataCollector/FormDataExtractor.php +++ b/Extension/DataCollector/FormDataExtractor.php @@ -27,7 +27,7 @@ public function extractConfiguration(FormInterface $form): array $data = [ 'id' => $this->buildId($form), 'name' => $form->getName(), - 'type_class' => \get_class($form->getConfig()->getType()->getInnerType()), + 'type_class' => $form->getConfig()->getType()->getInnerType()::class, 'synchronized' => $form->isSynchronized(), 'passed_options' => [], 'resolved_options' => [], diff --git a/Tests/Fixtures/TestExtension.php b/Tests/Fixtures/TestExtension.php index 3f7c4005fe..5f6556ca6e 100644 --- a/Tests/Fixtures/TestExtension.php +++ b/Tests/Fixtures/TestExtension.php @@ -31,7 +31,7 @@ public function __construct(FormTypeGuesserInterface $guesser) public function addType(FormTypeInterface $type) { - $this->types[\get_class($type)] = $type; + $this->types[$type::class] = $type; } public function getType($name): FormTypeInterface diff --git a/Tests/FormFactoryBuilderTest.php b/Tests/FormFactoryBuilderTest.php index fd6ef52bd5..818ab1b2b1 100644 --- a/Tests/FormFactoryBuilderTest.php +++ b/Tests/FormFactoryBuilderTest.php @@ -40,7 +40,7 @@ public function testAddType() $extensions = $registry->getExtensions(); $this->assertCount(1, $extensions); - $this->assertTrue($extensions[0]->hasType(\get_class($this->type))); + $this->assertTrue($extensions[0]->hasType($this->type::class)); $this->assertNull($extensions[0]->getTypeGuesser()); } From 941b56e7a76e1930347d49fd9139b672676a882b Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Wed, 28 Dec 2022 15:47:09 +0100 Subject: [PATCH 076/208] Drop v1 contracts packages everywhere --- composer.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index c740948c5e..e859bf2c7f 100644 --- a/composer.json +++ b/composer.json @@ -17,14 +17,14 @@ ], "require": { "php": ">=8.1", - "symfony/deprecation-contracts": "^2.1|^3", + "symfony/deprecation-contracts": "^2.5|^3", "symfony/event-dispatcher": "^5.4|^6.0", "symfony/options-resolver": "^5.4|^6.0", "symfony/polyfill-ctype": "~1.8", "symfony/polyfill-intl-icu": "^1.21", "symfony/polyfill-mbstring": "~1.0", "symfony/property-access": "^5.4|^6.0", - "symfony/service-contracts": "^1.1|^2|^3" + "symfony/service-contracts": "^2.5|^3" }, "require-dev": { "doctrine/collections": "^1.0|^2.0", @@ -52,7 +52,7 @@ "symfony/framework-bundle": "<5.4", "symfony/http-kernel": "<5.4", "symfony/translation": "<5.4", - "symfony/translation-contracts": "<1.1.7", + "symfony/translation-contracts": "<2.5", "symfony/twig-bridge": "<5.4" }, "suggest": { From f82bfb8b6f4c6e8392bfacaa497a1136b72f60c6 Mon Sep 17 00:00:00 2001 From: tigitz Date: Sun, 1 Jan 2023 19:45:34 +0100 Subject: [PATCH 077/208] Leverage arrow function syntax for closure --- ChoiceList/ArrayChoiceList.php | 4 +- .../Factory/DefaultChoiceListFactory.php | 16 +-- .../Factory/PropertyAccessDecorator.php | 48 +++----- Command/DebugCommand.php | 4 +- Console/Descriptor/TextDescriptor.php | 4 +- Extension/Core/Type/CheckboxType.php | 8 +- Extension/Core/Type/ChoiceType.php | 16 +-- Extension/Core/Type/CountryType.php | 4 +- Extension/Core/Type/CurrencyType.php | 4 +- Extension/Core/Type/DateIntervalType.php | 36 ++---- Extension/Core/Type/DateTimeType.php | 24 ++-- Extension/Core/Type/DateType.php | 24 ++-- Extension/Core/Type/EnumType.php | 8 +- Extension/Core/Type/FileType.php | 8 +- Extension/Core/Type/FormType.php | 22 +--- Extension/Core/Type/LocaleType.php | 4 +- Extension/Core/Type/TimeType.php | 20 +-- Extension/Core/Type/TimezoneType.php | 8 +- Extension/Core/Type/WeekType.php | 16 +-- Extension/DataCollector/FormDataCollector.php | 22 ++-- .../Type/FormTypeValidatorExtension.php | 4 +- .../Type/RepeatedTypeValidatorExtension.php | 4 +- .../Type/UploadValidatorExtension.php | 6 +- Extension/Validator/ValidatorTypeGuesser.php | 12 +- Form.php | 4 +- FormTypeGuesserChain.php | 16 +-- Tests/AbstractDivLayoutTest.php | 8 +- Tests/CallbackTransformerTest.php | 4 +- Tests/ChoiceList/ArrayChoiceListTest.php | 8 +- .../Factory/Cache/ChoiceLoaderTest.php | 4 +- .../Factory/CachingFactoryDecoratorTest.php | 12 +- .../Factory/DefaultChoiceListFactoryTest.php | 114 ++++++------------ Tests/ChoiceList/LazyChoiceListTest.php | 8 +- .../Loader/CallbackChoiceLoaderTest.php | 8 +- .../FilterChoiceLoaderDecoratorTest.php | 20 +-- .../Loader/IntlCallbackChoiceLoaderTest.php | 8 +- Tests/Command/DebugCommandTest.php | 10 +- Tests/CompoundFormTest.php | 6 +- .../Descriptor/AbstractDescriptorTest.php | 8 +- .../Core/DataMapper/DataMapperTest.php | 4 +- .../EventListener/ResizeFormListenerTest.php | 4 +- .../Extension/Core/Type/CheckboxTypeTest.php | 8 +- Tests/Extension/Core/Type/ChoiceTypeTest.php | 28 ++--- .../Core/Type/ChoiceTypeTranslationTest.php | 4 +- .../Core/Type/CollectionTypeTest.php | 8 +- .../Extension/Core/Type/DateTimeTypeTest.php | 4 +- Tests/Extension/Core/Type/DateTypeTest.php | 4 +- Tests/Extension/Core/Type/FormTypeTest.php | 10 +- Tests/Extension/Core/Type/TimeTypeTest.php | 4 +- .../DataCollector/FormDataCollectorTest.php | 4 +- .../Constraints/FormValidatorTest.php | 16 +-- .../Type/UploadValidatorExtensionTest.php | 6 +- .../ViolationMapper/ViolationMapperTest.php | 2 +- Tests/Fixtures/ArrayChoiceLoader.php | 4 +- Tests/Fixtures/ChoiceSubType.php | 10 +- Tests/Fixtures/LazyChoiceTypeExtension.php | 10 +- Tests/Resources/TranslationFilesTest.php | 2 +- Tests/SimpleFormTest.php | 4 +- 58 files changed, 206 insertions(+), 494 deletions(-) diff --git a/ChoiceList/ArrayChoiceList.php b/ChoiceList/ArrayChoiceList.php index 524bbf4355..8c25c19ccf 100644 --- a/ChoiceList/ArrayChoiceList.php +++ b/ChoiceList/ArrayChoiceList.php @@ -64,9 +64,7 @@ public function __construct(iterable $choices, callable $value = null) } if (null === $value && $this->castableToString($choices)) { - $value = function ($choice) { - return false === $choice ? '0' : (string) $choice; - }; + $value = fn ($choice) => false === $choice ? '0' : (string) $choice; } if (null !== $value) { diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index ef37699341..c417b84ac5 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -35,9 +35,7 @@ public function createListFromChoices(iterable $choices, callable $value = null, if ($filter) { // filter the choice list lazily return $this->createListFromLoader(new FilterChoiceLoaderDecorator( - new CallbackChoiceLoader(static function () use ($choices) { - return $choices; - } + new CallbackChoiceLoader(static fn () => $choices ), $filter), $value); } @@ -67,9 +65,7 @@ public function createView(ChoiceListInterface $list, array|callable $preferredC } else { // make sure we have keys that reflect order $preferredChoices = array_values($preferredChoices); - $preferredChoices = static function ($choice) use ($preferredChoices) { - return array_search($choice, $preferredChoices, true); - }; + $preferredChoices = static fn ($choice) => array_search($choice, $preferredChoices, true); } } @@ -137,11 +133,9 @@ public function createView(ChoiceListInterface $list, array|callable $preferredC ); } - uksort($preferredViews, static function ($a, $b) use ($preferredViewsOrder): int { - return isset($preferredViewsOrder[$a], $preferredViewsOrder[$b]) - ? $preferredViewsOrder[$a] <=> $preferredViewsOrder[$b] - : 0; - }); + uksort($preferredViews, static fn ($a, $b): int => isset($preferredViewsOrder[$a], $preferredViewsOrder[$b]) + ? $preferredViewsOrder[$a] <=> $preferredViewsOrder[$b] + : 0); return new ChoiceListView($otherViews, $preferredViews); } diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index 2f29bda726..b0b8e479d8 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -63,13 +63,11 @@ public function createListFromChoices(iterable $choices, mixed $value = null, mi if ($value instanceof PropertyPathInterface) { $accessor = $this->propertyAccessor; - $value = function ($choice) use ($accessor, $value) { - // The callable may be invoked with a non-object/array value - // when such values are passed to - // ChoiceListInterface::getValuesForChoices(). Handle this case - // so that the call to getValue() doesn't break. - return \is_object($choice) || \is_array($choice) ? $accessor->getValue($choice, $value) : null; - }; + // The callable may be invoked with a non-object/array value + // when such values are passed to + // ChoiceListInterface::getValuesForChoices(). Handle this case + // so that the call to getValue() doesn't break. + $value = fn ($choice) => \is_object($choice) || \is_array($choice) ? $accessor->getValue($choice, $value) : null; } if (\is_string($filter)) { @@ -78,9 +76,7 @@ public function createListFromChoices(iterable $choices, mixed $value = null, mi if ($filter instanceof PropertyPath) { $accessor = $this->propertyAccessor; - $filter = static function ($choice) use ($accessor, $filter) { - return (\is_object($choice) || \is_array($choice)) && $accessor->getValue($choice, $filter); - }; + $filter = static fn ($choice) => (\is_object($choice) || \is_array($choice)) && $accessor->getValue($choice, $filter); } return $this->decoratedFactory->createListFromChoices($choices, $value, $filter); @@ -94,13 +90,11 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value if ($value instanceof PropertyPathInterface) { $accessor = $this->propertyAccessor; - $value = function ($choice) use ($accessor, $value) { - // The callable may be invoked with a non-object/array value - // when such values are passed to - // ChoiceListInterface::getValuesForChoices(). Handle this case - // so that the call to getValue() doesn't break. - return \is_object($choice) || \is_array($choice) ? $accessor->getValue($choice, $value) : null; - }; + // The callable may be invoked with a non-object/array value + // when such values are passed to + // ChoiceListInterface::getValuesForChoices(). Handle this case + // so that the call to getValue() doesn't break. + $value = fn ($choice) => \is_object($choice) || \is_array($choice) ? $accessor->getValue($choice, $value) : null; } if (\is_string($filter)) { @@ -109,9 +103,7 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value if ($filter instanceof PropertyPath) { $accessor = $this->propertyAccessor; - $filter = static function ($choice) use ($accessor, $filter) { - return (\is_object($choice) || \is_array($choice)) && $accessor->getValue($choice, $filter); - }; + $filter = static fn ($choice) => (\is_object($choice) || \is_array($choice)) && $accessor->getValue($choice, $filter); } return $this->decoratedFactory->createListFromLoader($loader, $value, $filter); @@ -126,9 +118,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = } if ($label instanceof PropertyPathInterface) { - $label = function ($choice) use ($accessor, $label) { - return $accessor->getValue($choice, $label); - }; + $label = fn ($choice) => $accessor->getValue($choice, $label); } if (\is_string($preferredChoices)) { @@ -151,9 +141,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = } if ($index instanceof PropertyPathInterface) { - $index = function ($choice) use ($accessor, $index) { - return $accessor->getValue($choice, $index); - }; + $index = fn ($choice) => $accessor->getValue($choice, $index); } if (\is_string($groupBy)) { @@ -176,9 +164,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = } if ($attr instanceof PropertyPathInterface) { - $attr = function ($choice) use ($accessor, $attr) { - return $accessor->getValue($choice, $attr); - }; + $attr = fn ($choice) => $accessor->getValue($choice, $attr); } if (\is_string($labelTranslationParameters)) { @@ -186,9 +172,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = } if ($labelTranslationParameters instanceof PropertyPath) { - $labelTranslationParameters = static function ($choice) use ($accessor, $labelTranslationParameters) { - return $accessor->getValue($choice, $labelTranslationParameters); - }; + $labelTranslationParameters = static fn ($choice) => $accessor->getValue($choice, $labelTranslationParameters); } return $this->decoratedFactory->createView( diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index 0aadd4347a..a4975470c9 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -204,7 +204,7 @@ private function getCoreTypes(): array $coreExtension = new CoreExtension(); $loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes'); $coreTypes = $loadTypesRefMethod->invoke($coreExtension); - $coreTypes = array_map(function (FormTypeInterface $type) { return $type::class; }, $coreTypes); + $coreTypes = array_map(fn (FormTypeInterface $type) => $type::class, $coreTypes); sort($coreTypes); return $coreTypes; @@ -237,7 +237,7 @@ private function findAlternatives(string $name, array $collection): array } $threshold = 1e3; - $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; }); + $alternatives = array_filter($alternatives, fn ($lev) => $lev < 2 * $threshold); ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE); return array_keys($alternatives); diff --git a/Console/Descriptor/TextDescriptor.php b/Console/Descriptor/TextDescriptor.php index 53151574bd..317287f174 100644 --- a/Console/Descriptor/TextDescriptor.php +++ b/Console/Descriptor/TextDescriptor.php @@ -35,9 +35,7 @@ protected function describeDefaults(array $options) { if ($options['core_types']) { $this->output->section('Built-in form types (Symfony\Component\Form\Extension\Core\Type)'); - $shortClassNames = array_map(function ($fqcn) { - return $this->formatClassLink($fqcn, \array_slice(explode('\\', $fqcn), -1)[0]); - }, $options['core_types']); + $shortClassNames = array_map(fn ($fqcn) => $this->formatClassLink($fqcn, \array_slice(explode('\\', $fqcn), -1)[0]), $options['core_types']); for ($i = 0, $loopsMax = \count($shortClassNames); $i * 5 < $loopsMax; ++$i) { $this->output->writeln(' '.implode(', ', \array_slice($shortClassNames, $i * 5, 5))); } diff --git a/Extension/Core/Type/CheckboxType.php b/Extension/Core/Type/CheckboxType.php index d513694a4c..b9f5c3f478 100644 --- a/Extension/Core/Type/CheckboxType.php +++ b/Extension/Core/Type/CheckboxType.php @@ -42,9 +42,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) public function configureOptions(OptionsResolver $resolver) { - $emptyData = function (FormInterface $form, $viewData) { - return $viewData; - }; + $emptyData = fn (FormInterface $form, $viewData) => $viewData; $resolver->setDefaults([ 'value' => '1', @@ -52,9 +50,7 @@ public function configureOptions(OptionsResolver $resolver) 'compound' => false, 'false_values' => [null], 'invalid_message' => 'The checkbox has an invalid value.', - 'is_empty_callback' => static function ($modelData): bool { - return false === $modelData; - }, + 'is_empty_callback' => static fn ($modelData): bool => false === $modelData, ]); $resolver->setAllowedTypes('false_values', 'array'); diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 65692faeb4..051795b957 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -245,13 +245,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) // closure here that is optimized for the value of the form, to // avoid making the type check inside the closure. if ($options['multiple']) { - $view->vars['is_selected'] = function ($choice, array $values) { - return \in_array($choice, $values, true); - }; + $view->vars['is_selected'] = fn ($choice, array $values) => \in_array($choice, $values, true); } else { - $view->vars['is_selected'] = function ($choice, $value) { - return $choice === $value; - }; + $view->vars['is_selected'] = fn ($choice, $value) => $choice === $value; } // Check if the choices already contain the empty value @@ -301,9 +297,7 @@ public function configureOptions(OptionsResolver $resolver) return ''; }; - $placeholderDefault = function (Options $options) { - return $options['required'] ? null : ''; - }; + $placeholderDefault = fn (Options $options) => $options['required'] ? null : ''; $placeholderNormalizer = function (Options $options, $placeholder) { if ($options['multiple']) { @@ -324,9 +318,7 @@ public function configureOptions(OptionsResolver $resolver) return $placeholder; }; - $compound = function (Options $options) { - return $options['expanded']; - }; + $compound = fn (Options $options) => $options['expanded']; $choiceTranslationDomainNormalizer = function (Options $options, $choiceTranslationDomain) { if (true === $choiceTranslationDomain) { diff --git a/Extension/Core/Type/CountryType.php b/Extension/Core/Type/CountryType.php index 25aa652f5c..69f284c823 100644 --- a/Extension/Core/Type/CountryType.php +++ b/Extension/Core/Type/CountryType.php @@ -33,9 +33,7 @@ public function configureOptions(OptionsResolver $resolver) $choiceTranslationLocale = $options['choice_translation_locale']; $alpha3 = $options['alpha3']; - return ChoiceList::loader($this, new IntlCallbackChoiceLoader(function () use ($choiceTranslationLocale, $alpha3) { - return array_flip($alpha3 ? Countries::getAlpha3Names($choiceTranslationLocale) : Countries::getNames($choiceTranslationLocale)); - }), [$choiceTranslationLocale, $alpha3]); + return ChoiceList::loader($this, new IntlCallbackChoiceLoader(fn () => array_flip($alpha3 ? Countries::getAlpha3Names($choiceTranslationLocale) : Countries::getNames($choiceTranslationLocale))), [$choiceTranslationLocale, $alpha3]); }, 'choice_translation_domain' => false, 'choice_translation_locale' => null, diff --git a/Extension/Core/Type/CurrencyType.php b/Extension/Core/Type/CurrencyType.php index 435bc15709..f697f35416 100644 --- a/Extension/Core/Type/CurrencyType.php +++ b/Extension/Core/Type/CurrencyType.php @@ -32,9 +32,7 @@ public function configureOptions(OptionsResolver $resolver) $choiceTranslationLocale = $options['choice_translation_locale']; - return ChoiceList::loader($this, new IntlCallbackChoiceLoader(function () use ($choiceTranslationLocale) { - return array_flip(Currencies::getNames($choiceTranslationLocale)); - }), $choiceTranslationLocale); + return ChoiceList::loader($this, new IntlCallbackChoiceLoader(fn () => array_flip(Currencies::getNames($choiceTranslationLocale))), $choiceTranslationLocale); }, 'choice_translation_domain' => false, 'choice_translation_locale' => null, diff --git a/Extension/Core/Type/DateIntervalType.php b/Extension/Core/Type/DateIntervalType.php index e745c1af04..db1a14b52b 100644 --- a/Extension/Core/Type/DateIntervalType.php +++ b/Extension/Core/Type/DateIntervalType.php @@ -159,16 +159,10 @@ public function buildView(FormView $view, FormInterface $form, array $options) public function configureOptions(OptionsResolver $resolver) { - $compound = function (Options $options) { - return 'single_text' !== $options['widget']; - }; - $emptyData = function (Options $options) { - return 'single_text' === $options['widget'] ? '' : []; - }; + $compound = fn (Options $options) => 'single_text' !== $options['widget']; + $emptyData = fn (Options $options) => 'single_text' === $options['widget'] ? '' : []; - $placeholderDefault = function (Options $options) { - return $options['required'] ? null : ''; - }; + $placeholderDefault = fn (Options $options) => $options['required'] ? null : ''; $placeholderNormalizer = function (Options $options, $placeholder) use ($placeholderDefault) { if (\is_array($placeholder)) { @@ -180,20 +174,16 @@ public function configureOptions(OptionsResolver $resolver) return array_fill_keys(self::TIME_PARTS, $placeholder); }; - $labelsNormalizer = function (Options $options, array $labels) { - return array_replace([ - 'years' => null, - 'months' => null, - 'days' => null, - 'weeks' => null, - 'hours' => null, - 'minutes' => null, - 'seconds' => null, - 'invert' => 'Negative interval', - ], array_filter($labels, function ($label) { - return null !== $label; - })); - }; + $labelsNormalizer = fn (Options $options, array $labels) => array_replace([ + 'years' => null, + 'months' => null, + 'days' => null, + 'weeks' => null, + 'hours' => null, + 'minutes' => null, + 'seconds' => null, + 'invert' => 'Negative interval', + ], array_filter($labels, fn ($label) => null !== $label)); $resolver->setDefaults([ 'with_years' => true, diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index 35022530e6..bf7a734a9b 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -107,12 +107,10 @@ public function buildForm(FormBuilderInterface $builder, array $options) ])); if ($emptyData instanceof \Closure) { - $lazyEmptyData = static function ($option) use ($emptyData) { - return static function (FormInterface $form) use ($emptyData, $option) { - $emptyData = $emptyData($form->getParent()); + $lazyEmptyData = static fn ($option) => static function (FormInterface $form) use ($emptyData, $option) { + $emptyData = $emptyData($form->getParent()); - return $emptyData[$option] ?? ''; - }; + return $emptyData[$option] ?? ''; }; $dateOptions['empty_data'] = $lazyEmptyData('date'); @@ -222,19 +220,13 @@ public function buildView(FormView $view, FormInterface $form, array $options) public function configureOptions(OptionsResolver $resolver) { - $compound = function (Options $options) { - return 'single_text' !== $options['widget']; - }; + $compound = fn (Options $options) => 'single_text' !== $options['widget']; // Defaults to the value of "widget" - $dateWidget = function (Options $options) { - return 'single_text' === $options['widget'] ? null : $options['widget']; - }; + $dateWidget = fn (Options $options) => 'single_text' === $options['widget'] ? null : $options['widget']; // Defaults to the value of "widget" - $timeWidget = function (Options $options) { - return 'single_text' === $options['widget'] ? null : $options['widget']; - }; + $timeWidget = fn (Options $options) => 'single_text' === $options['widget'] ? null : $options['widget']; $resolver->setDefaults([ 'input' => 'datetime', @@ -260,9 +252,7 @@ public function configureOptions(OptionsResolver $resolver) 'compound' => $compound, 'date_label' => null, 'time_label' => null, - 'empty_data' => function (Options $options) { - return $options['compound'] ? [] : ''; - }, + 'empty_data' => fn (Options $options) => $options['compound'] ? [] : '', 'input_format' => 'Y-m-d H:i:s', 'invalid_message' => 'Please enter a valid date and time.', ]); diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index d88819ebd6..b18df900ff 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -81,12 +81,10 @@ public function buildForm(FormBuilderInterface $builder, array $options) $emptyData = $builder->getEmptyData() ?: []; if ($emptyData instanceof \Closure) { - $lazyEmptyData = static function ($option) use ($emptyData) { - return static function (FormInterface $form) use ($emptyData, $option) { - $emptyData = $emptyData($form->getParent()); + $lazyEmptyData = static fn ($option) => static function (FormInterface $form) use ($emptyData, $option) { + $emptyData = $emptyData($form->getParent()); - return $emptyData[$option] ?? ''; - }; + return $emptyData[$option] ?? ''; }; $yearOptions['empty_data'] = $lazyEmptyData('year'); @@ -218,13 +216,9 @@ public function finishView(FormView $view, FormInterface $form, array $options) public function configureOptions(OptionsResolver $resolver) { - $compound = function (Options $options) { - return 'single_text' !== $options['widget']; - }; + $compound = fn (Options $options) => 'single_text' !== $options['widget']; - $placeholderDefault = function (Options $options) { - return $options['required'] ? null : ''; - }; + $placeholderDefault = fn (Options $options) => $options['required'] ? null : ''; $placeholderNormalizer = function (Options $options, $placeholder) use ($placeholderDefault) { if (\is_array($placeholder)) { @@ -260,9 +254,7 @@ public function configureOptions(OptionsResolver $resolver) ]; }; - $format = function (Options $options) { - return 'single_text' === $options['widget'] ? self::HTML5_FORMAT : self::DEFAULT_FORMAT; - }; + $format = fn (Options $options) => 'single_text' === $options['widget'] ? self::HTML5_FORMAT : self::DEFAULT_FORMAT; $resolver->setDefaults([ 'years' => range((int) date('Y') - 5, (int) date('Y') + 5), @@ -285,9 +277,7 @@ public function configureOptions(OptionsResolver $resolver) // this option. 'data_class' => null, 'compound' => $compound, - 'empty_data' => function (Options $options) { - return $options['compound'] ? [] : ''; - }, + 'empty_data' => fn (Options $options) => $options['compound'] ? [] : '', 'choice_translation_domain' => false, 'input_format' => 'Y-m-d', 'invalid_message' => 'Please enter a valid date.', diff --git a/Extension/Core/Type/EnumType.php b/Extension/Core/Type/EnumType.php index 33944c2aec..003819e065 100644 --- a/Extension/Core/Type/EnumType.php +++ b/Extension/Core/Type/EnumType.php @@ -28,12 +28,8 @@ public function configureOptions(OptionsResolver $resolver): void ->setRequired(['class']) ->setAllowedTypes('class', 'string') ->setAllowedValues('class', enum_exists(...)) - ->setDefault('choices', static function (Options $options): array { - return $options['class']::cases(); - }) - ->setDefault('choice_label', static function (\UnitEnum $choice): string { - return $choice->name; - }) + ->setDefault('choices', static fn (Options $options): array => $options['class']::cases()) + ->setDefault('choice_label', static fn (\UnitEnum $choice): string => $choice->name) ->setDefault('choice_value', static function (Options $options): ?\Closure { if (!is_a($options['class'], \BackedEnum::class, true)) { return null; diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index 9e8e81394e..d1bad77505 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -104,14 +104,10 @@ public function configureOptions(OptionsResolver $resolver) { $dataClass = null; if (class_exists(File::class)) { - $dataClass = function (Options $options) { - return $options['multiple'] ? null : File::class; - }; + $dataClass = fn (Options $options) => $options['multiple'] ? null : File::class; } - $emptyData = function (Options $options) { - return $options['multiple'] ? [] : null; - }; + $emptyData = fn (Options $options) => $options['multiple'] ? [] : null; $resolver->setDefaults([ 'compound' => false, diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index e7ae6373ba..c08d5f9b52 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -134,37 +134,25 @@ public function configureOptions(OptionsResolver $resolver) parent::configureOptions($resolver); // Derive "data_class" option from passed "data" object - $dataClass = function (Options $options) { - return isset($options['data']) && \is_object($options['data']) ? $options['data']::class : null; - }; + $dataClass = fn (Options $options) => isset($options['data']) && \is_object($options['data']) ? $options['data']::class : null; // Derive "empty_data" closure from "data_class" option $emptyData = function (Options $options) { $class = $options['data_class']; if (null !== $class) { - return function (FormInterface $form) use ($class) { - return $form->isEmpty() && !$form->isRequired() ? null : new $class(); - }; + return fn (FormInterface $form) => $form->isEmpty() && !$form->isRequired() ? null : new $class(); } - return function (FormInterface $form) { - return $form->getConfig()->getCompound() ? [] : ''; - }; + return fn (FormInterface $form) => $form->getConfig()->getCompound() ? [] : ''; }; // Wrap "post_max_size_message" in a closure to translate it lazily - $uploadMaxSizeMessage = function (Options $options) { - return function () use ($options) { - return $options['post_max_size_message']; - }; - }; + $uploadMaxSizeMessage = fn (Options $options) => fn () => $options['post_max_size_message']; // For any form that is not represented by a single HTML control, // errors should bubble up by default - $errorBubbling = function (Options $options) { - return $options['compound'] && !$options['inherit_data']; - }; + $errorBubbling = fn (Options $options) => $options['compound'] && !$options['inherit_data']; // If data is given, the form is locked to that data // (independent of its value) diff --git a/Extension/Core/Type/LocaleType.php b/Extension/Core/Type/LocaleType.php index d4adca1f59..0cdde9e46b 100644 --- a/Extension/Core/Type/LocaleType.php +++ b/Extension/Core/Type/LocaleType.php @@ -32,9 +32,7 @@ public function configureOptions(OptionsResolver $resolver) $choiceTranslationLocale = $options['choice_translation_locale']; - return ChoiceList::loader($this, new IntlCallbackChoiceLoader(function () use ($choiceTranslationLocale) { - return array_flip(Locales::getNames($choiceTranslationLocale)); - }), $choiceTranslationLocale); + return ChoiceList::loader($this, new IntlCallbackChoiceLoader(fn () => array_flip(Locales::getNames($choiceTranslationLocale))), $choiceTranslationLocale); }, 'choice_translation_domain' => false, 'choice_translation_locale' => null, diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 2b8bbb5010..78929d79bf 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -96,12 +96,10 @@ public function buildForm(FormBuilderInterface $builder, array $options) $emptyData = $builder->getEmptyData() ?: []; if ($emptyData instanceof \Closure) { - $lazyEmptyData = static function ($option) use ($emptyData) { - return static function (FormInterface $form) use ($emptyData, $option) { - $emptyData = $emptyData($form->getParent()); + $lazyEmptyData = static fn ($option) => static function (FormInterface $form) use ($emptyData, $option) { + $emptyData = $emptyData($form->getParent()); - return $emptyData[$option] ?? ''; - }; + return $emptyData[$option] ?? ''; }; $hourOptions['empty_data'] = $lazyEmptyData('hour'); @@ -235,13 +233,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) public function configureOptions(OptionsResolver $resolver) { - $compound = function (Options $options) { - return 'single_text' !== $options['widget']; - }; + $compound = fn (Options $options) => 'single_text' !== $options['widget']; - $placeholderDefault = function (Options $options) { - return $options['required'] ? null : ''; - }; + $placeholderDefault = fn (Options $options) => $options['required'] ? null : ''; $placeholderNormalizer = function (Options $options, $placeholder) use ($placeholderDefault) { if (\is_array($placeholder)) { @@ -324,9 +318,7 @@ public function configureOptions(OptionsResolver $resolver) // representation is not \DateTime, but an array, we need to unset // this option. 'data_class' => null, - 'empty_data' => function (Options $options) { - return $options['compound'] ? [] : ''; - }, + 'empty_data' => fn (Options $options) => $options['compound'] ? [] : '', 'compound' => $compound, 'choice_translation_domain' => false, 'invalid_message' => 'Please enter a valid time.', diff --git a/Extension/Core/Type/TimezoneType.php b/Extension/Core/Type/TimezoneType.php index edea6678e2..d6ce3c3435 100644 --- a/Extension/Core/Type/TimezoneType.php +++ b/Extension/Core/Type/TimezoneType.php @@ -48,14 +48,10 @@ public function configureOptions(OptionsResolver $resolver) $choiceTranslationLocale = $options['choice_translation_locale']; - return ChoiceList::loader($this, new IntlCallbackChoiceLoader(function () use ($input, $choiceTranslationLocale) { - return self::getIntlTimezones($input, $choiceTranslationLocale); - }), [$input, $choiceTranslationLocale]); + return ChoiceList::loader($this, new IntlCallbackChoiceLoader(fn () => self::getIntlTimezones($input, $choiceTranslationLocale)), [$input, $choiceTranslationLocale]); } - return ChoiceList::lazy($this, function () use ($input) { - return self::getPhpTimezones($input); - }, $input); + return ChoiceList::lazy($this, fn () => self::getPhpTimezones($input), $input); }, 'choice_translation_domain' => false, 'choice_translation_locale' => null, diff --git a/Extension/Core/Type/WeekType.php b/Extension/Core/Type/WeekType.php index 760bb880b1..5b05e0a310 100644 --- a/Extension/Core/Type/WeekType.php +++ b/Extension/Core/Type/WeekType.php @@ -91,13 +91,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) public function configureOptions(OptionsResolver $resolver) { - $compound = function (Options $options) { - return 'single_text' !== $options['widget']; - }; + $compound = fn (Options $options) => 'single_text' !== $options['widget']; - $placeholderDefault = function (Options $options) { - return $options['required'] ? null : ''; - }; + $placeholderDefault = fn (Options $options) => $options['required'] ? null : ''; $placeholderNormalizer = function (Options $options, $placeholder) use ($placeholderDefault) { if (\is_array($placeholder)) { @@ -137,13 +133,9 @@ public function configureOptions(OptionsResolver $resolver) 'widget' => 'single_text', 'input' => 'array', 'placeholder' => $placeholderDefault, - 'html5' => static function (Options $options) { - return 'single_text' === $options['widget']; - }, + 'html5' => static fn (Options $options) => 'single_text' === $options['widget'], 'error_bubbling' => false, - 'empty_data' => function (Options $options) { - return $options['compound'] ? [] : ''; - }, + 'empty_data' => fn (Options $options) => $options['compound'] ? [] : '', 'compound' => $compound, 'choice_translation_domain' => false, 'invalid_message' => 'Please enter a valid week.', diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index 0fca88069b..cdc13c9d03 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -229,20 +229,16 @@ protected function getCasters(): array return $a; }, - FormInterface::class => function (FormInterface $f, array $a) { - return [ - Caster::PREFIX_VIRTUAL.'name' => $f->getName(), - Caster::PREFIX_VIRTUAL.'type_class' => new ClassStub($f->getConfig()->getType()->getInnerType()::class), - ]; - }, + FormInterface::class => fn (FormInterface $f, array $a) => [ + Caster::PREFIX_VIRTUAL.'name' => $f->getName(), + Caster::PREFIX_VIRTUAL.'type_class' => new ClassStub($f->getConfig()->getType()->getInnerType()::class), + ], FormView::class => StubCaster::cutInternals(...), - ConstraintViolationInterface::class => function (ConstraintViolationInterface $v, array $a) { - return [ - Caster::PREFIX_VIRTUAL.'root' => $v->getRoot(), - Caster::PREFIX_VIRTUAL.'path' => $v->getPropertyPath(), - Caster::PREFIX_VIRTUAL.'value' => $v->getInvalidValue(), - ]; - }, + ConstraintViolationInterface::class => fn (ConstraintViolationInterface $v, array $a) => [ + Caster::PREFIX_VIRTUAL.'root' => $v->getRoot(), + Caster::PREFIX_VIRTUAL.'path' => $v->getPropertyPath(), + Caster::PREFIX_VIRTUAL.'value' => $v->getInvalidValue(), + ], ]; } diff --git a/Extension/Validator/Type/FormTypeValidatorExtension.php b/Extension/Validator/Type/FormTypeValidatorExtension.php index 26653dc998..b28cf870b0 100644 --- a/Extension/Validator/Type/FormTypeValidatorExtension.php +++ b/Extension/Validator/Type/FormTypeValidatorExtension.php @@ -47,9 +47,7 @@ public function configureOptions(OptionsResolver $resolver) parent::configureOptions($resolver); // Constraint should always be converted to an array - $constraintsNormalizer = function (Options $options, $constraints) { - return \is_object($constraints) ? [$constraints] : (array) $constraints; - }; + $constraintsNormalizer = fn (Options $options, $constraints) => \is_object($constraints) ? [$constraints] : (array) $constraints; $resolver->setDefaults([ 'error_mapping' => [], diff --git a/Extension/Validator/Type/RepeatedTypeValidatorExtension.php b/Extension/Validator/Type/RepeatedTypeValidatorExtension.php index 664a3edae2..0e8a4ccf14 100644 --- a/Extension/Validator/Type/RepeatedTypeValidatorExtension.php +++ b/Extension/Validator/Type/RepeatedTypeValidatorExtension.php @@ -24,9 +24,7 @@ class RepeatedTypeValidatorExtension extends AbstractTypeExtension public function configureOptions(OptionsResolver $resolver) { // Map errors to the first field - $errorMapping = function (Options $options) { - return ['.' => $options['first_name']]; - }; + $errorMapping = fn (Options $options) => ['.' => $options['first_name']]; $resolver->setDefaults([ 'error_mapping' => $errorMapping, diff --git a/Extension/Validator/Type/UploadValidatorExtension.php b/Extension/Validator/Type/UploadValidatorExtension.php index 14f6c8f2d8..c720e6a0ec 100644 --- a/Extension/Validator/Type/UploadValidatorExtension.php +++ b/Extension/Validator/Type/UploadValidatorExtension.php @@ -36,11 +36,7 @@ public function configureOptions(OptionsResolver $resolver) { $translator = $this->translator; $translationDomain = $this->translationDomain; - $resolver->setNormalizer('upload_max_size_message', function (Options $options, $message) use ($translator, $translationDomain) { - return function () use ($translator, $translationDomain, $message) { - return $translator->trans($message(), [], $translationDomain); - }; - }); + $resolver->setNormalizer('upload_max_size_message', fn (Options $options, $message) => fn () => $translator->trans($message(), [], $translationDomain)); } public static function getExtendedTypes(): iterable diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index 6fb47884d2..4d65d071ee 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -66,9 +66,7 @@ public function __construct(MetadataFactoryInterface $metadataFactory) public function guessType(string $class, string $property): ?TypeGuess { - return $this->guess($class, $property, function (Constraint $constraint) { - return $this->guessTypeForConstraint($constraint); - }); + return $this->guess($class, $property, fn (Constraint $constraint) => $this->guessTypeForConstraint($constraint)); } public function guessRequired(string $class, string $property): ?ValueGuess @@ -82,16 +80,12 @@ public function guessRequired(string $class, string $property): ?ValueGuess public function guessMaxLength(string $class, string $property): ?ValueGuess { - return $this->guess($class, $property, function (Constraint $constraint) { - return $this->guessMaxLengthForConstraint($constraint); - }); + return $this->guess($class, $property, fn (Constraint $constraint) => $this->guessMaxLengthForConstraint($constraint)); } public function guessPattern(string $class, string $property): ?ValueGuess { - return $this->guess($class, $property, function (Constraint $constraint) { - return $this->guessPatternForConstraint($constraint); - }); + return $this->guess($class, $property, fn (Constraint $constraint) => $this->guessPatternForConstraint($constraint)); } /** diff --git a/Form.php b/Form.php index 7acf8c7251..9d6344c869 100644 --- a/Form.php +++ b/Form.php @@ -930,9 +930,7 @@ private function sort(array &$children): void return; } - uksort($children, static function ($a, $b) use ($c): int { - return [$c[$b]['p'], $c[$a]['i']] <=> [$c[$a]['p'], $c[$b]['i']]; - }); + uksort($children, static fn ($a, $b): int => [$c[$b]['p'], $c[$a]['i']] <=> [$c[$a]['p'], $c[$b]['i']]); } /** diff --git a/FormTypeGuesserChain.php b/FormTypeGuesserChain.php index 7d8f617f7b..2ac8e3c263 100644 --- a/FormTypeGuesserChain.php +++ b/FormTypeGuesserChain.php @@ -45,30 +45,22 @@ public function __construct(iterable $guessers) public function guessType(string $class, string $property): ?TypeGuess { - return $this->guess(function ($guesser) use ($class, $property) { - return $guesser->guessType($class, $property); - }); + return $this->guess(fn ($guesser) => $guesser->guessType($class, $property)); } public function guessRequired(string $class, string $property): ?ValueGuess { - return $this->guess(function ($guesser) use ($class, $property) { - return $guesser->guessRequired($class, $property); - }); + return $this->guess(fn ($guesser) => $guesser->guessRequired($class, $property)); } public function guessMaxLength(string $class, string $property): ?ValueGuess { - return $this->guess(function ($guesser) use ($class, $property) { - return $guesser->guessMaxLength($class, $property); - }); + return $this->guess(fn ($guesser) => $guesser->guessMaxLength($class, $property)); } public function guessPattern(string $class, string $property): ?ValueGuess { - return $this->guess(function ($guesser) use ($class, $property) { - return $guesser->guessPattern($class, $property); - }); + return $this->guess(fn ($guesser) => $guesser->guessPattern($class, $property)); } /** diff --git a/Tests/AbstractDivLayoutTest.php b/Tests/AbstractDivLayoutTest.php index 6a38a77017..23b90ebf76 100644 --- a/Tests/AbstractDivLayoutTest.php +++ b/Tests/AbstractDivLayoutTest.php @@ -763,9 +763,7 @@ public function testSingleChoiceExpandedWithLabelsSetFalseByCallable() { $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'choice_label' => function () { - return false; - }, + 'choice_label' => fn () => false, 'multiple' => false, 'expanded' => true, ]); @@ -840,9 +838,7 @@ public function testMultipleChoiceExpandedWithLabelsSetFalseByCallable() { $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a'], [ 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'choice_label' => function () { - return false; - }, + 'choice_label' => fn () => false, 'multiple' => true, 'expanded' => true, ]); diff --git a/Tests/CallbackTransformerTest.php b/Tests/CallbackTransformerTest.php index 9142e1fa3c..1fb6134dd9 100644 --- a/Tests/CallbackTransformerTest.php +++ b/Tests/CallbackTransformerTest.php @@ -19,8 +19,8 @@ class CallbackTransformerTest extends TestCase public function testTransform() { $transformer = new CallbackTransformer( - function ($value) { return $value.' has been transformed'; }, - function ($value) { return $value.' has reversely been transformed'; } + fn ($value) => $value.' has been transformed', + fn ($value) => $value.' has reversely been transformed' ); $this->assertEquals('foo has been transformed', $transformer->transform('foo')); diff --git a/Tests/ChoiceList/ArrayChoiceListTest.php b/Tests/ChoiceList/ArrayChoiceListTest.php index ce5f2e933f..5dc2e5db90 100644 --- a/Tests/ChoiceList/ArrayChoiceListTest.php +++ b/Tests/ChoiceList/ArrayChoiceListTest.php @@ -45,9 +45,7 @@ protected function getValues() public function testCreateChoiceListWithValueCallback() { - $callback = function ($choice) { - return ':'.$choice; - }; + $callback = fn ($choice) => ':'.$choice; $choiceList = new ArrayChoiceList([2 => 'foo', 7 => 'bar', 10 => 'baz'], $callback); @@ -112,9 +110,7 @@ public function testCreateChoiceListWithGroupedChoices() public function testCompareChoicesByIdentityByDefault() { - $callback = function ($choice) { - return $choice->value; - }; + $callback = fn ($choice) => $choice->value; $obj1 = (object) ['value' => 'value1']; $obj2 = (object) ['value' => 'value2']; diff --git a/Tests/ChoiceList/Factory/Cache/ChoiceLoaderTest.php b/Tests/ChoiceList/Factory/Cache/ChoiceLoaderTest.php index b2d0d2e6d7..6134160046 100644 --- a/Tests/ChoiceList/Factory/Cache/ChoiceLoaderTest.php +++ b/Tests/ChoiceList/Factory/Cache/ChoiceLoaderTest.php @@ -26,9 +26,7 @@ public function testSameFormTypeUseCachedLoader() $choiceList = new ArrayChoiceList($choices); $type = new FormType(); - $decorated = new CallbackChoiceLoader(static function () use ($choices) { - return $choices; - }); + $decorated = new CallbackChoiceLoader(static fn () => $choices); $loader1 = new ChoiceLoader($type, $decorated); $loader2 = new ChoiceLoader($type, new ArrayChoiceLoader()); diff --git a/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php b/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php index 4f5c4eb0e3..48aa3677a5 100644 --- a/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php +++ b/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php @@ -146,9 +146,7 @@ public function testCreateFromChoicesSameFilterClosure() $filter = function () {}; $list1 = $this->factory->createListFromChoices($choices, null, $filter); $list2 = $this->factory->createListFromChoices($choices, null, $filter); - $lazyChoiceList = new LazyChoiceList(new FilterChoiceLoaderDecorator(new CallbackChoiceLoader(static function () use ($choices) { - return $choices; - }), $filter), null); + $lazyChoiceList = new LazyChoiceList(new FilterChoiceLoaderDecorator(new CallbackChoiceLoader(static fn () => $choices), $filter), null); $this->assertNotSame($list1, $list2); $this->assertEquals($lazyChoiceList, $list1); @@ -162,9 +160,7 @@ public function testCreateFromChoicesSameFilterClosureUseCache() $filterCallback = function () {}; $list1 = $this->factory->createListFromChoices($choices, null, ChoiceList::filter($formType, $filterCallback)); $list2 = $this->factory->createListFromChoices($choices, null, ChoiceList::filter($formType, function () {})); - $lazyChoiceList = new LazyChoiceList(new FilterChoiceLoaderDecorator(new CallbackChoiceLoader(static function () use ($choices) { - return $choices; - }), function () {}), null); + $lazyChoiceList = new LazyChoiceList(new FilterChoiceLoaderDecorator(new CallbackChoiceLoader(static fn () => $choices), function () {}), null); $this->assertSame($list1, $list2); $this->assertEquals($lazyChoiceList, $list1); @@ -178,9 +174,7 @@ public function testCreateFromChoicesDifferentFilterClosure() $closure2 = function () {}; $list1 = $this->factory->createListFromChoices($choices, null, $closure1); $list2 = $this->factory->createListFromChoices($choices, null, $closure2); - $lazyChoiceList = new LazyChoiceList(new FilterChoiceLoaderDecorator(new CallbackChoiceLoader(static function () use ($choices) { - return $choices; - }), function () {}), null); + $lazyChoiceList = new LazyChoiceList(new FilterChoiceLoaderDecorator(new CallbackChoiceLoader(static fn () => $choices), function () {}), null); $this->assertNotSame($list1, $list2); $this->assertEquals($lazyChoiceList, $list1); diff --git a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index 054739c8cc..35526a98f6 100644 --- a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -151,7 +151,7 @@ public function testCreateFromChoicesFlatValuesAsClosure() { $list = $this->factory->createListFromChoices( ['A' => $this->obj1, 'B' => $this->obj2, 'C' => $this->obj3, 'D' => $this->obj4], - function ($object) { return $object->value; } + fn ($object) => $object->value ); $this->assertObjectListWithCustomValues($list); @@ -199,7 +199,7 @@ public function testCreateFromChoicesGroupedValuesAsClosure() 'Group 1' => ['A' => $this->obj1, 'B' => $this->obj2], 'Group 2' => ['C' => $this->obj3, 'D' => $this->obj4], ], - function ($object) { return $object->value; } + fn ($object) => $object->value ); $this->assertObjectListWithCustomValues($list); @@ -210,9 +210,7 @@ public function testCreateFromFilteredChoices() $list = $this->factory->createListFromChoices( ['A' => $this->obj1, 'B' => $this->obj2, 'C' => $this->obj3, 'D' => $this->obj4, 'E' => $this->obj5, 'F' => $this->obj6], null, - function ($choice) { - return $choice !== $this->obj5 && $choice !== $this->obj6; - } + fn ($choice) => $choice !== $this->obj5 && $choice !== $this->obj6 ); $this->assertObjectListWithGeneratedValues($list); @@ -228,9 +226,7 @@ public function testCreateFromChoicesGroupedAndFiltered() 'Group 4' => [/* empty group should be filtered */], ], null, - function ($choice) { - return $choice !== $this->obj5 && $choice !== $this->obj6; - } + fn ($choice) => $choice !== $this->obj5 && $choice !== $this->obj6 ); $this->assertObjectListWithGeneratedValues($list); @@ -246,9 +242,7 @@ public function testCreateFromChoicesGroupedAndFilteredTraversable() 'Group 4' => [/* empty group should be filtered */], ]), null, - function ($choice) { - return $choice !== $this->obj5 && $choice !== $this->obj6; - } + fn ($choice) => $choice !== $this->obj5 && $choice !== $this->obj6 ); $this->assertObjectListWithGeneratedValues($list); @@ -313,9 +307,7 @@ public function testCreateViewFlatPreferredChoicesSameOrder() [$this->obj2, $this->obj1, $this->obj4, $this->obj3] ); - $preferredLabels = array_map(static function (ChoiceView $view): string { - return $view->label; - }, $view->preferredChoices); + $preferredLabels = array_map(static fn (ChoiceView $view): string => $view->label, $view->preferredChoices); $this->assertSame( [ @@ -338,11 +330,7 @@ public function testCreateViewFlatPreferredChoiceGroupsSameOrder() $this->getGroup(...) ); - $preferredLabels = array_map(static function (ChoiceGroupView $groupView): array { - return array_map(static function (ChoiceView $view): string { - return $view->label; - }, $groupView->choices); - }, $view->preferredChoices); + $preferredLabels = array_map(static fn (ChoiceGroupView $groupView): array => array_map(static fn (ChoiceView $view): string => $view->label, $groupView->choices), $view->preferredChoices); $this->assertEquals( [ @@ -393,9 +381,7 @@ public function testCreateViewFlatPreferredChoicesAsClosure() $view = $this->factory->createView( $this->list, - function ($object) use ($obj2, $obj3) { - return $obj2 === $object || $obj3 === $object; - } + fn ($object) => $obj2 === $object || $obj3 === $object ); $this->assertFlatView($view); @@ -405,9 +391,7 @@ public function testCreateViewFlatPreferredChoicesClosureReceivesKey() { $view = $this->factory->createView( $this->list, - function ($object, $key) { - return 'B' === $key || 'C' === $key; - } + fn ($object, $key) => 'B' === $key || 'C' === $key ); $this->assertFlatView($view); @@ -417,9 +401,7 @@ public function testCreateViewFlatPreferredChoicesClosureReceivesValue() { $view = $this->factory->createView( $this->list, - function ($object, $key, $value) { - return '1' === $value || '2' === $value; - } + fn ($object, $key, $value) => '1' === $value || '2' === $value ); $this->assertFlatView($view); @@ -441,9 +423,7 @@ public function testCreateViewFlatLabelAsClosure() $view = $this->factory->createView( $this->list, [$this->obj2, $this->obj3], - function ($object) { - return $object->label; - } + fn ($object) => $object->label ); $this->assertFlatView($view); @@ -454,9 +434,7 @@ public function testCreateViewFlatLabelClosureReceivesKey() $view = $this->factory->createView( $this->list, [$this->obj2, $this->obj3], - function ($object, $key) { - return $key; - } + fn ($object, $key) => $key ); $this->assertFlatView($view); @@ -498,9 +476,7 @@ public function testCreateViewFlatIndexAsClosure() $this->list, [$this->obj2, $this->obj3], null, // label - function ($object) { - return $object->index; - } + fn ($object) => $object->index ); $this->assertFlatViewWithCustomIndices($view); @@ -622,9 +598,7 @@ public function testCreateViewFlatGroupByAsClosure() [$this->obj2, $this->obj3], null, // label null, // index - function ($object) use ($obj1, $obj2) { - return $obj1 === $object || $obj2 === $object ? 'Group 1' : 'Group 2'; - } + fn ($object) => $obj1 === $object || $obj2 === $object ? 'Group 1' : 'Group 2' ); $this->assertGroupedView($view); @@ -637,9 +611,7 @@ public function testCreateViewFlatGroupByClosureReceivesKey() [$this->obj2, $this->obj3], null, // label null, // index - function ($object, $key) { - return 'A' === $key || 'B' === $key ? 'Group 1' : 'Group 2'; - } + fn ($object, $key) => 'A' === $key || 'B' === $key ? 'Group 1' : 'Group 2' ); $this->assertGroupedView($view); @@ -652,9 +624,7 @@ public function testCreateViewFlatGroupByClosureReceivesValue() [$this->obj2, $this->obj3], null, // label null, // index - function ($object, $key, $value) { - return '0' === $value || '1' === $value ? 'Group 1' : 'Group 2'; - } + fn ($object, $key, $value) => '0' === $value || '1' === $value ? 'Group 1' : 'Group 2' ); $this->assertGroupedView($view); @@ -713,9 +683,7 @@ public function testCreateViewFlatAttrAsClosure() null, // label null, // index null, // group - function ($object) { - return $object->attr; - } + fn ($object) => $object->attr ); $this->assertFlatViewWithAttr($view); @@ -729,12 +697,10 @@ public function testCreateViewFlatAttrClosureReceivesKey() null, // label null, // index null, // group - function ($object, $key) { - return match ($key) { - 'B' => ['attr1' => 'value1'], - 'C' => ['attr2' => 'value2'], - default => [], - }; + fn ($object, $key) => match ($key) { + 'B' => ['attr1' => 'value1'], + 'C' => ['attr2' => 'value2'], + default => [], } ); @@ -749,12 +715,10 @@ public function testCreateViewFlatAttrClosureReceivesValue() null, // label null, // index null, // group - function ($object, $key, $value) { - return match ($value) { - '1' => ['attr1' => 'value1'], - '2' => ['attr2' => 'value2'], - default => [], - }; + fn ($object, $key, $value) => match ($value) { + '1' => ['attr1' => 'value1'], + '2' => ['attr2' => 'value2'], + default => [], } ); @@ -766,9 +730,7 @@ public function testPassTranslatableMessageAsLabelDoesntCastItToString() $view = $this->factory->createView( $this->list, [$this->obj1], - static function ($choice, $key, $value) { - return new TranslatableMessage('my_message', ['param1' => 'value1']); - } + static fn ($choice, $key, $value) => new TranslatableMessage('my_message', ['param1' => 'value1']) ); $this->assertInstanceOf(TranslatableMessage::class, $view->choices[0]->label); @@ -788,9 +750,7 @@ public function trans(TranslatorInterface $translator, string $locale = null): s $view = $this->factory->createView( $this->list, [$this->obj1], - static function () use ($message) { - return $message; - } + static fn () => $message ); $this->assertSame($message, $view->choices[0]->label); @@ -852,9 +812,7 @@ public function testCreateViewFlatlabelTranslationParametersAsClosure() null, // index null, // group null, // attr - function ($object) { - return $object->labelTranslationParameters; - } + fn ($object) => $object->labelTranslationParameters ); $this->assertFlatViewWithlabelTranslationParameters($view); @@ -869,11 +827,9 @@ public function testCreateViewFlatlabelTranslationParametersClosureReceivesKey() null, // index null, // group null, // attr - function ($object, $key) { - return match ($key) { - 'D' => ['%placeholder1%' => 'value1'], - default => [], - }; + fn ($object, $key) => match ($key) { + 'D' => ['%placeholder1%' => 'value1'], + default => [], } ); @@ -889,11 +845,9 @@ public function testCreateViewFlatlabelTranslationParametersClosureReceivesValue null, // index null, // group null, // attr - function ($object, $key, $value) { - return match ($value) { - '3' => ['%placeholder1%' => 'value1'], - default => [], - }; + fn ($object, $key, $value) => match ($value) { + '3' => ['%placeholder1%' => 'value1'], + default => [], } ); diff --git a/Tests/ChoiceList/LazyChoiceListTest.php b/Tests/ChoiceList/LazyChoiceListTest.php index 94d41cf9e7..501f4377ad 100644 --- a/Tests/ChoiceList/LazyChoiceListTest.php +++ b/Tests/ChoiceList/LazyChoiceListTest.php @@ -108,9 +108,7 @@ public function testGetChoicesForValuesUsesLoadedList() 'b' => 'bar', 'c' => 'baz', ]; - $list = new LazyChoiceList(new ArrayChoiceLoader($choices), function ($choice) use ($choices) { - return array_search($choice, $choices); - }); + $list = new LazyChoiceList(new ArrayChoiceLoader($choices), fn ($choice) => array_search($choice, $choices)); // load choice list $list->getChoices(); @@ -126,9 +124,7 @@ public function testGetValuesForChoicesUsesLoadedList() 'b' => 'bar', 'c' => 'baz', ]; - $list = new LazyChoiceList(new ArrayChoiceLoader($choices), function ($choice) use ($choices) { - return array_search($choice, $choices); - }); + $list = new LazyChoiceList(new ArrayChoiceLoader($choices), fn ($choice) => array_search($choice, $choices)); // load choice list $list->getChoices(); diff --git a/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php b/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php index 69eb787a23..e3e813b377 100644 --- a/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php +++ b/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php @@ -48,12 +48,8 @@ class CallbackChoiceLoaderTest extends TestCase public static function setUpBeforeClass(): void { - self::$loader = new CallbackChoiceLoader(function () { - return self::$choices; - }); - self::$value = function ($choice) { - return $choice->value ?? null; - }; + self::$loader = new CallbackChoiceLoader(fn () => self::$choices); + self::$value = fn ($choice) => $choice->value ?? null; self::$choices = [ (object) ['value' => 'choice_one'], (object) ['value' => 'choice_two'], diff --git a/Tests/ChoiceList/Loader/FilterChoiceLoaderDecoratorTest.php b/Tests/ChoiceList/Loader/FilterChoiceLoaderDecoratorTest.php index 1f91a47275..5a41e5aff3 100644 --- a/Tests/ChoiceList/Loader/FilterChoiceLoaderDecoratorTest.php +++ b/Tests/ChoiceList/Loader/FilterChoiceLoaderDecoratorTest.php @@ -20,9 +20,7 @@ class FilterChoiceLoaderDecoratorTest extends TestCase { public function testLoadChoiceList() { - $filter = function ($choice) { - return 0 === $choice % 2; - }; + $filter = fn ($choice) => 0 === $choice % 2; $loader = new FilterChoiceLoaderDecorator(new ArrayChoiceLoader(range(1, 4)), $filter); @@ -31,9 +29,7 @@ public function testLoadChoiceList() public function testLoadChoiceListWithGroupedChoices() { - $filter = function ($choice) { - return $choice < 9 && 0 === $choice % 2; - }; + $filter = fn ($choice) => $choice < 9 && 0 === $choice % 2; $loader = new FilterChoiceLoaderDecorator(new ArrayChoiceLoader(['units' => range(1, 9), 'tens' => range(10, 90, 10)]), $filter); @@ -49,9 +45,7 @@ public function testLoadChoiceListWithGroupedChoices() public function testLoadChoiceListMixedWithGroupedAndNonGroupedChoices() { - $filter = function ($choice) { - return 0 === $choice % 2; - }; + $filter = fn ($choice) => 0 === $choice % 2; $choices = array_merge(range(1, 9), ['grouped' => range(10, 40, 5)]); $loader = new FilterChoiceLoaderDecorator(new ArrayChoiceLoader($choices), $filter); @@ -74,9 +68,7 @@ public function testLoadValuesForChoices() { $evenValues = [1 => '2', 3 => '4']; - $filter = function ($choice) { - return 0 === $choice % 2; - }; + $filter = fn ($choice) => 0 === $choice % 2; $loader = new FilterChoiceLoaderDecorator(new ArrayChoiceLoader([range(1, 4)]), $filter); @@ -88,9 +80,7 @@ public function testLoadChoicesForValues() $evenChoices = [1 => 2, 3 => 4]; $values = array_map('strval', range(1, 4)); - $filter = function ($choice) { - return 0 === $choice % 2; - }; + $filter = fn ($choice) => 0 === $choice % 2; $loader = new FilterChoiceLoaderDecorator(new ArrayChoiceLoader(range(1, 4)), $filter); diff --git a/Tests/ChoiceList/Loader/IntlCallbackChoiceLoaderTest.php b/Tests/ChoiceList/Loader/IntlCallbackChoiceLoaderTest.php index e2827b0d91..0aed92fb5e 100644 --- a/Tests/ChoiceList/Loader/IntlCallbackChoiceLoaderTest.php +++ b/Tests/ChoiceList/Loader/IntlCallbackChoiceLoaderTest.php @@ -49,12 +49,8 @@ class IntlCallbackChoiceLoaderTest extends TestCase public static function setUpBeforeClass(): void { - self::$loader = new IntlCallbackChoiceLoader(function () { - return self::$choices; - }); - self::$value = function ($choice) { - return $choice->value ?? null; - }; + self::$loader = new IntlCallbackChoiceLoader(fn () => self::$choices); + self::$value = fn ($choice) => $choice->value ?? null; self::$choices = [ (object) ['value' => 'choice_one'], (object) ['value' => 'choice_two'], diff --git a/Tests/Command/DebugCommandTest.php b/Tests/Command/DebugCommandTest.php index f8ce76316f..9e3847d9ac 100644 --- a/Tests/Command/DebugCommandTest.php +++ b/Tests/Command/DebugCommandTest.php @@ -263,7 +263,7 @@ private static function getCoreTypes(): array $coreExtension = new CoreExtension(); $loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes'); $coreTypes = $loadTypesRefMethod->invoke($coreExtension); - $coreTypes = array_map(function (FormTypeInterface $type) { return $type::class; }, $coreTypes); + $coreTypes = array_map(fn (FormTypeInterface $type) => $type::class, $coreTypes); sort($coreTypes); return $coreTypes; @@ -290,15 +290,11 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setDefault('empty_data', function (Options $options) { $foo = $options['foo']; - return function (FormInterface $form) use ($foo) { - return $form->getConfig()->getCompound() ? [$foo] : $foo; - }; + return fn (FormInterface $form) => $form->getConfig()->getCompound() ? [$foo] : $foo; }); $resolver->setAllowedTypes('foo', 'string'); $resolver->setAllowedValues('foo', ['bar', 'baz']); - $resolver->setNormalizer('foo', function (Options $options, $value) { - return (string) $value; - }); + $resolver->setNormalizer('foo', fn (Options $options, $value) => (string) $value); $resolver->setInfo('foo', 'Info'); } } diff --git a/Tests/CompoundFormTest.php b/Tests/CompoundFormTest.php index 833dcc7616..52efb607b2 100644 --- a/Tests/CompoundFormTest.php +++ b/Tests/CompoundFormTest.php @@ -955,10 +955,8 @@ public function testCreateViewWithChildren() $this->form->add($field1); $this->form->add($field2); - $assertChildViewsEqual = function (array $childViews) { - return function (FormView $view) use ($childViews) { - $this->assertSame($childViews, $view->children); - }; + $assertChildViewsEqual = fn (array $childViews) => function (FormView $view) use ($childViews) { + $this->assertSame($childViews, $view->children); }; // First create the view diff --git a/Tests/Console/Descriptor/AbstractDescriptorTest.php b/Tests/Console/Descriptor/AbstractDescriptorTest.php index bc870494e6..1553292941 100644 --- a/Tests/Console/Descriptor/AbstractDescriptorTest.php +++ b/Tests/Console/Descriptor/AbstractDescriptorTest.php @@ -167,14 +167,10 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setDefault('empty_data', function (Options $options, $value) { $foo = $options['foo']; - return function (FormInterface $form) use ($foo) { - return $form->getConfig()->getCompound() ? [$foo] : $foo; - }; + return fn (FormInterface $form) => $form->getConfig()->getCompound() ? [$foo] : $foo; }); $resolver->setAllowedTypes('foo', 'string'); $resolver->setAllowedValues('foo', ['bar', 'baz']); - $resolver->setNormalizer('foo', function (Options $options, $value) { - return (string) $value; - }); + $resolver->setNormalizer('foo', fn (Options $options, $value) => (string) $value); } } diff --git a/Tests/Extension/Core/DataMapper/DataMapperTest.php b/Tests/Extension/Core/DataMapper/DataMapperTest.php index b39572ed80..a125078fd6 100644 --- a/Tests/Extension/Core/DataMapper/DataMapperTest.php +++ b/Tests/Extension/Core/DataMapper/DataMapperTest.php @@ -359,9 +359,7 @@ public function testMapDataToFormsUsingGetCallbackOption() $person = new DummyPerson($initialName); $config = new FormConfigBuilder('name', null, $this->dispatcher, [ - 'getter' => static function (DummyPerson $person) { - return $person->myName(); - }, + 'getter' => static fn (DummyPerson $person) => $person->myName(), ]); $form = new Form($config); diff --git a/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php b/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php index 9bcb22efe0..d42d4d8899 100644 --- a/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php +++ b/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php @@ -285,9 +285,7 @@ public function testOnSubmitDeleteEmptyCompoundEntriesIfAllowDelete() $this->form->get($child)->submit($dat); } $event = new FormEvent($this->form, $data); - $callback = function ($data) { - return null === $data['name']; - }; + $callback = fn ($data) => null === $data['name']; $listener = new ResizeFormListener('text', [], false, true, $callback); $listener->onSubmit($event); diff --git a/Tests/Extension/Core/Type/CheckboxTypeTest.php b/Tests/Extension/Core/Type/CheckboxTypeTest.php index 93ca921b7c..95ef611b1c 100644 --- a/Tests/Extension/Core/Type/CheckboxTypeTest.php +++ b/Tests/Extension/Core/Type/CheckboxTypeTest.php @@ -146,12 +146,8 @@ public function testCustomModelTransformer($data, $checked) { // present a binary status field as a checkbox $transformer = new CallbackTransformer( - function ($value) { - return 'checked' == $value; - }, - function ($value) { - return $value ? 'checked' : 'unchecked'; - } + fn ($value) => 'checked' == $value, + fn ($value) => $value ? 'checked' : 'unchecked' ); $form = $this->factory->createBuilder(static::TESTED_TYPE) diff --git a/Tests/Extension/Core/Type/ChoiceTypeTest.php b/Tests/Extension/Core/Type/ChoiceTypeTest.php index 8109a9c600..8bf3dc2359 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -531,9 +531,7 @@ public function testSubmitSingleNonExpandedEmptyExplicitEmptyChoice() 'choices' => [ 'Empty' => 'EMPTY_CHOICE', ], - 'choice_value' => function () { - return ''; - }, + 'choice_value' => fn () => '', ]); $form->submit(''); @@ -2208,9 +2206,7 @@ public function testFilteredChoices() { $form = $this->factory->create(static::TESTED_TYPE, null, [ 'choices' => $this->choices, - 'choice_filter' => function ($choice) { - return \in_array($choice, range('a', 'c'), true); - }, + 'choice_filter' => fn ($choice) => \in_array($choice, range('a', 'c'), true), ]); $this->assertEquals([ @@ -2224,9 +2220,7 @@ public function testFilteredGroupedChoices() { $form = $this->factory->create(static::TESTED_TYPE, null, [ 'choices' => $this->groupedChoices, - 'choice_filter' => function ($choice) { - return \in_array($choice, range('a', 'c'), true); - }, + 'choice_filter' => fn ($choice) => \in_array($choice, range('a', 'c'), true), ]); $this->assertEquals(['Symfony' => new ChoiceGroupView('Symfony', [ @@ -2239,12 +2233,8 @@ public function testFilteredGroupedChoices() public function testFilteredChoiceLoader() { $form = $this->factory->create(static::TESTED_TYPE, null, [ - 'choice_loader' => new CallbackChoiceLoader(function () { - return $this->choices; - }), - 'choice_filter' => function ($choice) { - return \in_array($choice, range('a', 'c'), true); - }, + 'choice_loader' => new CallbackChoiceLoader(fn () => $this->choices), + 'choice_filter' => fn ($choice) => \in_array($choice, range('a', 'c'), true), ]); $this->assertEquals([ @@ -2256,9 +2246,7 @@ public function testFilteredChoiceLoader() public function testWithSameLoaderAndDifferentChoiceValueCallbacks() { - $choiceLoader = new CallbackChoiceLoader(function () { - return [1, 2, 3]; - }); + $choiceLoader = new CallbackChoiceLoader(fn () => [1, 2, 3]); $view = $this->factory->create(FormTypeTest::TESTED_TYPE) ->add('choice_one', self::TESTED_TYPE, [ @@ -2266,9 +2254,7 @@ public function testWithSameLoaderAndDifferentChoiceValueCallbacks() ]) ->add('choice_two', self::TESTED_TYPE, [ 'choice_loader' => $choiceLoader, - 'choice_value' => function ($choice) { - return $choice ? (string) $choice * 10 : ''; - }, + 'choice_value' => fn ($choice) => $choice ? (string) $choice * 10 : '', ]) ->createView() ; diff --git a/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php b/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php index 9e14410059..490e84604a 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php @@ -31,9 +31,7 @@ protected function getExtensions() { $translator = $this->createMock(TranslatorInterface::class); $translator->expects($this->any())->method('trans') - ->willReturnCallback(function ($key, $params) { - return strtr(sprintf('Translation of: %s', $key), $params); - } + ->willReturnCallback(fn ($key, $params) => strtr(sprintf('Translation of: %s', $key), $params) ); return array_merge(parent::getExtensions(), [new CoreExtension(null, null, $translator)]); diff --git a/Tests/Extension/Core/Type/CollectionTypeTest.php b/Tests/Extension/Core/Type/CollectionTypeTest.php index 129c2c97b9..9df4eede1e 100644 --- a/Tests/Extension/Core/Type/CollectionTypeTest.php +++ b/Tests/Extension/Core/Type/CollectionTypeTest.php @@ -120,9 +120,7 @@ public function testResizedDownWithDeleteEmptyCallable() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'entry_type' => AuthorType::class, 'allow_delete' => true, - 'delete_empty' => function (Author $obj = null) { - return null === $obj || empty($obj->firstName); - }, + 'delete_empty' => fn (Author $obj = null) => null === $obj || empty($obj->firstName), ]); $form->setData([new Author('Bob'), new Author('Alice')]); @@ -143,9 +141,7 @@ public function testResizedDownIfSubmittedWithCompoundEmptyDataDeleteEmptyAndNoD 'entry_options' => ['data_class' => null], 'allow_add' => true, 'allow_delete' => true, - 'delete_empty' => function ($author) { - return empty($author['firstName']); - }, + 'delete_empty' => fn ($author) => empty($author['firstName']), ]); $form->setData([['firstName' => 'first', 'lastName' => 'last']]); $form->submit([ diff --git a/Tests/Extension/Core/Type/DateTimeTypeTest.php b/Tests/Extension/Core/Type/DateTimeTypeTest.php index 71edd6afc7..12b6939a68 100644 --- a/Tests/Extension/Core/Type/DateTimeTypeTest.php +++ b/Tests/Extension/Core/Type/DateTimeTypeTest.php @@ -709,9 +709,7 @@ public function testSubmitNullUsesDateEmptyData($widget, $emptyData, $expectedDa public function provideEmptyData() { $expectedData = \DateTime::createFromFormat('Y-m-d H:i', '2018-11-11 21:23'); - $lazyEmptyData = static function (FormInterface $form) { - return $form->getConfig()->getCompound() ? ['date' => ['year' => '2018', 'month' => '11', 'day' => '11'], 'time' => ['hour' => '21', 'minute' => '23']] : '2018-11-11T21:23:00'; - }; + $lazyEmptyData = static fn (FormInterface $form) => $form->getConfig()->getCompound() ? ['date' => ['year' => '2018', 'month' => '11', 'day' => '11'], 'time' => ['hour' => '21', 'minute' => '23']] : '2018-11-11T21:23:00'; return [ 'Simple field' => ['single_text', '2018-11-11T21:23:00', $expectedData], diff --git a/Tests/Extension/Core/Type/DateTypeTest.php b/Tests/Extension/Core/Type/DateTypeTest.php index 74e0a8d355..62a12289cb 100644 --- a/Tests/Extension/Core/Type/DateTypeTest.php +++ b/Tests/Extension/Core/Type/DateTypeTest.php @@ -1057,9 +1057,7 @@ public function testSubmitNullUsesDateEmptyData($widget, $emptyData, $expectedDa public function provideEmptyData() { $expectedData = \DateTime::createFromFormat('Y-m-d H:i:s', '2018-11-11 00:00:00'); - $lazyEmptyData = static function (FormInterface $form) { - return $form->getConfig()->getCompound() ? ['year' => '2018', 'month' => '11', 'day' => '11'] : '2018-11-11'; - }; + $lazyEmptyData = static fn (FormInterface $form) => $form->getConfig()->getCompound() ? ['year' => '2018', 'month' => '11', 'day' => '11'] : '2018-11-11'; return [ 'Simple field' => ['single_text', '2018-11-11', $expectedData], diff --git a/Tests/Extension/Core/Type/FormTypeTest.php b/Tests/Extension/Core/Type/FormTypeTest.php index 3701b653f8..b4bca15130 100644 --- a/Tests/Extension/Core/Type/FormTypeTest.php +++ b/Tests/Extension/Core/Type/FormTypeTest.php @@ -439,9 +439,8 @@ public function testSubformCallsSettersIfReferenceIsScalar() $builder->add('referenceCopy', static::TESTED_TYPE); $builder->get('referenceCopy')->addViewTransformer(new CallbackTransformer( function () {}, - function ($value) { // reverseTransform - return 'foobar'; - } + fn ($value) => // reverseTransform +'foobar' )); $form = $builder->getForm(); @@ -464,9 +463,8 @@ public function testSubformAlwaysInsertsIntoArrays() $builder->add('referenceCopy', static::TESTED_TYPE); $builder->get('referenceCopy')->addViewTransformer(new CallbackTransformer( function () {}, - function ($value) use ($ref2) { // reverseTransform - return $ref2; - } + fn ($value) => // reverseTransform +$ref2 )); $form = $builder->getForm(); diff --git a/Tests/Extension/Core/Type/TimeTypeTest.php b/Tests/Extension/Core/Type/TimeTypeTest.php index 08284dbbf0..991d9c23fe 100644 --- a/Tests/Extension/Core/Type/TimeTypeTest.php +++ b/Tests/Extension/Core/Type/TimeTypeTest.php @@ -1113,9 +1113,7 @@ public function testSubmitNullUsesDateEmptyData($widget, $emptyData, $expectedDa public function provideEmptyData() { $expectedData = \DateTime::createFromFormat('Y-m-d H:i', '1970-01-01 21:23'); - $lazyEmptyData = static function (FormInterface $form) { - return $form->getConfig()->getCompound() ? ['hour' => '21', 'minute' => '23'] : '21:23'; - }; + $lazyEmptyData = static fn (FormInterface $form) => $form->getConfig()->getCompound() ? ['hour' => '21', 'minute' => '23'] : '21:23'; return [ 'Simple field' => ['single_text', '21:23', $expectedData], diff --git a/Tests/Extension/DataCollector/FormDataCollectorTest.php b/Tests/Extension/DataCollector/FormDataCollectorTest.php index 39009b598c..fd9870fa6d 100644 --- a/Tests/Extension/DataCollector/FormDataCollectorTest.php +++ b/Tests/Extension/DataCollector/FormDataCollectorTest.php @@ -335,9 +335,7 @@ public function testSerializeWithFormAddedMultipleTimes() $form1View = new FormView(); $form2View = new FormView(); $child1View = new FormView(); - $child1View->vars['is_selected'] = function ($choice, array $values) { - return \in_array($choice, $values, true); - }; + $child1View->vars['is_selected'] = fn ($choice, array $values) => \in_array($choice, $values, true); $form1->add($child1); $form2->add($child1); diff --git a/Tests/Extension/Validator/Constraints/FormValidatorTest.php b/Tests/Extension/Validator/Constraints/FormValidatorTest.php index c614a1ac18..7d9061c882 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorTest.php @@ -272,7 +272,7 @@ public function testDontValidateIfNotSynchronized() ]) ->setData($object) ->addViewTransformer(new CallbackTransformer( - function ($data) { return $data; }, + fn ($data) => $data, function () { throw new TransformationFailedException(); } )) ->getForm(); @@ -309,7 +309,7 @@ public function testAddInvalidErrorEvenIfNoValidationGroups() ]) ->setData($object) ->addViewTransformer(new CallbackTransformer( - function ($data) { return $data; }, + fn ($data) => $data, function () { throw new TransformationFailedException(); } )) ->getForm(); @@ -344,7 +344,7 @@ public function testDontValidateConstraintsIfNotSynchronized() $form = $this->getBuilder('name', '\stdClass', $options) ->setData($object) ->addViewTransformer(new CallbackTransformer( - function ($data) { return $data; }, + fn ($data) => $data, function () { throw new TransformationFailedException(); } )) ->getForm(); @@ -375,7 +375,7 @@ public function testTransformationFailedExceptionInvalidMessageIsUsed() ]) ->setData($object) ->addViewTransformer(new CallbackTransformer( - function ($data) { return $data; }, + fn ($data) => $data, function () { $failure = new TransformationFailedException(); $failure->setInvalidMessage('safe message to be used', ['{{ bar }}' => 'bar']); @@ -451,9 +451,7 @@ public function testDontExecuteFunctionNames() public function testHandleClosureValidationGroups() { $object = new \stdClass(); - $options = ['validation_groups' => function (FormInterface $form) { - return ['group1', 'group2']; - }]; + $options = ['validation_groups' => fn (FormInterface $form) => ['group1', 'group2']]; $form = $this->getCompoundForm($object, $options); $form->submit([]); @@ -565,9 +563,7 @@ public function testUseInheritedClosureValidationGroup() $object = new \stdClass(); $parentOptions = [ - 'validation_groups' => function () { - return ['group1', 'group2']; - }, + 'validation_groups' => fn () => ['group1', 'group2'], ]; $parent = $this->getBuilder('parent', null, $parentOptions) ->setCompound(true) diff --git a/Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php b/Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php index 34c911f52a..0533883f70 100644 --- a/Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php @@ -26,11 +26,7 @@ public function testPostMaxSizeTranslation() $resolver = new OptionsResolver(); $resolver->setDefault('post_max_size_message', 'old max {{ max }}!'); - $resolver->setDefault('upload_max_size_message', function (Options $options) { - return function () use ($options) { - return $options['post_max_size_message']; - }; - }); + $resolver->setDefault('upload_max_size_message', fn (Options $options) => fn () => $options['post_max_size_message']); $extension->configureOptions($resolver); $options = $resolver->resolve(); diff --git a/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php b/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php index 08b8caaedd..f0a9124c6f 100644 --- a/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php +++ b/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php @@ -91,7 +91,7 @@ protected function getForm($name = 'name', $propertyPath = null, $dataClass = nu if (!$synchronized) { $config->addViewTransformer(new CallbackTransformer( - function ($normData) { return $normData; }, + fn ($normData) => $normData, function () { throw new TransformationFailedException(); } )); } diff --git a/Tests/Fixtures/ArrayChoiceLoader.php b/Tests/Fixtures/ArrayChoiceLoader.php index 7224d0e936..8c5a3a4733 100644 --- a/Tests/Fixtures/ArrayChoiceLoader.php +++ b/Tests/Fixtures/ArrayChoiceLoader.php @@ -8,8 +8,6 @@ class ArrayChoiceLoader extends CallbackChoiceLoader { public function __construct(array $choices = []) { - parent::__construct(static function () use ($choices): array { - return $choices; - }); + parent::__construct(static fn (): array => $choices); } } diff --git a/Tests/Fixtures/ChoiceSubType.php b/Tests/Fixtures/ChoiceSubType.php index d67f0b96ac..7399dfe36b 100644 --- a/Tests/Fixtures/ChoiceSubType.php +++ b/Tests/Fixtures/ChoiceSubType.php @@ -23,12 +23,10 @@ class ChoiceSubType extends AbstractType public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(['expanded' => true]); - $resolver->setNormalizer('choices', function () { - return [ - 'attr1' => 'Attribute 1', - 'attr2' => 'Attribute 2', - ]; - }); + $resolver->setNormalizer('choices', fn () => [ + 'attr1' => 'Attribute 1', + 'attr2' => 'Attribute 2', + ]); } public function getParent(): ?string diff --git a/Tests/Fixtures/LazyChoiceTypeExtension.php b/Tests/Fixtures/LazyChoiceTypeExtension.php index b04eb61721..ccd5b3f489 100644 --- a/Tests/Fixtures/LazyChoiceTypeExtension.php +++ b/Tests/Fixtures/LazyChoiceTypeExtension.php @@ -21,12 +21,10 @@ class LazyChoiceTypeExtension extends AbstractTypeExtension public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefault('choice_loader', ChoiceList::lazy($this, function () { - return [ - 'Lazy A' => 'lazy_a', - 'Lazy B' => 'lazy_b', - ]; - })); + $resolver->setDefault('choice_loader', ChoiceList::lazy($this, fn () => [ + 'Lazy A' => 'lazy_a', + 'Lazy B' => 'lazy_b', + ])); } public static function getExtendedTypes(): iterable diff --git a/Tests/Resources/TranslationFilesTest.php b/Tests/Resources/TranslationFilesTest.php index 1b83bfc3bf..00e6c687c9 100644 --- a/Tests/Resources/TranslationFilesTest.php +++ b/Tests/Resources/TranslationFilesTest.php @@ -46,7 +46,7 @@ public function testTranslationFileIsValidWithoutEntityLoader($filePath) public function provideTranslationFiles() { return array_map( - function ($filePath) { return (array) $filePath; }, + fn ($filePath) => (array) $filePath, glob(\dirname(__DIR__, 2).'/Resources/translations/*.xlf') ); } diff --git a/Tests/SimpleFormTest.php b/Tests/SimpleFormTest.php index 3d8b0b20d8..19ae3b5074 100644 --- a/Tests/SimpleFormTest.php +++ b/Tests/SimpleFormTest.php @@ -1112,12 +1112,12 @@ public function testIsEmptyCallback() { $config = new FormConfigBuilder('foo', null, new EventDispatcher()); - $config->setIsEmptyCallback(function ($modelData): bool { return 'ccc' === $modelData; }); + $config->setIsEmptyCallback(fn ($modelData): bool => 'ccc' === $modelData); $form = new Form($config); $form->setData('ccc'); $this->assertTrue($form->isEmpty()); - $config->setIsEmptyCallback(function (): bool { return false; }); + $config->setIsEmptyCallback(fn (): bool => false); $form = new Form($config); $form->setData(null); $this->assertFalse($form->isEmpty()); From cfb099e0cc059d25a550b751f6aa9dce70eb426e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A1bor=20Egyed?= Date: Thu, 2 Feb 2023 21:20:53 +0100 Subject: [PATCH 078/208] [Form] Fix PasswordHasherListener to work with empty data --- .../EventListener/PasswordHasherListener.php | 58 ++++++++++++------- ...asswordTypePasswordHasherExtensionTest.php | 36 ++++++++++++ 2 files changed, 74 insertions(+), 20 deletions(-) diff --git a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php index c9cf0d4a34..e83a117c92 100644 --- a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php +++ b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php @@ -14,6 +14,7 @@ use Symfony\Component\Form\Exception\InvalidConfigurationException; use Symfony\Component\Form\Extension\Core\Type\RepeatedType; use Symfony\Component\Form\FormEvent; +use Symfony\Component\Form\FormInterface; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; @@ -21,6 +22,7 @@ /** * @author Sébastien Alfaiate + * @author Gábor Egyed */ class PasswordHasherListener { @@ -35,26 +37,11 @@ public function __construct( public function registerPassword(FormEvent $event) { - $form = $event->getForm(); - $parentForm = $form->getParent(); - $mapped = $form->getConfig()->getMapped(); - - if ($parentForm && $parentForm->getConfig()->getType()->getInnerType() instanceof RepeatedType) { - $mapped = $parentForm->getConfig()->getMapped(); - $parentForm = $parentForm->getParent(); - } - - if ($mapped) { - throw new InvalidConfigurationException('The "hash_property_path" option cannot be used on mapped field.'); - } - - if (!($user = $parentForm?->getData()) || !$user instanceof PasswordAuthenticatedUserInterface) { - throw new InvalidConfigurationException(sprintf('The "hash_property_path" option only supports "%s" objects, "%s" given.', PasswordAuthenticatedUserInterface::class, get_debug_type($user))); - } + $this->assertNotMapped($event->getForm()); $this->passwords[] = [ - 'user' => $user, - 'property_path' => $form->getConfig()->getOption('hash_property_path'), + 'form' => $event->getForm(), + 'property_path' => $event->getForm()->getConfig()->getOption('hash_property_path'), 'password' => $event->getData(), ]; } @@ -69,14 +56,45 @@ public function hashPasswords(FormEvent $event) if ($form->isValid()) { foreach ($this->passwords as $password) { + $user = $this->getUser($password['form']); + $this->propertyAccessor->setValue( - $password['user'], + $user, $password['property_path'], - $this->passwordHasher->hashPassword($password['user'], $password['password']) + $this->passwordHasher->hashPassword($user, $password['password']) ); } } $this->passwords = []; } + + private function getTargetForm(FormInterface $form): FormInterface + { + $parent = $form->getParent(); + + if ($parent && $parent->getConfig()->getType()->getInnerType() instanceof RepeatedType) { + return $parent; + } + + return $form; + } + + private function getUser(FormInterface $form): PasswordAuthenticatedUserInterface + { + $parent = $this->getTargetForm($form)->getParent(); + + if (!($user = $parent?->getData()) || !$user instanceof PasswordAuthenticatedUserInterface) { + throw new InvalidConfigurationException(sprintf('The "hash_property_path" option only supports "%s" objects, "%s" given.', PasswordAuthenticatedUserInterface::class, get_debug_type($user))); + } + + return $user; + } + + private function assertNotMapped(FormInterface $form): void + { + if ($this->getTargetForm($form)->getConfig()->getMapped()) { + throw new InvalidConfigurationException('The "hash_property_path" option cannot be used on mapped field.'); + } + } } diff --git a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php index 75b2f99257..a3a4d225f8 100644 --- a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php +++ b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php @@ -77,6 +77,42 @@ public function testPasswordHashSuccess() $this->assertSame($user->getPassword(), $hashedPassword); } + public function testPasswordHashSuccessWitnEmptyData() + { + $user = new User(); + + $plainPassword = 'PlainPassword'; + $hashedPassword = 'HashedPassword'; + + $this->passwordHasher + ->expects($this->once()) + ->method('hashPassword') + ->with($user, $plainPassword) + ->willReturn($hashedPassword) + ; + + $this->assertNull($user->getPassword()); + + $form = $this->factory + ->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ + 'data_class' => User::class, + 'empty_data' => function () use ($user) { + return $user; + }, + ]) + ->add('plainPassword', 'Symfony\Component\Form\Extension\Core\Type\PasswordType', [ + 'hash_property_path' => 'password', + 'mapped' => false, + ]) + ->getForm() + ; + + $form->submit(['plainPassword' => $plainPassword]); + + $this->assertTrue($form->isValid()); + $this->assertSame($user->getPassword(), $hashedPassword); + } + public function testPasswordHashOnInvalidForm() { $user = new User(); From 119c314bb6f342cd68b40afbd81f49739aaa9cac Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Sun, 5 Feb 2023 10:22:16 +0100 Subject: [PATCH 079/208] fix typo --- .../Type/PasswordTypePasswordHasherExtensionTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php index a3a4d225f8..a55843861c 100644 --- a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php +++ b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php @@ -77,7 +77,7 @@ public function testPasswordHashSuccess() $this->assertSame($user->getPassword(), $hashedPassword); } - public function testPasswordHashSuccessWitnEmptyData() + public function testPasswordHashSuccessWithEmptyData() { $user = new User(); From e155b8d6a28887b21323cd927faf44a5932b9dc7 Mon Sep 17 00:00:00 2001 From: Mathieu Date: Mon, 6 Feb 2023 17:09:41 +0100 Subject: [PATCH 080/208] [Form] Check for `RepeatedType` child in `PasswordHasherListener` --- .../EventListener/PasswordHasherListener.php | 14 ++++-- ...asswordTypePasswordHasherExtensionTest.php | 50 +++++++++++++++++++ Tests/Fixtures/RepeatedPasswordField.php | 36 +++++++++++++ 3 files changed, 96 insertions(+), 4 deletions(-) create mode 100644 Tests/Fixtures/RepeatedPasswordField.php diff --git a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php index e83a117c92..3fccfd8965 100644 --- a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php +++ b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php @@ -71,12 +71,18 @@ public function hashPasswords(FormEvent $event) private function getTargetForm(FormInterface $form): FormInterface { - $parent = $form->getParent(); - - if ($parent && $parent->getConfig()->getType()->getInnerType() instanceof RepeatedType) { - return $parent; + if (!$parentForm = $form->getParent()) { + return $form; } + $parentType = $parentForm->getConfig()->getType(); + + do { + if ($parentType->getInnerType() instanceof RepeatedType) { + return $parentForm; + } + } while ($parentType = $parentType->getParent()); + return $form; } diff --git a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php index a55843861c..895a39c41b 100644 --- a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php +++ b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php @@ -13,9 +13,12 @@ use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Form\Exception\InvalidConfigurationException; +use Symfony\Component\Form\Extension\Core\Type\PasswordType; +use Symfony\Component\Form\Extension\Core\Type\RepeatedType; use Symfony\Component\Form\Extension\PasswordHasher\EventListener\PasswordHasherListener; use Symfony\Component\Form\Extension\PasswordHasher\PasswordHasherExtension; use Symfony\Component\Form\Test\TypeTestCase; +use Symfony\Component\Form\Tests\Fixtures\RepeatedPasswordField; use Symfony\Component\Form\Tests\Fixtures\User; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; @@ -113,6 +116,53 @@ public function testPasswordHashSuccessWithEmptyData() $this->assertSame($user->getPassword(), $hashedPassword); } + /** + * @dataProvider provideRepeatedPasswordField + */ + public function testRepeatedPasswordField(string $type, array $options = []) + { + $user = new User(); + + $plainPassword = 'PlainPassword'; + $hashedPassword = 'HashedPassword'; + + $this->passwordHasher + ->expects($this->once()) + ->method('hashPassword') + ->with($user, $plainPassword) + ->willReturn($hashedPassword) + ; + + $this->assertNull($user->getPassword()); + + $form = $this->factory + ->createBuilder(data: $user) + ->add('plainPassword', $type, $options) + ->getForm() + ; + + $form->submit(['plainPassword' => ['first' => $plainPassword, 'second' => $plainPassword]]); + + $this->assertTrue($form->isValid()); + $this->assertSame($user->getPassword(), $hashedPassword); + } + + public static function provideRepeatedPasswordField(): iterable + { + yield 'RepeatedType' => [ + RepeatedType::class, + [ + 'type' => PasswordType::class, + 'first_options' => [ + 'hash_property_path' => 'password', + ], + 'mapped' => false, + ], + ]; + + yield 'RepeatedType child' => [RepeatedPasswordField::class]; + } + public function testPasswordHashOnInvalidForm() { $user = new User(); diff --git a/Tests/Fixtures/RepeatedPasswordField.php b/Tests/Fixtures/RepeatedPasswordField.php new file mode 100644 index 0000000000..605c81c4c7 --- /dev/null +++ b/Tests/Fixtures/RepeatedPasswordField.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Tests\Fixtures; + +use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\Extension\Core\Type\PasswordType; +use Symfony\Component\Form\Extension\Core\Type\RepeatedType; +use Symfony\Component\OptionsResolver\OptionsResolver; + +class RepeatedPasswordField extends AbstractType +{ + public function getParent(): ?string + { + return RepeatedType::class; + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([ + 'mapped' => false, + 'type' => PasswordType::class, + 'first_options' => [ + 'hash_property_path' => 'password', + ], + ]); + } +} From 73db41ca740200787acd4cfce11680aa6a41a6bb Mon Sep 17 00:00:00 2001 From: Oskar Stark Date: Mon, 6 Feb 2023 06:06:48 +0100 Subject: [PATCH 081/208] [PHPUnit 10] Use `TestCase` suffix for abstract tests in `/Tests/` --- ...bstractDivLayoutTest.php => AbstractDivLayoutTestCase.php} | 2 +- Tests/{AbstractLayoutTest.php => AbstractLayoutTestCase.php} | 2 +- ...uestHandlerTest.php => AbstractRequestHandlerTestCase.php} | 2 +- ...actTableLayoutTest.php => AbstractTableLayoutTestCase.php} | 2 +- ...tractChoiceListTest.php => AbstractChoiceListTestCase.php} | 2 +- Tests/ChoiceList/ArrayChoiceListTest.php | 2 +- ...tractDescriptorTest.php => AbstractDescriptorTestCase.php} | 2 +- Tests/Console/Descriptor/JsonDescriptorTest.php | 2 +- Tests/Console/Descriptor/TextDescriptorTest.php | 2 +- ...ransformerTest.php => BaseDateTimeTransformerTestCase.php} | 2 +- .../Core/DataTransformer/DateTimeToArrayTransformerTest.php | 2 +- .../DateTimeToHtml5LocalDateTimeTransformerTest.php | 2 +- .../DateTimeToLocalizedStringTransformerTest.php | 2 +- .../Core/DataTransformer/DateTimeToRfc3339TransformerTest.php | 2 +- .../Core/DataTransformer/DateTimeToStringTransformerTest.php | 2 +- .../DataTransformer/DateTimeToTimestampTransformerTest.php | 2 +- .../EventListener/MergeCollectionListenerArrayObjectTest.php | 2 +- .../Core/EventListener/MergeCollectionListenerArrayTest.php | 2 +- .../MergeCollectionListenerCustomArrayObjectTest.php | 2 +- ...onListenerTest.php => MergeCollectionListenerTestCase.php} | 2 +- .../Core/Type/{BaseTypeTest.php => BaseTypeTestCase.php} | 2 +- Tests/Extension/Core/Type/ButtonTypeTest.php | 2 +- Tests/Extension/Core/Type/CheckboxTypeTest.php | 2 +- Tests/Extension/Core/Type/ChoiceTypeTest.php | 2 +- Tests/Extension/Core/Type/CollectionTypeTest.php | 2 +- Tests/Extension/Core/Type/ColorTypeTest.php | 2 +- Tests/Extension/Core/Type/CountryTypeTest.php | 2 +- Tests/Extension/Core/Type/CurrencyTypeTest.php | 2 +- Tests/Extension/Core/Type/DateIntervalTypeTest.php | 2 +- Tests/Extension/Core/Type/DateTimeTypeTest.php | 2 +- Tests/Extension/Core/Type/DateTypeTest.php | 2 +- Tests/Extension/Core/Type/EnumTypeTest.php | 4 ++-- Tests/Extension/Core/Type/FileTypeTest.php | 2 +- Tests/Extension/Core/Type/FormTypeTest.php | 2 +- Tests/Extension/Core/Type/IntegerTypeTest.php | 2 +- Tests/Extension/Core/Type/LanguageTypeTest.php | 2 +- Tests/Extension/Core/Type/LocaleTypeTest.php | 2 +- Tests/Extension/Core/Type/MoneyTypeTest.php | 2 +- Tests/Extension/Core/Type/NumberTypeTest.php | 2 +- Tests/Extension/Core/Type/PasswordTypeTest.php | 2 +- Tests/Extension/Core/Type/RepeatedTypeTest.php | 2 +- Tests/Extension/Core/Type/TextTypeTest.php | 2 +- Tests/Extension/Core/Type/TimeTypeTest.php | 2 +- Tests/Extension/Core/Type/TimezoneTypeTest.php | 2 +- Tests/Extension/Core/Type/UlidTypeTest.php | 2 +- Tests/Extension/Core/Type/UuidTypeTest.php | 2 +- Tests/Extension/Core/Type/WeekTypeTest.php | 2 +- .../HttpFoundation/HttpFoundationRequestHandlerTest.php | 4 ++-- ...orExtensionTest.php => BaseValidatorExtensionTestCase.php} | 2 +- .../Validator/Type/BirthdayTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/CheckboxTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/ChoiceTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/CollectionTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/ColorTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/CountryTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/CurrencyTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/DateIntervalTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/DateTimeTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/DateTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/EmailTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/FileTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/FormTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/HiddenTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/IntegerTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/LanguageTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/LocaleTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/MoneyTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/NumberTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/PasswordTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/PercentTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/RadioTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/RangeTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/RepeatedTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/SearchTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/SubmitTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/TelTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/TimeTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/TimezoneTypeValidatorExtensionTest.php | 2 +- .../Validator/Type/UrlTypeValidatorExtensionTest.php | 2 +- .../Descriptor/overridden_option_with_default_closures.txt | 2 +- Tests/NativeRequestHandlerTest.php | 2 +- composer.json | 4 ++-- 82 files changed, 85 insertions(+), 85 deletions(-) rename Tests/{AbstractDivLayoutTest.php => AbstractDivLayoutTestCase.php} (99%) rename Tests/{AbstractLayoutTest.php => AbstractLayoutTestCase.php} (99%) rename Tests/{AbstractRequestHandlerTest.php => AbstractRequestHandlerTestCase.php} (99%) rename Tests/{AbstractTableLayoutTest.php => AbstractTableLayoutTestCase.php} (99%) rename Tests/ChoiceList/{AbstractChoiceListTest.php => AbstractChoiceListTestCase.php} (98%) rename Tests/Console/Descriptor/{AbstractDescriptorTest.php => AbstractDescriptorTestCase.php} (99%) rename Tests/Extension/Core/DataTransformer/{BaseDateTimeTransformerTest.php => BaseDateTimeTransformerTestCase.php} (95%) rename Tests/Extension/Core/EventListener/{MergeCollectionListenerTest.php => MergeCollectionListenerTestCase.php} (99%) rename Tests/Extension/Core/Type/{BaseTypeTest.php => BaseTypeTestCase.php} (99%) rename Tests/Extension/Validator/Type/{BaseValidatorExtensionTest.php => BaseValidatorExtensionTestCase.php} (97%) diff --git a/Tests/AbstractDivLayoutTest.php b/Tests/AbstractDivLayoutTestCase.php similarity index 99% rename from Tests/AbstractDivLayoutTest.php rename to Tests/AbstractDivLayoutTestCase.php index 23b90ebf76..32468895d9 100644 --- a/Tests/AbstractDivLayoutTest.php +++ b/Tests/AbstractDivLayoutTestCase.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\FormError; use Symfony\Component\Security\Csrf\CsrfToken; -abstract class AbstractDivLayoutTest extends AbstractLayoutTest +abstract class AbstractDivLayoutTestCase extends AbstractLayoutTestCase { public function testRow() { diff --git a/Tests/AbstractLayoutTest.php b/Tests/AbstractLayoutTestCase.php similarity index 99% rename from Tests/AbstractLayoutTest.php rename to Tests/AbstractLayoutTestCase.php index 58e853e111..f1ca19a2d4 100644 --- a/Tests/AbstractLayoutTest.php +++ b/Tests/AbstractLayoutTestCase.php @@ -23,7 +23,7 @@ use Symfony\Contracts\Translation\TranslatableInterface; use Symfony\Contracts\Translation\TranslatorInterface; -abstract class AbstractLayoutTest extends FormIntegrationTestCase +abstract class AbstractLayoutTestCase extends FormIntegrationTestCase { use VersionAwareTest; diff --git a/Tests/AbstractRequestHandlerTest.php b/Tests/AbstractRequestHandlerTestCase.php similarity index 99% rename from Tests/AbstractRequestHandlerTest.php rename to Tests/AbstractRequestHandlerTestCase.php index 1d33451d45..15a0f03522 100644 --- a/Tests/AbstractRequestHandlerTest.php +++ b/Tests/AbstractRequestHandlerTestCase.php @@ -27,7 +27,7 @@ /** * @author Bernhard Schussek */ -abstract class AbstractRequestHandlerTest extends TestCase +abstract class AbstractRequestHandlerTestCase extends TestCase { /** * @var RequestHandlerInterface diff --git a/Tests/AbstractTableLayoutTest.php b/Tests/AbstractTableLayoutTestCase.php similarity index 99% rename from Tests/AbstractTableLayoutTest.php rename to Tests/AbstractTableLayoutTestCase.php index 5ce77a7f8a..09d669129f 100644 --- a/Tests/AbstractTableLayoutTest.php +++ b/Tests/AbstractTableLayoutTestCase.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\FormError; use Symfony\Component\Security\Csrf\CsrfToken; -abstract class AbstractTableLayoutTest extends AbstractLayoutTest +abstract class AbstractTableLayoutTestCase extends AbstractLayoutTestCase { public function testRow() { diff --git a/Tests/ChoiceList/AbstractChoiceListTest.php b/Tests/ChoiceList/AbstractChoiceListTestCase.php similarity index 98% rename from Tests/ChoiceList/AbstractChoiceListTest.php rename to Tests/ChoiceList/AbstractChoiceListTestCase.php index d2aac23e3a..dd55bfcff0 100644 --- a/Tests/ChoiceList/AbstractChoiceListTest.php +++ b/Tests/ChoiceList/AbstractChoiceListTestCase.php @@ -17,7 +17,7 @@ /** * @author Bernhard Schussek */ -abstract class AbstractChoiceListTest extends TestCase +abstract class AbstractChoiceListTestCase extends TestCase { /** * @var ChoiceListInterface diff --git a/Tests/ChoiceList/ArrayChoiceListTest.php b/Tests/ChoiceList/ArrayChoiceListTest.php index 5dc2e5db90..835085a7ac 100644 --- a/Tests/ChoiceList/ArrayChoiceListTest.php +++ b/Tests/ChoiceList/ArrayChoiceListTest.php @@ -17,7 +17,7 @@ /** * @author Bernhard Schussek */ -class ArrayChoiceListTest extends AbstractChoiceListTest +class ArrayChoiceListTest extends AbstractChoiceListTestCase { private $object; diff --git a/Tests/Console/Descriptor/AbstractDescriptorTest.php b/Tests/Console/Descriptor/AbstractDescriptorTestCase.php similarity index 99% rename from Tests/Console/Descriptor/AbstractDescriptorTest.php rename to Tests/Console/Descriptor/AbstractDescriptorTestCase.php index 1553292941..3fea781b6c 100644 --- a/Tests/Console/Descriptor/AbstractDescriptorTest.php +++ b/Tests/Console/Descriptor/AbstractDescriptorTestCase.php @@ -26,7 +26,7 @@ use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Security\Csrf\CsrfTokenManager; -abstract class AbstractDescriptorTest extends TestCase +abstract class AbstractDescriptorTestCase extends TestCase { private $colSize; diff --git a/Tests/Console/Descriptor/JsonDescriptorTest.php b/Tests/Console/Descriptor/JsonDescriptorTest.php index c035be6bcd..4545ee2b01 100644 --- a/Tests/Console/Descriptor/JsonDescriptorTest.php +++ b/Tests/Console/Descriptor/JsonDescriptorTest.php @@ -13,7 +13,7 @@ use Symfony\Component\Form\Console\Descriptor\JsonDescriptor; -class JsonDescriptorTest extends AbstractDescriptorTest +class JsonDescriptorTest extends AbstractDescriptorTestCase { protected function getDescriptor() { diff --git a/Tests/Console/Descriptor/TextDescriptorTest.php b/Tests/Console/Descriptor/TextDescriptorTest.php index c970eba96e..575783c74a 100644 --- a/Tests/Console/Descriptor/TextDescriptorTest.php +++ b/Tests/Console/Descriptor/TextDescriptorTest.php @@ -13,7 +13,7 @@ use Symfony\Component\Form\Console\Descriptor\TextDescriptor; -class TextDescriptorTest extends AbstractDescriptorTest +class TextDescriptorTest extends AbstractDescriptorTestCase { protected function getDescriptor() { diff --git a/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.php b/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTestCase.php similarity index 95% rename from Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.php rename to Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTestCase.php index e3f101a8aa..7e86f2c069 100644 --- a/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTestCase.php @@ -15,7 +15,7 @@ use Symfony\Component\Form\Exception\InvalidArgumentException; use Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer; -abstract class BaseDateTimeTransformerTest extends TestCase +abstract class BaseDateTimeTransformerTestCase extends TestCase { public function testConstructFailsIfInputTimezoneIsInvalid() { diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php index 3aafbec88a..08e05c5840 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToArrayTransformer; -class DateTimeToArrayTransformerTest extends BaseDateTimeTransformerTest +class DateTimeToArrayTransformerTest extends BaseDateTimeTransformerTestCase { public function testTransform() { diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php index 6e6e66afb1..6a3475dd3e 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php @@ -16,7 +16,7 @@ use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToHtml5LocalDateTimeTransformer; use Symfony\Component\Form\Tests\Extension\Core\DataTransformer\Traits\DateTimeEqualsTrait; -class DateTimeToHtml5LocalDateTimeTransformerTest extends BaseDateTimeTransformerTest +class DateTimeToHtml5LocalDateTimeTransformerTest extends BaseDateTimeTransformerTestCase { use DateTimeEqualsTrait; diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php index 2212bcf99e..fe829a4299 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php @@ -17,7 +17,7 @@ use Symfony\Component\Form\Tests\Extension\Core\DataTransformer\Traits\DateTimeEqualsTrait; use Symfony\Component\Intl\Util\IntlTestHelper; -class DateTimeToLocalizedStringTransformerTest extends BaseDateTimeTransformerTest +class DateTimeToLocalizedStringTransformerTest extends BaseDateTimeTransformerTestCase { use DateTimeEqualsTrait; diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php index 0412dc321a..90d1c538f2 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php @@ -16,7 +16,7 @@ use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToRfc3339Transformer; use Symfony\Component\Form\Tests\Extension\Core\DataTransformer\Traits\DateTimeEqualsTrait; -class DateTimeToRfc3339TransformerTest extends BaseDateTimeTransformerTest +class DateTimeToRfc3339TransformerTest extends BaseDateTimeTransformerTestCase { use DateTimeEqualsTrait; diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToStringTransformerTest.php index 4bdfff1ed0..1ca6078688 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToStringTransformerTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer; -class DateTimeToStringTransformerTest extends BaseDateTimeTransformerTest +class DateTimeToStringTransformerTest extends BaseDateTimeTransformerTestCase { public function dataProvider(): array { diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToTimestampTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToTimestampTransformerTest.php index 7a84153a73..bf662d6464 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToTimestampTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToTimestampTransformerTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToTimestampTransformer; -class DateTimeToTimestampTransformerTest extends BaseDateTimeTransformerTest +class DateTimeToTimestampTransformerTest extends BaseDateTimeTransformerTestCase { public function testTransform() { diff --git a/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayObjectTest.php b/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayObjectTest.php index 5de0ea607a..47db5a0acd 100644 --- a/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayObjectTest.php +++ b/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayObjectTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormFactoryBuilder; -class MergeCollectionListenerArrayObjectTest extends MergeCollectionListenerTest +class MergeCollectionListenerArrayObjectTest extends MergeCollectionListenerTestCase { protected function getData(array $data) { diff --git a/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayTest.php b/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayTest.php index 4f19a3ff8e..df382a0b50 100644 --- a/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayTest.php +++ b/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormFactoryBuilder; -class MergeCollectionListenerArrayTest extends MergeCollectionListenerTest +class MergeCollectionListenerArrayTest extends MergeCollectionListenerTestCase { protected function getData(array $data) { diff --git a/Tests/Extension/Core/EventListener/MergeCollectionListenerCustomArrayObjectTest.php b/Tests/Extension/Core/EventListener/MergeCollectionListenerCustomArrayObjectTest.php index 4be3b4baba..a13a6c071a 100644 --- a/Tests/Extension/Core/EventListener/MergeCollectionListenerCustomArrayObjectTest.php +++ b/Tests/Extension/Core/EventListener/MergeCollectionListenerCustomArrayObjectTest.php @@ -16,7 +16,7 @@ use Symfony\Component\Form\FormFactoryBuilder; use Symfony\Component\Form\Tests\Fixtures\CustomArrayObject; -class MergeCollectionListenerCustomArrayObjectTest extends MergeCollectionListenerTest +class MergeCollectionListenerCustomArrayObjectTest extends MergeCollectionListenerTestCase { protected function getData(array $data) { diff --git a/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php b/Tests/Extension/Core/EventListener/MergeCollectionListenerTestCase.php similarity index 99% rename from Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php rename to Tests/Extension/Core/EventListener/MergeCollectionListenerTestCase.php index 4cb0970aba..b9ca39c93b 100644 --- a/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.php +++ b/Tests/Extension/Core/EventListener/MergeCollectionListenerTestCase.php @@ -16,7 +16,7 @@ use Symfony\Component\Form\Extension\Core\EventListener\MergeCollectionListener; use Symfony\Component\Form\FormEvent; -abstract class MergeCollectionListenerTest extends TestCase +abstract class MergeCollectionListenerTestCase extends TestCase { protected $form; diff --git a/Tests/Extension/Core/Type/BaseTypeTest.php b/Tests/Extension/Core/Type/BaseTypeTestCase.php similarity index 99% rename from Tests/Extension/Core/Type/BaseTypeTest.php rename to Tests/Extension/Core/Type/BaseTypeTestCase.php index 3303e6a5c7..e86bf9e41e 100644 --- a/Tests/Extension/Core/Type/BaseTypeTest.php +++ b/Tests/Extension/Core/Type/BaseTypeTestCase.php @@ -17,7 +17,7 @@ /** * @author Bernhard Schussek */ -abstract class BaseTypeTest extends TypeTestCase +abstract class BaseTypeTestCase extends TypeTestCase { use VersionAwareTest; diff --git a/Tests/Extension/Core/Type/ButtonTypeTest.php b/Tests/Extension/Core/Type/ButtonTypeTest.php index dcff028026..afb5f82082 100644 --- a/Tests/Extension/Core/Type/ButtonTypeTest.php +++ b/Tests/Extension/Core/Type/ButtonTypeTest.php @@ -19,7 +19,7 @@ /** * @author Bernhard Schussek */ -class ButtonTypeTest extends BaseTypeTest +class ButtonTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\ButtonType'; diff --git a/Tests/Extension/Core/Type/CheckboxTypeTest.php b/Tests/Extension/Core/Type/CheckboxTypeTest.php index 95ef611b1c..6f8402126f 100644 --- a/Tests/Extension/Core/Type/CheckboxTypeTest.php +++ b/Tests/Extension/Core/Type/CheckboxTypeTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; -class CheckboxTypeTest extends BaseTypeTest +class CheckboxTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\CheckboxType'; diff --git a/Tests/Extension/Core/Type/ChoiceTypeTest.php b/Tests/Extension/Core/Type/ChoiceTypeTest.php index 8bf3dc2359..c9a47f3520 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -18,7 +18,7 @@ use Symfony\Component\Form\FormInterface; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; -class ChoiceTypeTest extends BaseTypeTest +class ChoiceTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\ChoiceType'; diff --git a/Tests/Extension/Core/Type/CollectionTypeTest.php b/Tests/Extension/Core/Type/CollectionTypeTest.php index 9df4eede1e..211b14a270 100644 --- a/Tests/Extension/Core/Type/CollectionTypeTest.php +++ b/Tests/Extension/Core/Type/CollectionTypeTest.php @@ -18,7 +18,7 @@ use Symfony\Component\Form\Tests\Fixtures\AuthorType; use Symfony\Component\Form\Tests\Fixtures\BlockPrefixedFooTextType; -class CollectionTypeTest extends BaseTypeTest +class CollectionTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\CollectionType'; diff --git a/Tests/Extension/Core/Type/ColorTypeTest.php b/Tests/Extension/Core/Type/ColorTypeTest.php index cfe7f0c527..cd514d152a 100644 --- a/Tests/Extension/Core/Type/ColorTypeTest.php +++ b/Tests/Extension/Core/Type/ColorTypeTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\ColorType; use Symfony\Component\Form\FormError; -final class ColorTypeTest extends BaseTypeTest +final class ColorTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = ColorType::class; diff --git a/Tests/Extension/Core/Type/CountryTypeTest.php b/Tests/Extension/Core/Type/CountryTypeTest.php index 9572f3418c..57146e1ecf 100644 --- a/Tests/Extension/Core/Type/CountryTypeTest.php +++ b/Tests/Extension/Core/Type/CountryTypeTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Intl\Util\IntlTestHelper; -class CountryTypeTest extends BaseTypeTest +class CountryTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\CountryType'; diff --git a/Tests/Extension/Core/Type/CurrencyTypeTest.php b/Tests/Extension/Core/Type/CurrencyTypeTest.php index 8cccfd32bd..51aaf6b372 100644 --- a/Tests/Extension/Core/Type/CurrencyTypeTest.php +++ b/Tests/Extension/Core/Type/CurrencyTypeTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Intl\Util\IntlTestHelper; -class CurrencyTypeTest extends BaseTypeTest +class CurrencyTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\CurrencyType'; diff --git a/Tests/Extension/Core/Type/DateIntervalTypeTest.php b/Tests/Extension/Core/Type/DateIntervalTypeTest.php index efbb47bea5..3d8f872287 100644 --- a/Tests/Extension/Core/Type/DateIntervalTypeTest.php +++ b/Tests/Extension/Core/Type/DateIntervalTypeTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; -class DateIntervalTypeTest extends BaseTypeTest +class DateIntervalTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = DateIntervalType::class; diff --git a/Tests/Extension/Core/Type/DateTimeTypeTest.php b/Tests/Extension/Core/Type/DateTimeTypeTest.php index 12b6939a68..d35c189da0 100644 --- a/Tests/Extension/Core/Type/DateTimeTypeTest.php +++ b/Tests/Extension/Core/Type/DateTimeTypeTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; -class DateTimeTypeTest extends BaseTypeTest +class DateTimeTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\DateTimeType'; diff --git a/Tests/Extension/Core/Type/DateTypeTest.php b/Tests/Extension/Core/Type/DateTypeTest.php index 62a12289cb..f875345f1b 100644 --- a/Tests/Extension/Core/Type/DateTypeTest.php +++ b/Tests/Extension/Core/Type/DateTypeTest.php @@ -17,7 +17,7 @@ use Symfony\Component\Intl\Util\IntlTestHelper; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; -class DateTypeTest extends BaseTypeTest +class DateTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\DateType'; diff --git a/Tests/Extension/Core/Type/EnumTypeTest.php b/Tests/Extension/Core/Type/EnumTypeTest.php index 9eb89442ea..61eb456895 100644 --- a/Tests/Extension/Core/Type/EnumTypeTest.php +++ b/Tests/Extension/Core/Type/EnumTypeTest.php @@ -12,14 +12,14 @@ namespace Extension\Core\Type; use Symfony\Component\Form\Extension\Core\Type\EnumType; -use Symfony\Component\Form\Tests\Extension\Core\Type\BaseTypeTest; +use Symfony\Component\Form\Tests\Extension\Core\Type\BaseTypeTestCase; use Symfony\Component\Form\Tests\Fixtures\Answer; use Symfony\Component\Form\Tests\Fixtures\Number; use Symfony\Component\Form\Tests\Fixtures\Suit; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; -class EnumTypeTest extends BaseTypeTest +class EnumTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = EnumType::class; diff --git a/Tests/Extension/Core/Type/FileTypeTest.php b/Tests/Extension/Core/Type/FileTypeTest.php index 5ca5267430..a893d6d622 100644 --- a/Tests/Extension/Core/Type/FileTypeTest.php +++ b/Tests/Extension/Core/Type/FileTypeTest.php @@ -19,7 +19,7 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\Translation\IdentityTranslator; -class FileTypeTest extends BaseTypeTest +class FileTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\FileType'; diff --git a/Tests/Extension/Core/Type/FormTypeTest.php b/Tests/Extension/Core/Type/FormTypeTest.php index b4bca15130..0c307a3b76 100644 --- a/Tests/Extension/Core/Type/FormTypeTest.php +++ b/Tests/Extension/Core/Type/FormTypeTest.php @@ -62,7 +62,7 @@ public function setReferenceCopy($reference) } } -class FormTypeTest extends BaseTypeTest +class FormTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\FormType'; diff --git a/Tests/Extension/Core/Type/IntegerTypeTest.php b/Tests/Extension/Core/Type/IntegerTypeTest.php index 15cf308d99..6d03ebf6cf 100644 --- a/Tests/Extension/Core/Type/IntegerTypeTest.php +++ b/Tests/Extension/Core/Type/IntegerTypeTest.php @@ -13,7 +13,7 @@ use Symfony\Component\Intl\Util\IntlTestHelper; -class IntegerTypeTest extends BaseTypeTest +class IntegerTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\IntegerType'; diff --git a/Tests/Extension/Core/Type/LanguageTypeTest.php b/Tests/Extension/Core/Type/LanguageTypeTest.php index 4946aca29e..e214e0afd4 100644 --- a/Tests/Extension/Core/Type/LanguageTypeTest.php +++ b/Tests/Extension/Core/Type/LanguageTypeTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Intl\Util\IntlTestHelper; -class LanguageTypeTest extends BaseTypeTest +class LanguageTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\LanguageType'; diff --git a/Tests/Extension/Core/Type/LocaleTypeTest.php b/Tests/Extension/Core/Type/LocaleTypeTest.php index 8d3eaea363..8486b6656b 100644 --- a/Tests/Extension/Core/Type/LocaleTypeTest.php +++ b/Tests/Extension/Core/Type/LocaleTypeTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Intl\Util\IntlTestHelper; -class LocaleTypeTest extends BaseTypeTest +class LocaleTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\LocaleType'; diff --git a/Tests/Extension/Core/Type/MoneyTypeTest.php b/Tests/Extension/Core/Type/MoneyTypeTest.php index 94f47706ab..c65629d946 100644 --- a/Tests/Extension/Core/Type/MoneyTypeTest.php +++ b/Tests/Extension/Core/Type/MoneyTypeTest.php @@ -13,7 +13,7 @@ use Symfony\Component\Intl\Util\IntlTestHelper; -class MoneyTypeTest extends BaseTypeTest +class MoneyTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\MoneyType'; diff --git a/Tests/Extension/Core/Type/NumberTypeTest.php b/Tests/Extension/Core/Type/NumberTypeTest.php index 0cf482a9d8..f289fa6978 100644 --- a/Tests/Extension/Core/Type/NumberTypeTest.php +++ b/Tests/Extension/Core/Type/NumberTypeTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Intl\Util\IntlTestHelper; -class NumberTypeTest extends BaseTypeTest +class NumberTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\NumberType'; diff --git a/Tests/Extension/Core/Type/PasswordTypeTest.php b/Tests/Extension/Core/Type/PasswordTypeTest.php index 29756f17b9..8d428a26a5 100644 --- a/Tests/Extension/Core/Type/PasswordTypeTest.php +++ b/Tests/Extension/Core/Type/PasswordTypeTest.php @@ -11,7 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; -class PasswordTypeTest extends BaseTypeTest +class PasswordTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\PasswordType'; diff --git a/Tests/Extension/Core/Type/RepeatedTypeTest.php b/Tests/Extension/Core/Type/RepeatedTypeTest.php index 60d5657876..2d200ede19 100644 --- a/Tests/Extension/Core/Type/RepeatedTypeTest.php +++ b/Tests/Extension/Core/Type/RepeatedTypeTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Form\Tests\Fixtures\NotMappedType; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; -class RepeatedTypeTest extends BaseTypeTest +class RepeatedTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\RepeatedType'; diff --git a/Tests/Extension/Core/Type/TextTypeTest.php b/Tests/Extension/Core/Type/TextTypeTest.php index 3f8fbe7725..7b30fe31a1 100644 --- a/Tests/Extension/Core/Type/TextTypeTest.php +++ b/Tests/Extension/Core/Type/TextTypeTest.php @@ -11,7 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; -class TextTypeTest extends BaseTypeTest +class TextTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\TextType'; diff --git a/Tests/Extension/Core/Type/TimeTypeTest.php b/Tests/Extension/Core/Type/TimeTypeTest.php index 991d9c23fe..ba5b935c7b 100644 --- a/Tests/Extension/Core/Type/TimeTypeTest.php +++ b/Tests/Extension/Core/Type/TimeTypeTest.php @@ -18,7 +18,7 @@ use Symfony\Component\Form\FormInterface; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; -class TimeTypeTest extends BaseTypeTest +class TimeTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\TimeType'; diff --git a/Tests/Extension/Core/Type/TimezoneTypeTest.php b/Tests/Extension/Core/Type/TimezoneTypeTest.php index 669f0d9e57..9966b40438 100644 --- a/Tests/Extension/Core/Type/TimezoneTypeTest.php +++ b/Tests/Extension/Core/Type/TimezoneTypeTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Intl\Util\IntlTestHelper; -class TimezoneTypeTest extends BaseTypeTest +class TimezoneTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\TimezoneType'; diff --git a/Tests/Extension/Core/Type/UlidTypeTest.php b/Tests/Extension/Core/Type/UlidTypeTest.php index 4f61992cb6..5ed324e823 100644 --- a/Tests/Extension/Core/Type/UlidTypeTest.php +++ b/Tests/Extension/Core/Type/UlidTypeTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\UlidType; use Symfony\Component\Uid\Ulid; -final class UlidTypeTest extends BaseTypeTest +final class UlidTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = UlidType::class; diff --git a/Tests/Extension/Core/Type/UuidTypeTest.php b/Tests/Extension/Core/Type/UuidTypeTest.php index 9b9bfb2d2a..90043356da 100644 --- a/Tests/Extension/Core/Type/UuidTypeTest.php +++ b/Tests/Extension/Core/Type/UuidTypeTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\UuidType; use Symfony\Component\Uid\Uuid; -final class UuidTypeTest extends BaseTypeTest +final class UuidTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = UuidType::class; diff --git a/Tests/Extension/Core/Type/WeekTypeTest.php b/Tests/Extension/Core/Type/WeekTypeTest.php index 7d0dc1958b..68cadba570 100644 --- a/Tests/Extension/Core/Type/WeekTypeTest.php +++ b/Tests/Extension/Core/Type/WeekTypeTest.php @@ -13,7 +13,7 @@ use Symfony\Component\Form\FormError; -class WeekTypeTest extends BaseTypeTest +class WeekTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\WeekType'; diff --git a/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php b/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php index 69be3777cc..4aacf904d5 100644 --- a/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php +++ b/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.php @@ -13,14 +13,14 @@ use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler; -use Symfony\Component\Form\Tests\AbstractRequestHandlerTest; +use Symfony\Component\Form\Tests\AbstractRequestHandlerTestCase; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; /** * @author Bernhard Schussek */ -class HttpFoundationRequestHandlerTest extends AbstractRequestHandlerTest +class HttpFoundationRequestHandlerTest extends AbstractRequestHandlerTestCase { public function testRequestShouldNotBeNull() { diff --git a/Tests/Extension/Validator/Type/BaseValidatorExtensionTest.php b/Tests/Extension/Validator/Type/BaseValidatorExtensionTestCase.php similarity index 97% rename from Tests/Extension/Validator/Type/BaseValidatorExtensionTest.php rename to Tests/Extension/Validator/Type/BaseValidatorExtensionTestCase.php index 4b69dfe886..2ade3b844b 100644 --- a/Tests/Extension/Validator/Type/BaseValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/BaseValidatorExtensionTestCase.php @@ -18,7 +18,7 @@ /** * @author Bernhard Schussek */ -abstract class BaseValidatorExtensionTest extends TypeTestCase +abstract class BaseValidatorExtensionTestCase extends TypeTestCase { public function testValidationGroupNullByDefault() { diff --git a/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php index 8beaaf6e58..7ef39bde14 100644 --- a/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\BirthdayType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class BirthdayTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class BirthdayTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php index 6617389a1c..361c0539c3 100644 --- a/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CheckboxTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class CheckboxTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class CheckboxTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php index e8c3c94bf8..3f4db70fd5 100644 --- a/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/ChoiceTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class ChoiceTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class ChoiceTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php index 34105251c3..c6f11c24aa 100644 --- a/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CollectionTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class CollectionTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class CollectionTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php index 51567835c1..766beeec05 100644 --- a/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/ColorTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\ColorType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class ColorTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class ColorTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php index 1470b49c6c..c8b2bd3424 100644 --- a/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CountryTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\CountryType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class CountryTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class CountryTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php index b340de93a1..134be31154 100644 --- a/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/CurrencyTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\CurrencyType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class CurrencyTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class CurrencyTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php index 634af5696a..ea2f4998c0 100644 --- a/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/DateIntervalTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\DateIntervalType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class DateIntervalTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class DateIntervalTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php index 973e86d66d..a8206e40c3 100644 --- a/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\DateTimeType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class DateTimeTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class DateTimeTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php index fe76eaf97f..32594430dc 100644 --- a/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class DateTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class DateTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php index e8de05ae05..89e69749c3 100644 --- a/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/EmailTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\EmailType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class EmailTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class EmailTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php index 7cda446bb8..84045d6ade 100644 --- a/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/FileTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class FileTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class FileTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php index 30db508520..3b4cd77396 100644 --- a/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php @@ -28,7 +28,7 @@ use Symfony\Component\Validator\Mapping\Factory\MetadataFactoryInterface; use Symfony\Component\Validator\Validation; -class FormTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class FormTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php index 955027ff09..83de73f996 100644 --- a/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/HiddenTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\HiddenType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class HiddenTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class HiddenTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php index e664003274..0621d6d8d0 100644 --- a/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/IntegerTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class IntegerTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class IntegerTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php index e29e837e0c..9343a9a123 100644 --- a/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/LanguageTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\LanguageType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class LanguageTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class LanguageTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php index 83f7c762f2..e2e948b5db 100644 --- a/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/LocaleTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\LocaleType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class LocaleTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class LocaleTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php index 5d62c63852..e457a4b2a7 100644 --- a/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/MoneyTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\MoneyType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class MoneyTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class MoneyTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php index 11efbde963..6e886cecdc 100644 --- a/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/NumberTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\NumberType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class NumberTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class NumberTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php index 489d87283b..5ddc0d4cb0 100644 --- a/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/PasswordTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\PasswordType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class PasswordTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class PasswordTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php index 2ac42f674f..d4317eb17a 100644 --- a/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/PercentTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\PercentType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class PercentTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class PercentTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php index cc489c90aa..c6ac73544c 100644 --- a/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/RadioTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\RadioType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class RadioTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class RadioTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php index eba6049e95..0ace710977 100644 --- a/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/RangeTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\RangeType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class RangeTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class RangeTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php index 445e60c6c2..99c521682b 100644 --- a/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/RepeatedTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\RepeatedType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class RepeatedTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class RepeatedTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php index d362c8cfe6..14d4350e5a 100644 --- a/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/SearchTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\SearchType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class SearchTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class SearchTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/SubmitTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/SubmitTypeValidatorExtensionTest.php index c347c89bce..42aeb609bf 100644 --- a/Tests/Extension/Validator/Type/SubmitTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/SubmitTypeValidatorExtensionTest.php @@ -13,7 +13,7 @@ use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class SubmitTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class SubmitTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php index 7d7f5307bf..ff6ec95c83 100644 --- a/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/TelTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\TelType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class TelTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class TelTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php index 2b48de4d19..09893b98a1 100644 --- a/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\TimeType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class TimeTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class TimeTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php index f66d4d4229..3ee0f5d202 100644 --- a/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/TimezoneTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\TimezoneType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class TimezoneTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class TimezoneTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php index cb85fde39a..e6314a3c59 100644 --- a/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php @@ -14,7 +14,7 @@ use Symfony\Component\Form\Extension\Core\Type\UrlType; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; -class UrlTypeValidatorExtensionTest extends BaseValidatorExtensionTest +class UrlTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase { use ValidatorExtensionTrait; diff --git a/Tests/Fixtures/Descriptor/overridden_option_with_default_closures.txt b/Tests/Fixtures/Descriptor/overridden_option_with_default_closures.txt index 043a1dbc27..cedca25a60 100644 --- a/Tests/Fixtures/Descriptor/overridden_option_with_default_closures.txt +++ b/Tests/Fixtures/Descriptor/overridden_option_with_default_closures.txt @@ -14,7 +14,7 @@ Symfony\Component\Form\Tests\Console\Descriptor\FooType (empty_data) line: %s }, %s Closure%s{%A - file: "%s%eTests%eConsole%eDescriptor%eAbstractDescriptorTest.php"%w + file: "%s%eTests%eConsole%eDescriptor%eAbstractDescriptorTestCase.php"%w line: %s } %s ] %s diff --git a/Tests/NativeRequestHandlerTest.php b/Tests/NativeRequestHandlerTest.php index 8bbf0793ff..e698138376 100644 --- a/Tests/NativeRequestHandlerTest.php +++ b/Tests/NativeRequestHandlerTest.php @@ -17,7 +17,7 @@ /** * @author Bernhard Schussek */ -class NativeRequestHandlerTest extends AbstractRequestHandlerTest +class NativeRequestHandlerTest extends AbstractRequestHandlerTestCase { private static $serverBackup; diff --git a/composer.json b/composer.json index e859bf2c7f..4fc6eb72da 100644 --- a/composer.json +++ b/composer.json @@ -47,13 +47,13 @@ "phpunit/phpunit": "<5.4.3", "symfony/console": "<5.4", "symfony/dependency-injection": "<5.4", - "symfony/doctrine-bridge": "<5.4", + "symfony/doctrine-bridge": "<6.3", "symfony/error-handler": "<5.4", "symfony/framework-bundle": "<5.4", "symfony/http-kernel": "<5.4", "symfony/translation": "<5.4", "symfony/translation-contracts": "<2.5", - "symfony/twig-bridge": "<5.4" + "symfony/twig-bridge": "<6.3" }, "suggest": { "symfony/validator": "For form validation.", From d78da7723450a7c4820a3718a2308434b6c61ddb Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Mon, 13 Feb 2023 00:00:11 +0100 Subject: [PATCH 082/208] Add missing PHPdoc return types --- ButtonBuilder.php | 6 ++++ FormConfigBuilder.php | 63 ++++++++++++++++++++++++++++++++++ FormConfigBuilderInterface.php | 2 ++ 3 files changed, 71 insertions(+) diff --git a/ButtonBuilder.php b/ButtonBuilder.php index bfba1d6cd0..9cc32888e1 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -173,6 +173,9 @@ public function resetModelTransformers(): static throw new BadMethodCallException('Buttons do not support data transformers.'); } + /** + * @return $this + */ public function setAttribute(string $name, mixed $value): static { $this->attributes[$name] = $value; @@ -180,6 +183,9 @@ public function setAttribute(string $name, mixed $value): static return $this; } + /** + * @return $this + */ public function setAttributes(array $attributes): static { $this->attributes = $attributes; diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index e18db7ed8e..0220399758 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -316,6 +316,9 @@ public function getIsEmptyCallback(): ?callable return $this->isEmptyCallback; } + /** + * @return $this + */ public function setAttribute(string $name, mixed $value): static { if ($this->locked) { @@ -327,6 +330,9 @@ public function setAttribute(string $name, mixed $value): static return $this; } + /** + * @return $this + */ public function setAttributes(array $attributes): static { if ($this->locked) { @@ -338,6 +344,9 @@ public function setAttributes(array $attributes): static return $this; } + /** + * @return $this + */ public function setDataMapper(DataMapperInterface $dataMapper = null): static { if (1 > \func_num_args()) { @@ -352,6 +361,9 @@ public function setDataMapper(DataMapperInterface $dataMapper = null): static return $this; } + /** + * @return $this + */ public function setDisabled(bool $disabled): static { if ($this->locked) { @@ -363,6 +375,9 @@ public function setDisabled(bool $disabled): static return $this; } + /** + * @return $this + */ public function setEmptyData(mixed $emptyData): static { if ($this->locked) { @@ -374,6 +389,9 @@ public function setEmptyData(mixed $emptyData): static return $this; } + /** + * @return $this + */ public function setErrorBubbling(bool $errorBubbling): static { if ($this->locked) { @@ -385,6 +403,9 @@ public function setErrorBubbling(bool $errorBubbling): static return $this; } + /** + * @return $this + */ public function setRequired(bool $required): static { if ($this->locked) { @@ -396,6 +417,9 @@ public function setRequired(bool $required): static return $this; } + /** + * @return $this + */ public function setPropertyPath(string|PropertyPathInterface|null $propertyPath): static { if ($this->locked) { @@ -411,6 +435,9 @@ public function setPropertyPath(string|PropertyPathInterface|null $propertyPath) return $this; } + /** + * @return $this + */ public function setMapped(bool $mapped): static { if ($this->locked) { @@ -422,6 +449,9 @@ public function setMapped(bool $mapped): static return $this; } + /** + * @return $this + */ public function setByReference(bool $byReference): static { if ($this->locked) { @@ -433,6 +463,9 @@ public function setByReference(bool $byReference): static return $this; } + /** + * @return $this + */ public function setInheritData(bool $inheritData): static { if ($this->locked) { @@ -444,6 +477,9 @@ public function setInheritData(bool $inheritData): static return $this; } + /** + * @return $this + */ public function setCompound(bool $compound): static { if ($this->locked) { @@ -455,6 +491,9 @@ public function setCompound(bool $compound): static return $this; } + /** + * @return $this + */ public function setType(ResolvedFormTypeInterface $type): static { if ($this->locked) { @@ -466,6 +505,9 @@ public function setType(ResolvedFormTypeInterface $type): static return $this; } + /** + * @return $this + */ public function setData(mixed $data): static { if ($this->locked) { @@ -477,6 +519,9 @@ public function setData(mixed $data): static return $this; } + /** + * @return $this + */ public function setDataLocked(bool $locked): static { if ($this->locked) { @@ -488,6 +533,9 @@ public function setDataLocked(bool $locked): static return $this; } + /** + * @return $this + */ public function setFormFactory(FormFactoryInterface $formFactory) { if ($this->locked) { @@ -499,6 +547,9 @@ public function setFormFactory(FormFactoryInterface $formFactory) return $this; } + /** + * @return $this + */ public function setAction(string $action): static { if ($this->locked) { @@ -510,6 +561,9 @@ public function setAction(string $action): static return $this; } + /** + * @return $this + */ public function setMethod(string $method): static { if ($this->locked) { @@ -521,6 +575,9 @@ public function setMethod(string $method): static return $this; } + /** + * @return $this + */ public function setRequestHandler(RequestHandlerInterface $requestHandler): static { if ($this->locked) { @@ -532,6 +589,9 @@ public function setRequestHandler(RequestHandlerInterface $requestHandler): stat return $this; } + /** + * @return $this + */ public function setAutoInitialize(bool $initialize): static { if ($this->locked) { @@ -556,6 +616,9 @@ public function getFormConfig(): FormConfigInterface return $config; } + /** + * @return $this + */ public function setIsEmptyCallback(?callable $isEmptyCallback): static { $this->isEmptyCallback = null === $isEmptyCallback ? null : $isEmptyCallback(...); diff --git a/FormConfigBuilderInterface.php b/FormConfigBuilderInterface.php index 84f40d3711..09b9149801 100644 --- a/FormConfigBuilderInterface.php +++ b/FormConfigBuilderInterface.php @@ -205,6 +205,8 @@ public function setDataLocked(bool $locked): static; /** * Sets the form factory used for creating new forms. + * + * @return $this */ public function setFormFactory(FormFactoryInterface $formFactory); From b8d7a891bc8a205f27b69a67e191ee86c2b922c7 Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Mon, 13 Feb 2023 00:00:27 +0100 Subject: [PATCH 083/208] Add PHP types to private methods and functions --- Console/Descriptor/Descriptor.php | 16 ++++++++-------- Console/Descriptor/JsonDescriptor.php | 10 +++++----- Console/Descriptor/TextDescriptor.php | 6 +++--- Extension/Core/Type/ChoiceType.php | 4 ++-- Extension/Core/Type/DateType.php | 8 ++++---- Extension/Core/Type/FileType.php | 4 ++-- 6 files changed, 24 insertions(+), 24 deletions(-) diff --git a/Console/Descriptor/Descriptor.php b/Console/Descriptor/Descriptor.php index 43edf13d35..782bad8870 100644 --- a/Console/Descriptor/Descriptor.php +++ b/Console/Descriptor/Descriptor.php @@ -40,7 +40,7 @@ abstract class Descriptor implements DescriptorInterface protected $parents = []; protected $extensions = []; - public function describe(OutputInterface $output, ?object $object, array $options = []) + public function describe(OutputInterface $output, ?object $object, array $options = []): void { $this->output = $output instanceof OutputStyle ? $output : new SymfonyStyle(new ArrayInput([]), $output); @@ -52,13 +52,13 @@ public function describe(OutputInterface $output, ?object $object, array $option }; } - abstract protected function describeDefaults(array $options); + abstract protected function describeDefaults(array $options): void; - abstract protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = []); + abstract protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = []): void; - abstract protected function describeOption(OptionsResolver $optionsResolver, array $options); + abstract protected function describeOption(OptionsResolver $optionsResolver, array $options): void; - protected function collectOptions(ResolvedFormTypeInterface $type) + protected function collectOptions(ResolvedFormTypeInterface $type): void { $this->parents = []; $this->extensions = []; @@ -96,7 +96,7 @@ protected function collectOptions(ResolvedFormTypeInterface $type) $this->extensions = array_keys($this->extensions); } - protected function getOptionDefinition(OptionsResolver $optionsResolver, string $option) + protected function getOptionDefinition(OptionsResolver $optionsResolver, string $option): array { $definition = []; @@ -139,7 +139,7 @@ protected function getOptionDefinition(OptionsResolver $optionsResolver, string return $definition; } - protected function filterOptionsByDeprecated(ResolvedFormTypeInterface $type) + protected function filterOptionsByDeprecated(ResolvedFormTypeInterface $type): void { $deprecatedOptions = []; $resolver = $type->getOptionsResolver(); @@ -186,7 +186,7 @@ private function getParentOptionsResolver(ResolvedFormTypeInterface $type): Opti return $optionsResolver; } - private function collectTypeExtensionsOptions(ResolvedFormTypeInterface $type, OptionsResolver $optionsResolver) + private function collectTypeExtensionsOptions(ResolvedFormTypeInterface $type, OptionsResolver $optionsResolver): void { foreach ($type->getTypeExtensions() as $extension) { $inheritedOptions = $optionsResolver->getDefinedOptions(); diff --git a/Console/Descriptor/JsonDescriptor.php b/Console/Descriptor/JsonDescriptor.php index 92d600389f..1f5c7bfa55 100644 --- a/Console/Descriptor/JsonDescriptor.php +++ b/Console/Descriptor/JsonDescriptor.php @@ -21,7 +21,7 @@ */ class JsonDescriptor extends Descriptor { - protected function describeDefaults(array $options) + protected function describeDefaults(array $options): void { $data['builtin_form_types'] = $options['core_types']; $data['service_form_types'] = $options['service_types']; @@ -33,7 +33,7 @@ protected function describeDefaults(array $options) $this->writeData($data, $options); } - protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = []) + protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = []): void { $this->collectOptions($resolvedFormType); @@ -61,7 +61,7 @@ protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedF $this->writeData($data, $options); } - protected function describeOption(OptionsResolver $optionsResolver, array $options) + protected function describeOption(OptionsResolver $optionsResolver, array $options): void { $definition = $this->getOptionDefinition($optionsResolver, $options['option']); @@ -93,14 +93,14 @@ protected function describeOption(OptionsResolver $optionsResolver, array $optio $this->writeData($data, $options); } - private function writeData(array $data, array $options) + private function writeData(array $data, array $options): void { $flags = $options['json_encoding'] ?? 0; $this->output->write(json_encode($data, $flags | \JSON_PRETTY_PRINT)."\n"); } - private function sortOptions(array &$options) + private function sortOptions(array &$options): void { foreach ($options as &$opts) { $sorted = false; diff --git a/Console/Descriptor/TextDescriptor.php b/Console/Descriptor/TextDescriptor.php index 317287f174..c4a2db27a0 100644 --- a/Console/Descriptor/TextDescriptor.php +++ b/Console/Descriptor/TextDescriptor.php @@ -31,7 +31,7 @@ public function __construct(FileLinkFormatter $fileLinkFormatter = null) $this->fileLinkFormatter = $fileLinkFormatter; } - protected function describeDefaults(array $options) + protected function describeDefaults(array $options): void { if ($options['core_types']) { $this->output->section('Built-in form types (Symfony\Component\Form\Extension\Core\Type)'); @@ -59,7 +59,7 @@ protected function describeDefaults(array $options) } } - protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = []) + protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = []): void { $this->collectOptions($resolvedFormType); @@ -99,7 +99,7 @@ protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedF } } - protected function describeOption(OptionsResolver $optionsResolver, array $options) + protected function describeOption(OptionsResolver $optionsResolver, array $options): void { $definition = $this->getOptionDefinition($optionsResolver, $options['option']); diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 051795b957..9694ed750a 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -420,7 +420,7 @@ private function addSubForm(FormBuilderInterface $builder, string $name, ChoiceV $builder->add($name, $choiceType, $choiceOpts); } - private function createChoiceList(array $options) + private function createChoiceList(array $options): ChoiceListInterface { if (null !== $options['choice_loader']) { return $this->choiceListFactory->createListFromLoader( @@ -440,7 +440,7 @@ private function createChoiceList(array $options) ); } - private function createChoiceListView(ChoiceListInterface $choiceList, array $options) + private function createChoiceListView(ChoiceListInterface $choiceList, array $options): ChoiceListView { return $this->choiceListFactory->createView( $choiceList, diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index b18df900ff..b08a4dd834 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -319,7 +319,7 @@ public function getBlockPrefix(): string return 'date'; } - private function formatTimestamps(\IntlDateFormatter $formatter, string $regex, array $timestamps) + private function formatTimestamps(\IntlDateFormatter $formatter, string $regex, array $timestamps): array { $pattern = $formatter->getPattern(); $timezone = $formatter->getTimeZoneId(); @@ -344,7 +344,7 @@ private function formatTimestamps(\IntlDateFormatter $formatter, string $regex, return $formattedTimestamps; } - private function listYears(array $years) + private function listYears(array $years): array { $result = []; @@ -355,7 +355,7 @@ private function listYears(array $years) return $result; } - private function listMonths(array $months) + private function listMonths(array $months): array { $result = []; @@ -366,7 +366,7 @@ private function listMonths(array $months) return $result; } - private function listDays(array $days) + private function listDays(array $days): array { $result = []; diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index d1bad77505..16d212ef0f 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -124,7 +124,7 @@ public function getBlockPrefix(): string return 'file'; } - private function getFileUploadError(int $errorCode) + private function getFileUploadError(int $errorCode): FileUploadError { $messageParameters = []; @@ -191,7 +191,7 @@ private static function getMaxFilesize(): int|float * * This method should be kept in sync with Symfony\Component\Validator\Constraints\FileValidator::factorizeSizes(). */ - private function factorizeSizes(int $size, int|float $limit) + private function factorizeSizes(int $size, int|float $limit): array { $coef = self::MIB_BYTES; $coefFactor = self::KIB_BYTES; From f94d6c607d7b97bec664cac2a195b14341f7d68f Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Sun, 12 Feb 2023 23:57:18 +0100 Subject: [PATCH 084/208] Add void return types --- AbstractExtension.php | 6 +++--- AbstractRendererEngine.php | 3 +++ AbstractType.php | 12 ++++++++++++ AbstractTypeExtension.php | 12 ++++++++++++ ChoiceList/ArrayChoiceList.php | 2 +- ChoiceList/Factory/CachingFactoryDecorator.php | 3 +++ .../Factory/DefaultChoiceListFactory.php | 6 +++--- Command/DebugCommand.php | 3 +++ DependencyInjection/FormPass.php | 3 +++ .../Core/DataMapper/CheckboxListMapper.php | 6 ++++++ Extension/Core/DataMapper/RadioListMapper.php | 6 ++++++ .../EventListener/FixUrlProtocolListener.php | 3 +++ .../EventListener/MergeCollectionListener.php | 3 +++ .../Core/EventListener/ResizeFormListener.php | 9 +++++++++ .../TransformationFailureListener.php | 3 +++ Extension/Core/EventListener/TrimListener.php | 3 +++ Extension/Core/Type/BaseType.php | 9 +++++++++ Extension/Core/Type/BirthdayType.php | 3 +++ Extension/Core/Type/ButtonType.php | 3 +++ Extension/Core/Type/CheckboxType.php | 9 +++++++++ Extension/Core/Type/CollectionType.php | 12 ++++++++++++ Extension/Core/Type/ColorType.php | 6 ++++++ Extension/Core/Type/CountryType.php | 3 +++ Extension/Core/Type/CurrencyType.php | 3 +++ Extension/Core/Type/DateIntervalType.php | 9 +++++++++ Extension/Core/Type/DateTimeType.php | 9 +++++++++ Extension/Core/Type/EmailType.php | 3 +++ Extension/Core/Type/FormType.php | 12 ++++++++++++ Extension/Core/Type/HiddenType.php | 3 +++ Extension/Core/Type/IntegerType.php | 9 +++++++++ Extension/Core/Type/LanguageType.php | 3 +++ Extension/Core/Type/LocaleType.php | 3 +++ Extension/Core/Type/MoneyType.php | 9 +++++++++ Extension/Core/Type/NumberType.php | 9 +++++++++ Extension/Core/Type/PasswordType.php | 6 ++++++ Extension/Core/Type/PercentType.php | 9 +++++++++ Extension/Core/Type/RadioType.php | 3 +++ Extension/Core/Type/RangeType.php | 3 +++ Extension/Core/Type/RepeatedType.php | 6 ++++++ Extension/Core/Type/SearchType.php | 3 +++ Extension/Core/Type/SubmitType.php | 6 ++++++ Extension/Core/Type/TelType.php | 3 +++ Extension/Core/Type/TextType.php | 6 ++++++ Extension/Core/Type/TextareaType.php | 3 +++ Extension/Core/Type/TimeType.php | 9 +++++++++ Extension/Core/Type/TimezoneType.php | 6 ++++++ .../Type/TransformationFailureExtension.php | 3 +++ Extension/Core/Type/UlidType.php | 6 ++++++ Extension/Core/Type/UrlType.php | 9 +++++++++ Extension/Core/Type/UuidType.php | 6 ++++++ Extension/Core/Type/WeekType.php | 9 +++++++++ .../EventListener/CsrfValidationListener.php | 3 +++ Extension/Csrf/Type/FormTypeCsrfExtension.php | 7 +++++++ .../EventListener/DataCollectorListener.php | 4 ++++ Extension/DataCollector/FormDataCollector.php | 18 +++++++++--------- .../Proxy/ResolvedTypeDataCollectorProxy.php | 9 +++++++++ .../Type/DataCollectorTypeExtension.php | 3 +++ .../Type/TextTypeHtmlSanitizerExtension.php | 6 ++++++ .../HttpFoundationRequestHandler.php | 3 +++ .../Type/FormTypeHttpFoundationExtension.php | 3 +++ .../EventListener/PasswordHasherListener.php | 6 ++++++ .../Type/FormTypePasswordHasherExtension.php | 3 +++ .../PasswordTypePasswordHasherExtension.php | 6 ++++++ .../Validator/Constraints/FormValidator.php | 3 +++ .../EventListener/ValidationListener.php | 3 +++ .../Validator/Type/BaseValidatorExtension.php | 3 +++ .../Type/FormTypeValidatorExtension.php | 6 ++++++ .../Type/RepeatedTypeValidatorExtension.php | 3 +++ .../Type/UploadValidatorExtension.php | 3 +++ .../ViolationMapper/ViolationMapper.php | 3 +++ .../ViolationMapper/ViolationPath.php | 2 +- FormBuilder.php | 2 +- FormConfigBuilder.php | 2 +- FormError.php | 2 ++ FormEvent.php | 2 ++ FormRenderer.php | 3 +++ FormView.php | 3 +++ NativeRequestHandler.php | 2 ++ ResolvedFormType.php | 9 +++++++++ 79 files changed, 399 insertions(+), 19 deletions(-) diff --git a/AbstractExtension.php b/AbstractExtension.php index 5d3c1a8480..cffca7d398 100644 --- a/AbstractExtension.php +++ b/AbstractExtension.php @@ -128,7 +128,7 @@ protected function loadTypeGuesser() * * @throws UnexpectedTypeException if any registered type is not an instance of FormTypeInterface */ - private function initTypes() + private function initTypes(): void { $this->types = []; @@ -147,7 +147,7 @@ private function initTypes() * @throws UnexpectedTypeException if any registered type extension is not * an instance of FormTypeExtensionInterface */ - private function initTypeExtensions() + private function initTypeExtensions(): void { $this->typeExtensions = []; @@ -167,7 +167,7 @@ private function initTypeExtensions() * * @throws UnexpectedTypeException if the type guesser is not an instance of FormTypeGuesserInterface */ - private function initTypeGuesser() + private function initTypeGuesser(): void { $this->typeGuesserLoaded = true; diff --git a/AbstractRendererEngine.php b/AbstractRendererEngine.php index f79f1c1338..3f1ab79c26 100644 --- a/AbstractRendererEngine.php +++ b/AbstractRendererEngine.php @@ -61,6 +61,9 @@ public function __construct(array $defaultThemes = []) $this->defaultThemes = $defaultThemes; } + /** + * @return void + */ public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true) { $cacheKey = $view->vars[self::CACHE_KEY_VAR]; diff --git a/AbstractType.php b/AbstractType.php index da401930d7..b163506132 100644 --- a/AbstractType.php +++ b/AbstractType.php @@ -20,18 +20,30 @@ */ abstract class AbstractType implements FormTypeInterface { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { } + /** + * @return void + */ public function finishView(FormView $view, FormInterface $form, array $options) { } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { } diff --git a/AbstractTypeExtension.php b/AbstractTypeExtension.php index bcd408c170..422f28bf33 100644 --- a/AbstractTypeExtension.php +++ b/AbstractTypeExtension.php @@ -18,18 +18,30 @@ */ abstract class AbstractTypeExtension implements FormTypeExtensionInterface { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { } + /** + * @return void + */ public function finishView(FormView $view, FormInterface $form, array $options) { } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { } diff --git a/ChoiceList/ArrayChoiceList.php b/ChoiceList/ArrayChoiceList.php index 8c25c19ccf..ef09ca5837 100644 --- a/ChoiceList/ArrayChoiceList.php +++ b/ChoiceList/ArrayChoiceList.php @@ -162,7 +162,7 @@ public function getValuesForChoices(array $choices): array * * @internal */ - protected function flatten(array $choices, callable $value, ?array &$choicesByValues, ?array &$keysByValues, ?array &$structuredValues) + protected function flatten(array $choices, callable $value, ?array &$choicesByValues, ?array &$keysByValues, ?array &$structuredValues): void { if (null === $choicesByValues) { $choicesByValues = []; diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index 62d1b71d9d..304105cbc2 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -214,6 +214,9 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = return $this->views[$hash]; } + /** + * @return void + */ public function reset() { $this->lists = []; diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index c417b84ac5..b5b8337047 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -140,7 +140,7 @@ public function createView(ChoiceListInterface $list, array|callable $preferredC return new ChoiceListView($otherViews, $preferredViews); } - private static function addChoiceView($choice, string $value, $label, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews) + private static function addChoiceView($choice, string $value, $label, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews): void { // $value may be an integer or a string, since it's stored in the array // keys. We want to guarantee it's a string though. @@ -186,7 +186,7 @@ private static function addChoiceView($choice, string $value, $label, array $key $otherViews[$nextIndex] = $view; } - private static function addChoiceViewsFromStructuredValues(array $values, $label, array $choices, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews) + private static function addChoiceViewsFromStructuredValues(array $values, $label, array $choices, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews): void { foreach ($values as $key => $value) { if (null === $value) { @@ -240,7 +240,7 @@ private static function addChoiceViewsFromStructuredValues(array $values, $label } } - private static function addChoiceViewsGroupedByCallable(callable $groupBy, $choice, string $value, $label, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews) + private static function addChoiceViewsGroupedByCallable(callable $groupBy, $choice, string $value, $label, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews): void { $groupLabels = $groupBy($choice, $keys[$value], $value); diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index a4975470c9..9b6b830341 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -54,6 +54,9 @@ public function __construct(FormRegistryInterface $formRegistry, array $namespac $this->fileLinkFormatter = $fileLinkFormatter; } + /** + * @return void + */ protected function configure() { $this diff --git a/DependencyInjection/FormPass.php b/DependencyInjection/FormPass.php index cba1aeeb2c..efb6d5c8bb 100644 --- a/DependencyInjection/FormPass.php +++ b/DependencyInjection/FormPass.php @@ -30,6 +30,9 @@ class FormPass implements CompilerPassInterface { use PriorityTaggedServiceTrait; + /** + * @return void + */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition('form.extension')) { diff --git a/Extension/Core/DataMapper/CheckboxListMapper.php b/Extension/Core/DataMapper/CheckboxListMapper.php index 2345138112..119c81107d 100644 --- a/Extension/Core/DataMapper/CheckboxListMapper.php +++ b/Extension/Core/DataMapper/CheckboxListMapper.php @@ -25,6 +25,9 @@ */ class CheckboxListMapper implements DataMapperInterface { + /** + * @return void + */ public function mapDataToForms(mixed $choices, \Traversable $checkboxes) { if (!\is_array($choices ??= [])) { @@ -37,6 +40,9 @@ public function mapDataToForms(mixed $choices, \Traversable $checkboxes) } } + /** + * @return void + */ public function mapFormsToData(\Traversable $checkboxes, mixed &$choices) { if (!\is_array($choices)) { diff --git a/Extension/Core/DataMapper/RadioListMapper.php b/Extension/Core/DataMapper/RadioListMapper.php index 4ae0fc3c8f..37fdba0c35 100644 --- a/Extension/Core/DataMapper/RadioListMapper.php +++ b/Extension/Core/DataMapper/RadioListMapper.php @@ -25,6 +25,9 @@ */ class RadioListMapper implements DataMapperInterface { + /** + * @return void + */ public function mapDataToForms(mixed $choice, \Traversable $radios) { if (!\is_string($choice)) { @@ -37,6 +40,9 @@ public function mapDataToForms(mixed $choice, \Traversable $radios) } } + /** + * @return void + */ public function mapFormsToData(\Traversable $radios, mixed &$choice) { if (null !== $choice && !\is_string($choice)) { diff --git a/Extension/Core/EventListener/FixUrlProtocolListener.php b/Extension/Core/EventListener/FixUrlProtocolListener.php index e9288da415..7189977549 100644 --- a/Extension/Core/EventListener/FixUrlProtocolListener.php +++ b/Extension/Core/EventListener/FixUrlProtocolListener.php @@ -32,6 +32,9 @@ public function __construct(?string $defaultProtocol = 'http') $this->defaultProtocol = $defaultProtocol; } + /** + * @return void + */ public function onSubmit(FormEvent $event) { $data = $event->getData(); diff --git a/Extension/Core/EventListener/MergeCollectionListener.php b/Extension/Core/EventListener/MergeCollectionListener.php index 4f77342f90..62cd0a42a7 100644 --- a/Extension/Core/EventListener/MergeCollectionListener.php +++ b/Extension/Core/EventListener/MergeCollectionListener.php @@ -41,6 +41,9 @@ public static function getSubscribedEvents(): array ]; } + /** + * @return void + */ public function onSubmit(FormEvent $event) { $dataToMergeInto = $event->getForm()->getNormData(); diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index a524e15574..4c06342e54 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -50,6 +50,9 @@ public static function getSubscribedEvents(): array ]; } + /** + * @return void + */ public function preSetData(FormEvent $event) { $form = $event->getForm(); @@ -72,6 +75,9 @@ public function preSetData(FormEvent $event) } } + /** + * @return void + */ public function preSubmit(FormEvent $event) { $form = $event->getForm(); @@ -102,6 +108,9 @@ public function preSubmit(FormEvent $event) } } + /** + * @return void + */ public function onSubmit(FormEvent $event) { $form = $event->getForm(); diff --git a/Extension/Core/EventListener/TransformationFailureListener.php b/Extension/Core/EventListener/TransformationFailureListener.php index 090a27158d..c9c216b59f 100644 --- a/Extension/Core/EventListener/TransformationFailureListener.php +++ b/Extension/Core/EventListener/TransformationFailureListener.php @@ -36,6 +36,9 @@ public static function getSubscribedEvents(): array ]; } + /** + * @return void + */ public function convertTransformationFailureToFormError(FormEvent $event) { $form = $event->getForm(); diff --git a/Extension/Core/EventListener/TrimListener.php b/Extension/Core/EventListener/TrimListener.php index be763c78d2..81a55f3cb0 100644 --- a/Extension/Core/EventListener/TrimListener.php +++ b/Extension/Core/EventListener/TrimListener.php @@ -23,6 +23,9 @@ */ class TrimListener implements EventSubscriberInterface { + /** + * @return void + */ public function preSubmit(FormEvent $event) { $data = $event->getData(); diff --git a/Extension/Core/Type/BaseType.php b/Extension/Core/Type/BaseType.php index 0bc3ebe943..5e2ae22481 100644 --- a/Extension/Core/Type/BaseType.php +++ b/Extension/Core/Type/BaseType.php @@ -29,12 +29,18 @@ */ abstract class BaseType extends AbstractType { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->setDisabled($options['disabled']); $builder->setAutoInitialize($options['auto_initialize']); } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $name = $form->getName(); @@ -119,6 +125,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/BirthdayType.php b/Extension/Core/Type/BirthdayType.php index 1be317ebd3..fa60d016eb 100644 --- a/Extension/Core/Type/BirthdayType.php +++ b/Extension/Core/Type/BirthdayType.php @@ -16,6 +16,9 @@ class BirthdayType extends AbstractType { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/ButtonType.php b/Extension/Core/Type/ButtonType.php index ee39cee56b..d710546407 100644 --- a/Extension/Core/Type/ButtonType.php +++ b/Extension/Core/Type/ButtonType.php @@ -31,6 +31,9 @@ public function getBlockPrefix(): string return 'button'; } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); diff --git a/Extension/Core/Type/CheckboxType.php b/Extension/Core/Type/CheckboxType.php index b9f5c3f478..b261f926bb 100644 --- a/Extension/Core/Type/CheckboxType.php +++ b/Extension/Core/Type/CheckboxType.php @@ -20,6 +20,9 @@ class CheckboxType extends AbstractType { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { // Unlike in other types, where the data is NULL by default, it @@ -32,6 +35,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) $builder->addViewTransformer(new BooleanToStringTransformer($options['value'], $options['false_values'])); } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars = array_replace($view->vars, [ @@ -40,6 +46,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $emptyData = fn (FormInterface $form, $viewData) => $viewData; diff --git a/Extension/Core/Type/CollectionType.php b/Extension/Core/Type/CollectionType.php index c310441cc7..1654d379a8 100644 --- a/Extension/Core/Type/CollectionType.php +++ b/Extension/Core/Type/CollectionType.php @@ -21,6 +21,9 @@ class CollectionType extends AbstractType { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { if ($options['allow_add'] && $options['prototype']) { @@ -48,6 +51,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) $builder->addEventSubscriber($resizeListener); } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars = array_replace($view->vars, [ @@ -61,6 +67,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function finishView(FormView $view, FormInterface $form, array $options) { $prefixOffset = -2; @@ -92,6 +101,9 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $entryOptionsNormalizer = function (Options $options, $value) { diff --git a/Extension/Core/Type/ColorType.php b/Extension/Core/Type/ColorType.php index 26d670634b..6e205fcbc9 100644 --- a/Extension/Core/Type/ColorType.php +++ b/Extension/Core/Type/ColorType.php @@ -33,6 +33,9 @@ public function __construct(TranslatorInterface $translator = null) $this->translator = $translator; } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { if (!$options['html5']) { @@ -59,6 +62,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) }); } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/CountryType.php b/Extension/Core/Type/CountryType.php index 69f284c823..b647284904 100644 --- a/Extension/Core/Type/CountryType.php +++ b/Extension/Core/Type/CountryType.php @@ -22,6 +22,9 @@ class CountryType extends AbstractType { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/CurrencyType.php b/Extension/Core/Type/CurrencyType.php index f697f35416..1c0ac471b8 100644 --- a/Extension/Core/Type/CurrencyType.php +++ b/Extension/Core/Type/CurrencyType.php @@ -22,6 +22,9 @@ class CurrencyType extends AbstractType { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/DateIntervalType.php b/Extension/Core/Type/DateIntervalType.php index db1a14b52b..0e4a7555a0 100644 --- a/Extension/Core/Type/DateIntervalType.php +++ b/Extension/Core/Type/DateIntervalType.php @@ -43,6 +43,9 @@ class DateIntervalType extends AbstractType 'choice' => ChoiceType::class, ]; + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { if (!$options['with_years'] && !$options['with_months'] && !$options['with_weeks'] && !$options['with_days'] && !$options['with_hours'] && !$options['with_minutes'] && !$options['with_seconds']) { @@ -145,6 +148,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $vars = [ @@ -157,6 +163,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) $view->vars = array_replace($view->vars, $vars); } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $compound = fn (Options $options) => 'single_text' !== $options['widget']; diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index bf7a734a9b..ae47519c53 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -47,6 +47,9 @@ class DateTimeType extends AbstractType \IntlDateFormatter::SHORT, ]; + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $parts = ['year', 'month', 'day', 'hour']; @@ -197,6 +200,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['widget'] = $options['widget']; @@ -218,6 +224,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $compound = fn (Options $options) => 'single_text' !== $options['widget']; diff --git a/Extension/Core/Type/EmailType.php b/Extension/Core/Type/EmailType.php index 70e8c8a191..64d01ee67a 100644 --- a/Extension/Core/Type/EmailType.php +++ b/Extension/Core/Type/EmailType.php @@ -16,6 +16,9 @@ class EmailType extends AbstractType { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index 3bd04a374d..560d1e2cb3 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -38,6 +38,9 @@ public function __construct(PropertyAccessorInterface $propertyAccessor = null) ])); } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); @@ -66,6 +69,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) $builder->setIsEmptyCallback($options['is_empty_callback']); } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { parent::buildView($view, $form, $options); @@ -105,6 +111,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } + /** + * @return void + */ public function finishView(FormView $view, FormInterface $form, array $options) { $multipart = false; @@ -119,6 +128,9 @@ public function finishView(FormView $view, FormInterface $form, array $options) $view->vars['multipart'] = $multipart; } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); diff --git a/Extension/Core/Type/HiddenType.php b/Extension/Core/Type/HiddenType.php index a69e172bc6..c4e5eb2ccf 100644 --- a/Extension/Core/Type/HiddenType.php +++ b/Extension/Core/Type/HiddenType.php @@ -16,6 +16,9 @@ class HiddenType extends AbstractType { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/IntegerType.php b/Extension/Core/Type/IntegerType.php index 49e37f7490..a287b66b7c 100644 --- a/Extension/Core/Type/IntegerType.php +++ b/Extension/Core/Type/IntegerType.php @@ -20,11 +20,17 @@ class IntegerType extends AbstractType { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addViewTransformer(new IntegerToLocalizedStringTransformer($options['grouping'], $options['rounding_mode'], !$options['grouping'] ? 'en' : null)); } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { if ($options['grouping']) { @@ -32,6 +38,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/LanguageType.php b/Extension/Core/Type/LanguageType.php index f875657eaa..0c6faafec6 100644 --- a/Extension/Core/Type/LanguageType.php +++ b/Extension/Core/Type/LanguageType.php @@ -23,6 +23,9 @@ class LanguageType extends AbstractType { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/LocaleType.php b/Extension/Core/Type/LocaleType.php index 0cdde9e46b..5086b0b0e6 100644 --- a/Extension/Core/Type/LocaleType.php +++ b/Extension/Core/Type/LocaleType.php @@ -22,6 +22,9 @@ class LocaleType extends AbstractType { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/MoneyType.php b/Extension/Core/Type/MoneyType.php index e9ecd409eb..aea35410c1 100644 --- a/Extension/Core/Type/MoneyType.php +++ b/Extension/Core/Type/MoneyType.php @@ -24,6 +24,9 @@ class MoneyType extends AbstractType { protected static $patterns = []; + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { // Values used in HTML5 number inputs should be formatted as in "1234.5", ie. 'en' format without grouping, @@ -39,6 +42,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['money_pattern'] = self::getPattern($options['currency']); @@ -48,6 +54,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/NumberType.php b/Extension/Core/Type/NumberType.php index 6d2d9eca2e..c1b5f3e627 100644 --- a/Extension/Core/Type/NumberType.php +++ b/Extension/Core/Type/NumberType.php @@ -23,6 +23,9 @@ class NumberType extends AbstractType { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addViewTransformer(new NumberToLocalizedStringTransformer( @@ -37,6 +40,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { if ($options['html5']) { @@ -46,6 +52,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/PasswordType.php b/Extension/Core/Type/PasswordType.php index 495160361d..0c247f0f30 100644 --- a/Extension/Core/Type/PasswordType.php +++ b/Extension/Core/Type/PasswordType.php @@ -18,6 +18,9 @@ class PasswordType extends AbstractType { + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { if ($options['always_empty'] || !$form->isSubmitted()) { @@ -25,6 +28,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/PercentType.php b/Extension/Core/Type/PercentType.php index d006c6d5e1..f71e288b3e 100644 --- a/Extension/Core/Type/PercentType.php +++ b/Extension/Core/Type/PercentType.php @@ -20,6 +20,9 @@ class PercentType extends AbstractType { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addViewTransformer(new PercentToLocalizedStringTransformer( @@ -30,6 +33,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) )); } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['symbol'] = $options['symbol']; @@ -39,6 +45,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/RadioType.php b/Extension/Core/Type/RadioType.php index d40f39106d..4b97b0ae21 100644 --- a/Extension/Core/Type/RadioType.php +++ b/Extension/Core/Type/RadioType.php @@ -16,6 +16,9 @@ class RadioType extends AbstractType { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/RangeType.php b/Extension/Core/Type/RangeType.php index 857028c9c1..2e33a977d9 100644 --- a/Extension/Core/Type/RangeType.php +++ b/Extension/Core/Type/RangeType.php @@ -16,6 +16,9 @@ class RangeType extends AbstractType { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/RepeatedType.php b/Extension/Core/Type/RepeatedType.php index fb55bf2940..4176f93e52 100644 --- a/Extension/Core/Type/RepeatedType.php +++ b/Extension/Core/Type/RepeatedType.php @@ -18,6 +18,9 @@ class RepeatedType extends AbstractType { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { // Overwrite required option for child fields @@ -41,6 +44,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/SearchType.php b/Extension/Core/Type/SearchType.php index 76ed420118..0dca6e42a8 100644 --- a/Extension/Core/Type/SearchType.php +++ b/Extension/Core/Type/SearchType.php @@ -16,6 +16,9 @@ class SearchType extends AbstractType { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/SubmitType.php b/Extension/Core/Type/SubmitType.php index dde4457652..3f1b5f95c9 100644 --- a/Extension/Core/Type/SubmitType.php +++ b/Extension/Core/Type/SubmitType.php @@ -24,6 +24,9 @@ */ class SubmitType extends AbstractType implements SubmitButtonTypeInterface { + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['clicked'] = $form->isClicked(); @@ -33,6 +36,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefault('validate', true); diff --git a/Extension/Core/Type/TelType.php b/Extension/Core/Type/TelType.php index 8ba7fd843b..05fdd41626 100644 --- a/Extension/Core/Type/TelType.php +++ b/Extension/Core/Type/TelType.php @@ -16,6 +16,9 @@ class TelType extends AbstractType { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/TextType.php b/Extension/Core/Type/TextType.php index dd019192bc..479ce054d8 100644 --- a/Extension/Core/Type/TextType.php +++ b/Extension/Core/Type/TextType.php @@ -18,6 +18,9 @@ class TextType extends AbstractType implements DataTransformerInterface { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { // When empty_data is explicitly set to an empty string, @@ -30,6 +33,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/TextareaType.php b/Extension/Core/Type/TextareaType.php index 43d8e0eac4..40e7580d80 100644 --- a/Extension/Core/Type/TextareaType.php +++ b/Extension/Core/Type/TextareaType.php @@ -17,6 +17,9 @@ class TextareaType extends AbstractType { + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['pattern'] = null; diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 78929d79bf..a22f2122cd 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -34,6 +34,9 @@ class TimeType extends AbstractType 'choice' => ChoiceType::class, ]; + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $parts = ['hour']; @@ -207,6 +210,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars = array_replace($view->vars, [ @@ -231,6 +237,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $compound = fn (Options $options) => 'single_text' !== $options['widget']; diff --git a/Extension/Core/Type/TimezoneType.php b/Extension/Core/Type/TimezoneType.php index d6ce3c3435..0827fcfc5a 100644 --- a/Extension/Core/Type/TimezoneType.php +++ b/Extension/Core/Type/TimezoneType.php @@ -25,6 +25,9 @@ class TimezoneType extends AbstractType { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { if ('datetimezone' === $options['input']) { @@ -34,6 +37,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/TransformationFailureExtension.php b/Extension/Core/Type/TransformationFailureExtension.php index 4fb9cae664..029ad4d439 100644 --- a/Extension/Core/Type/TransformationFailureExtension.php +++ b/Extension/Core/Type/TransformationFailureExtension.php @@ -28,6 +28,9 @@ public function __construct(TranslatorInterface $translator = null) $this->translator = $translator; } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { if (!isset($options['constraints'])) { diff --git a/Extension/Core/Type/UlidType.php b/Extension/Core/Type/UlidType.php index 24eab77d8e..ea3da07c02 100644 --- a/Extension/Core/Type/UlidType.php +++ b/Extension/Core/Type/UlidType.php @@ -21,6 +21,9 @@ */ class UlidType extends AbstractType { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder @@ -28,6 +31,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/UrlType.php b/Extension/Core/Type/UrlType.php index 313fbedbf5..385c7a25fa 100644 --- a/Extension/Core/Type/UrlType.php +++ b/Extension/Core/Type/UrlType.php @@ -20,6 +20,9 @@ class UrlType extends AbstractType { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { if (null !== $options['default_protocol']) { @@ -27,6 +30,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { if ($options['default_protocol']) { @@ -35,6 +41,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/UuidType.php b/Extension/Core/Type/UuidType.php index 214d308689..7c0f65b9a0 100644 --- a/Extension/Core/Type/UuidType.php +++ b/Extension/Core/Type/UuidType.php @@ -21,6 +21,9 @@ */ class UuidType extends AbstractType { + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder @@ -28,6 +31,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Core/Type/WeekType.php b/Extension/Core/Type/WeekType.php index 5b05e0a310..f0d8f96467 100644 --- a/Extension/Core/Type/WeekType.php +++ b/Extension/Core/Type/WeekType.php @@ -28,6 +28,9 @@ class WeekType extends AbstractType 'choice' => ChoiceType::class, ]; + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { if ('string' === $options['input']) { @@ -80,6 +83,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $view->vars['widget'] = $options['widget']; @@ -89,6 +95,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $compound = fn (Options $options) => 'single_text' !== $options['widget']; diff --git a/Extension/Csrf/EventListener/CsrfValidationListener.php b/Extension/Csrf/EventListener/CsrfValidationListener.php index 732b036de1..eca450a165 100644 --- a/Extension/Csrf/EventListener/CsrfValidationListener.php +++ b/Extension/Csrf/EventListener/CsrfValidationListener.php @@ -51,6 +51,9 @@ public function __construct(string $fieldName, CsrfTokenManagerInterface $tokenM $this->serverParams = $serverParams ?? new ServerParams(); } + /** + * @return void + */ public function preSubmit(FormEvent $event) { $form = $event->getForm(); diff --git a/Extension/Csrf/Type/FormTypeCsrfExtension.php b/Extension/Csrf/Type/FormTypeCsrfExtension.php index bb0d04f509..8c3d45dec0 100644 --- a/Extension/Csrf/Type/FormTypeCsrfExtension.php +++ b/Extension/Csrf/Type/FormTypeCsrfExtension.php @@ -47,6 +47,8 @@ public function __construct(CsrfTokenManagerInterface $defaultTokenManager, bool /** * Adds a CSRF field to the form when the CSRF protection is enabled. + * + * @return void */ public function buildForm(FormBuilderInterface $builder, array $options) { @@ -69,6 +71,8 @@ public function buildForm(FormBuilderInterface $builder, array $options) /** * Adds a CSRF field to the root form view. + * + * @return void */ public function finishView(FormView $view, FormInterface $form, array $options) { @@ -86,6 +90,9 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/DataCollector/EventListener/DataCollectorListener.php b/Extension/DataCollector/EventListener/DataCollectorListener.php index be30912c7c..41a52e091e 100644 --- a/Extension/DataCollector/EventListener/DataCollectorListener.php +++ b/Extension/DataCollector/EventListener/DataCollectorListener.php @@ -43,6 +43,8 @@ public static function getSubscribedEvents(): array /** * Listener for the {@link FormEvents::POST_SET_DATA} event. + * + * @return void */ public function postSetData(FormEvent $event) { @@ -57,6 +59,8 @@ public function postSetData(FormEvent $event) /** * Listener for the {@link FormEvents::POST_SUBMIT} event. + * + * @return void */ public function postSubmit(FormEvent $event) { diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index cdc13c9d03..b93bfd82a1 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -76,11 +76,11 @@ public function __construct(FormDataExtractorInterface $dataExtractor) /** * Does nothing. The data is collected during the form event listeners. */ - public function collect(Request $request, Response $response, \Throwable $exception = null) + public function collect(Request $request, Response $response, \Throwable $exception = null): void { } - public function reset() + public function reset(): void { $this->data = [ 'forms' => [], @@ -89,12 +89,12 @@ public function reset() ]; } - public function associateFormWithView(FormInterface $form, FormView $view) + public function associateFormWithView(FormInterface $form, FormView $view): void { $this->formsByView[spl_object_hash($view)] = spl_object_hash($form); } - public function collectConfiguration(FormInterface $form) + public function collectConfiguration(FormInterface $form): void { $hash = spl_object_hash($form); @@ -112,7 +112,7 @@ public function collectConfiguration(FormInterface $form) } } - public function collectDefaultData(FormInterface $form) + public function collectDefaultData(FormInterface $form): void { $hash = spl_object_hash($form); @@ -131,7 +131,7 @@ public function collectDefaultData(FormInterface $form) } } - public function collectSubmittedData(FormInterface $form) + public function collectSubmittedData(FormInterface $form): void { $hash = spl_object_hash($form); @@ -162,7 +162,7 @@ public function collectSubmittedData(FormInterface $form) } } - public function collectViewVariables(FormView $view) + public function collectViewVariables(FormView $view): void { $hash = spl_object_hash($view); @@ -180,12 +180,12 @@ public function collectViewVariables(FormView $view) } } - public function buildPreliminaryFormTree(FormInterface $form) + public function buildPreliminaryFormTree(FormInterface $form): void { $this->data['forms'][$form->getName()] = &$this->recursiveBuildPreliminaryFormTree($form, $this->data['forms_by_hash']); } - public function buildFinalFormTree(FormInterface $form, FormView $view) + public function buildFinalFormTree(FormInterface $form, FormView $view): void { $this->data['forms'][$form->getName()] = &$this->recursiveBuildFinalFormTree($form, $view, $this->data['forms_by_hash']); } diff --git a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php index d273fbbc75..6c8cf3ee24 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php @@ -71,16 +71,25 @@ public function createView(FormInterface $form, FormView $parent = null): FormVi return $this->proxiedType->createView($form, $parent); } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $this->proxiedType->buildForm($builder, $options); } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $this->proxiedType->buildView($view, $form, $options); } + /** + * @return void + */ public function finishView(FormView $view, FormInterface $form, array $options) { $this->proxiedType->finishView($view, $form, $options); diff --git a/Extension/DataCollector/Type/DataCollectorTypeExtension.php b/Extension/DataCollector/Type/DataCollectorTypeExtension.php index d014f0e457..f1e3c903ec 100644 --- a/Extension/DataCollector/Type/DataCollectorTypeExtension.php +++ b/Extension/DataCollector/Type/DataCollectorTypeExtension.php @@ -32,6 +32,9 @@ public function __construct(FormDataCollectorInterface $dataCollector) $this->listener = new DataCollectorListener($dataCollector); } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventSubscriber($this->listener); diff --git a/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php b/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php index 4b2dffe9a1..8e92ea74a5 100644 --- a/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php +++ b/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php @@ -35,6 +35,9 @@ public static function getExtendedTypes(): iterable return [TextType::class]; } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver @@ -44,6 +47,9 @@ public function configureOptions(OptionsResolver $resolver) ; } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { if (!$options['sanitize_html']) { diff --git a/Extension/HttpFoundation/HttpFoundationRequestHandler.php b/Extension/HttpFoundation/HttpFoundationRequestHandler.php index 3b1aaebf02..b4e835c95a 100644 --- a/Extension/HttpFoundation/HttpFoundationRequestHandler.php +++ b/Extension/HttpFoundation/HttpFoundationRequestHandler.php @@ -35,6 +35,9 @@ public function __construct(ServerParams $serverParams = null) $this->serverParams = $serverParams ?? new ServerParams(); } + /** + * @return void + */ public function handleRequest(FormInterface $form, mixed $request = null) { if (!$request instanceof Request) { diff --git a/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php b/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php index 9a5ae66618..cc3e5e1207 100644 --- a/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php +++ b/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php @@ -29,6 +29,9 @@ public function __construct(RequestHandlerInterface $requestHandler = null) $this->requestHandler = $requestHandler ?? new HttpFoundationRequestHandler(); } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->setRequestHandler($this->requestHandler); diff --git a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php index 3fccfd8965..f905a7e034 100644 --- a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php +++ b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php @@ -35,6 +35,9 @@ public function __construct( $this->propertyAccessor ??= PropertyAccess::createPropertyAccessor(); } + /** + * @return void + */ public function registerPassword(FormEvent $event) { $this->assertNotMapped($event->getForm()); @@ -46,6 +49,9 @@ public function registerPassword(FormEvent $event) ]; } + /** + * @return void + */ public function hashPasswords(FormEvent $event) { $form = $event->getForm(); diff --git a/Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php b/Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php index 7294ee5f02..5308992863 100644 --- a/Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php +++ b/Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php @@ -27,6 +27,9 @@ public function __construct( ) { } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventListener(FormEvents::POST_SUBMIT, [$this->passwordHasherListener, 'hashPasswords']); diff --git a/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php b/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php index e75a6e9ff2..6f022fb1bf 100644 --- a/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php +++ b/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php @@ -29,6 +29,9 @@ public function __construct( ) { } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { if ($options['hash_property_path']) { @@ -36,6 +39,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ diff --git a/Extension/Validator/Constraints/FormValidator.php b/Extension/Validator/Constraints/FormValidator.php index ada84f14bf..d664e9b500 100644 --- a/Extension/Validator/Constraints/FormValidator.php +++ b/Extension/Validator/Constraints/FormValidator.php @@ -29,6 +29,9 @@ class FormValidator extends ConstraintValidator */ private \SplObjectStorage $resolvedGroups; + /** + * @return void + */ public function validate(mixed $form, Constraint $formConstraint) { if (!$formConstraint instanceof Form) { diff --git a/Extension/Validator/EventListener/ValidationListener.php b/Extension/Validator/EventListener/ValidationListener.php index 2963d6f7b0..e2d4357622 100644 --- a/Extension/Validator/EventListener/ValidationListener.php +++ b/Extension/Validator/EventListener/ValidationListener.php @@ -37,6 +37,9 @@ public function __construct(ValidatorInterface $validator, ViolationMapperInterf $this->violationMapper = $violationMapper; } + /** + * @return void + */ public function validateForm(FormEvent $event) { $form = $event->getForm(); diff --git a/Extension/Validator/Type/BaseValidatorExtension.php b/Extension/Validator/Type/BaseValidatorExtension.php index 9366a20f89..2abc466fe3 100644 --- a/Extension/Validator/Type/BaseValidatorExtension.php +++ b/Extension/Validator/Type/BaseValidatorExtension.php @@ -24,6 +24,9 @@ */ abstract class BaseValidatorExtension extends AbstractTypeExtension { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { // Make sure that validation groups end up as null, closure or array diff --git a/Extension/Validator/Type/FormTypeValidatorExtension.php b/Extension/Validator/Type/FormTypeValidatorExtension.php index b28cf870b0..4602918c3a 100644 --- a/Extension/Validator/Type/FormTypeValidatorExtension.php +++ b/Extension/Validator/Type/FormTypeValidatorExtension.php @@ -37,11 +37,17 @@ public function __construct(ValidatorInterface $validator, bool $legacyErrorMess $this->violationMapper = new ViolationMapper($formRenderer, $translator); } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventSubscriber(new ValidationListener($this->validator, $this->violationMapper)); } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); diff --git a/Extension/Validator/Type/RepeatedTypeValidatorExtension.php b/Extension/Validator/Type/RepeatedTypeValidatorExtension.php index 0e8a4ccf14..2e2c21426a 100644 --- a/Extension/Validator/Type/RepeatedTypeValidatorExtension.php +++ b/Extension/Validator/Type/RepeatedTypeValidatorExtension.php @@ -21,6 +21,9 @@ */ class RepeatedTypeValidatorExtension extends AbstractTypeExtension { + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { // Map errors to the first field diff --git a/Extension/Validator/Type/UploadValidatorExtension.php b/Extension/Validator/Type/UploadValidatorExtension.php index c720e6a0ec..70034135bf 100644 --- a/Extension/Validator/Type/UploadValidatorExtension.php +++ b/Extension/Validator/Type/UploadValidatorExtension.php @@ -32,6 +32,9 @@ public function __construct(TranslatorInterface $translator, string $translation $this->translationDomain = $translationDomain; } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $translator = $this->translator; diff --git a/Extension/Validator/ViolationMapper/ViolationMapper.php b/Extension/Validator/ViolationMapper/ViolationMapper.php index e6bcd29fea..2f2ccefd30 100644 --- a/Extension/Validator/ViolationMapper/ViolationMapper.php +++ b/Extension/Validator/ViolationMapper/ViolationMapper.php @@ -38,6 +38,9 @@ public function __construct(FormRendererInterface $formRenderer = null, Translat $this->translator = $translator; } + /** + * @return void + */ public function mapViolation(ConstraintViolation $violation, FormInterface $form, bool $allowNonSynchronized = false) { $this->allowNonSynchronized = $allowNonSynchronized; diff --git a/Extension/Validator/ViolationMapper/ViolationPath.php b/Extension/Validator/ViolationMapper/ViolationPath.php index a597dcb139..a9a0f15d6e 100644 --- a/Extension/Validator/ViolationMapper/ViolationPath.php +++ b/Extension/Validator/ViolationMapper/ViolationPath.php @@ -193,7 +193,7 @@ public function getIterator(): ViolationPathIterator /** * Builds the string representation from the elements. */ - private function buildString() + private function buildString(): void { $this->pathAsString = ''; $data = false; diff --git a/FormBuilder.php b/FormBuilder.php index c6215635ec..33f07b0f1d 100644 --- a/FormBuilder.php +++ b/FormBuilder.php @@ -206,7 +206,7 @@ private function resolveChild(string $name): FormBuilderInterface /** * Converts all unresolved children into {@link FormBuilder} instances. */ - private function resolveChildren() + private function resolveChildren(): void { foreach ($this->unresolvedChildren as $name => $info) { $this->children[$name] = $this->create($name, $info[0], $info[1]); diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 0220399758..9fed3d1a0a 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -633,7 +633,7 @@ public function setIsEmptyCallback(?callable $isEmptyCallback): static * * @internal */ - final public static function validateName(?string $name) + final public static function validateName(?string $name): void { if (!self::isValidName($name)) { throw new InvalidArgumentException(sprintf('The name "%s" contains illegal characters. Names should start with a letter, digit or underscore and only contain letters, digits, numbers, underscores ("_"), hyphens ("-") and colons (":").', $name)); diff --git a/FormError.php b/FormError.php index aafd723f22..5b19d6ea5b 100644 --- a/FormError.php +++ b/FormError.php @@ -100,6 +100,8 @@ public function getCause(): mixed * This method must only be called once. * * @throws BadMethodCallException If the method is called more than once + * + * @return void */ public function setOrigin(FormInterface $origin) { diff --git a/FormEvent.php b/FormEvent.php index c9c3053cfe..1e6aa34d63 100644 --- a/FormEvent.php +++ b/FormEvent.php @@ -45,6 +45,8 @@ public function getData(): mixed /** * Allows updating with some filtered data. + * + * @return void */ public function setData(mixed $data) { diff --git a/FormRenderer.php b/FormRenderer.php index 12c7c0dddd..18dec4946b 100644 --- a/FormRenderer.php +++ b/FormRenderer.php @@ -42,6 +42,9 @@ public function getEngine(): FormRendererEngineInterface return $this->engine; } + /** + * @return void + */ public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true) { $this->engine->setTheme($view, $themes, $useDefaultThemes); diff --git a/FormView.php b/FormView.php index fe32f90cef..e04fa13b09 100644 --- a/FormView.php +++ b/FormView.php @@ -92,6 +92,9 @@ public function isMethodRendered(): bool return $this->methodRendered; } + /** + * @return void + */ public function setMethodRendered() { $this->methodRendered = true; diff --git a/NativeRequestHandler.php b/NativeRequestHandler.php index cf193398c8..bf240de37e 100644 --- a/NativeRequestHandler.php +++ b/NativeRequestHandler.php @@ -41,6 +41,8 @@ public function __construct(ServerParams $params = null) /** * @throws Exception\UnexpectedTypeException If the $request is not null + * + * @return void */ public function handleRequest(FormInterface $form, mixed $request = null) { diff --git a/ResolvedFormType.php b/ResolvedFormType.php index af794a3b7c..f05db1533b 100644 --- a/ResolvedFormType.php +++ b/ResolvedFormType.php @@ -92,6 +92,9 @@ public function createView(FormInterface $form, FormView $parent = null): FormVi return $this->newView($parent); } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $this->parent?->buildForm($builder, $options); @@ -103,6 +106,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $this->parent?->buildView($view, $form, $options); @@ -114,6 +120,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function finishView(FormView $view, FormInterface $form, array $options) { $this->parent?->finishView($view, $form, $options); From 3494dfea4332118cbe91da3fc2a743f8d8d2d6fb Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Wed, 15 Feb 2023 00:58:54 +0100 Subject: [PATCH 085/208] Add missing return types to interfaces --- FormTypeInterface.php | 8 ++++++++ Tests/Command/DebugCommandTest.php | 2 +- .../Descriptor/AbstractDescriptorTestCase.php | 2 +- .../Csrf/Type/FormTypeCsrfExtensionTest.php | 2 +- .../FormValidatorFunctionalTest.php | 18 +++++++++--------- Tests/Fixtures/AlternatingRowType.php | 2 +- Tests/Fixtures/AuthorType.php | 4 ++-- Tests/Fixtures/BlockPrefixedFooTextType.php | 2 +- Tests/Fixtures/ChoiceSubType.php | 2 +- Tests/Fixtures/ChoiceTypeExtension.php | 2 +- Tests/Fixtures/FooTypeBarExtension.php | 4 ++-- Tests/Fixtures/FooTypeBazExtension.php | 2 +- Tests/Fixtures/LazyChoiceTypeExtension.php | 2 +- Tests/Fixtures/NotMappedType.php | 2 +- 14 files changed, 31 insertions(+), 23 deletions(-) diff --git a/FormTypeInterface.php b/FormTypeInterface.php index 2b9066a511..0c586d3f71 100644 --- a/FormTypeInterface.php +++ b/FormTypeInterface.php @@ -26,6 +26,8 @@ interface FormTypeInterface * * @param array $options * + * @return void + * * @see FormTypeExtensionInterface::buildForm() */ public function buildForm(FormBuilderInterface $builder, array $options); @@ -42,6 +44,8 @@ public function buildForm(FormBuilderInterface $builder, array $options); * * @param array $options * + * @return void + * * @see FormTypeExtensionInterface::buildView() */ public function buildView(FormView $view, FormInterface $form, array $options); @@ -59,12 +63,16 @@ public function buildView(FormView $view, FormInterface $form, array $options); * * @param array $options * + * @return void + * * @see FormTypeExtensionInterface::finishView() */ public function finishView(FormView $view, FormInterface $form, array $options); /** * Configures the options for this type. + * + * @return void */ public function configureOptions(OptionsResolver $resolver); diff --git a/Tests/Command/DebugCommandTest.php b/Tests/Command/DebugCommandTest.php index 9cc1025fc7..4537099c2d 100644 --- a/Tests/Command/DebugCommandTest.php +++ b/Tests/Command/DebugCommandTest.php @@ -284,7 +284,7 @@ private function createCommandTester(array $namespaces = ['Symfony\Component\For class FooType extends AbstractType { - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setRequired('foo'); $resolver->setDefined('bar'); diff --git a/Tests/Console/Descriptor/AbstractDescriptorTestCase.php b/Tests/Console/Descriptor/AbstractDescriptorTestCase.php index 33641f23d8..3201ab9f72 100644 --- a/Tests/Console/Descriptor/AbstractDescriptorTestCase.php +++ b/Tests/Console/Descriptor/AbstractDescriptorTestCase.php @@ -159,7 +159,7 @@ private function getFixtureFilename($name) class FooType extends AbstractType { - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setRequired('foo'); $resolver->setDefined('bar'); diff --git a/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php b/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php index 7fcc80fee7..81418527ee 100644 --- a/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php +++ b/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php @@ -23,7 +23,7 @@ class FormTypeCsrfExtensionTest_ChildType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { // The form needs a child in order to trigger CSRF protection by // default diff --git a/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php b/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php index f712805e00..e1698e6b9b 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php @@ -486,7 +486,7 @@ class Foo public $bar; public $baz; - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('bar', new NotBlank()); } @@ -494,7 +494,7 @@ public static function loadValidatorMetadata(ClassMetadata $metadata) class FooType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('bar') @@ -504,7 +504,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('data_class', Foo::class); } @@ -516,7 +516,7 @@ class Review public $title; public $author; - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('title', new NotBlank()); $metadata->addPropertyConstraint('rating', new NotBlank()); @@ -525,7 +525,7 @@ public static function loadValidatorMetadata(ClassMetadata $metadata) class ReviewType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('rating', IntegerType::class, [ @@ -538,7 +538,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('data_class', Review::class); } @@ -548,7 +548,7 @@ class Customer { public $email; - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('email', new NotBlank()); } @@ -556,14 +556,14 @@ public static function loadValidatorMetadata(ClassMetadata $metadata) class CustomerType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('email') ; } - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('data_class', Customer::class); } diff --git a/Tests/Fixtures/AlternatingRowType.php b/Tests/Fixtures/AlternatingRowType.php index 556166f554..3e0bb40c2b 100644 --- a/Tests/Fixtures/AlternatingRowType.php +++ b/Tests/Fixtures/AlternatingRowType.php @@ -9,7 +9,7 @@ class AlternatingRowType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { $form = $event->getForm(); diff --git a/Tests/Fixtures/AuthorType.php b/Tests/Fixtures/AuthorType.php index 84c988984f..a55dbfeacc 100644 --- a/Tests/Fixtures/AuthorType.php +++ b/Tests/Fixtures/AuthorType.php @@ -8,7 +8,7 @@ class AuthorType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('firstName') @@ -16,7 +16,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => 'Symfony\Component\Form\Tests\Fixtures\Author', diff --git a/Tests/Fixtures/BlockPrefixedFooTextType.php b/Tests/Fixtures/BlockPrefixedFooTextType.php index 3fda7a55dd..fa145a49c2 100644 --- a/Tests/Fixtures/BlockPrefixedFooTextType.php +++ b/Tests/Fixtures/BlockPrefixedFooTextType.php @@ -16,7 +16,7 @@ class BlockPrefixedFooTextType extends AbstractType { - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('block_prefix', 'foo'); } diff --git a/Tests/Fixtures/ChoiceSubType.php b/Tests/Fixtures/ChoiceSubType.php index 7399dfe36b..38b22b87e5 100644 --- a/Tests/Fixtures/ChoiceSubType.php +++ b/Tests/Fixtures/ChoiceSubType.php @@ -20,7 +20,7 @@ */ class ChoiceSubType extends AbstractType { - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults(['expanded' => true]); $resolver->setNormalizer('choices', fn () => [ diff --git a/Tests/Fixtures/ChoiceTypeExtension.php b/Tests/Fixtures/ChoiceTypeExtension.php index 1751531d19..3549763f16 100644 --- a/Tests/Fixtures/ChoiceTypeExtension.php +++ b/Tests/Fixtures/ChoiceTypeExtension.php @@ -18,7 +18,7 @@ class ChoiceTypeExtension extends AbstractTypeExtension { public static $extendedType; - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('choices', [ 'A' => 'a', diff --git a/Tests/Fixtures/FooTypeBarExtension.php b/Tests/Fixtures/FooTypeBarExtension.php index 70c710e922..477f36148e 100644 --- a/Tests/Fixtures/FooTypeBarExtension.php +++ b/Tests/Fixtures/FooTypeBarExtension.php @@ -16,12 +16,12 @@ class FooTypeBarExtension extends AbstractTypeExtension { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->setAttribute('bar', 'x'); } - public function getAllowedOptionValues() + public function getAllowedOptionValues(): array { return [ 'a_or_b' => ['c'], diff --git a/Tests/Fixtures/FooTypeBazExtension.php b/Tests/Fixtures/FooTypeBazExtension.php index a11f158844..9720439eb1 100644 --- a/Tests/Fixtures/FooTypeBazExtension.php +++ b/Tests/Fixtures/FooTypeBazExtension.php @@ -16,7 +16,7 @@ class FooTypeBazExtension extends AbstractTypeExtension { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->setAttribute('baz', 'x'); } diff --git a/Tests/Fixtures/LazyChoiceTypeExtension.php b/Tests/Fixtures/LazyChoiceTypeExtension.php index ccd5b3f489..0c7e294144 100644 --- a/Tests/Fixtures/LazyChoiceTypeExtension.php +++ b/Tests/Fixtures/LazyChoiceTypeExtension.php @@ -19,7 +19,7 @@ class LazyChoiceTypeExtension extends AbstractTypeExtension { public static $extendedType; - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('choice_loader', ChoiceList::lazy($this, fn () => [ 'Lazy A' => 'lazy_a', diff --git a/Tests/Fixtures/NotMappedType.php b/Tests/Fixtures/NotMappedType.php index 14c340b891..3d55122e79 100644 --- a/Tests/Fixtures/NotMappedType.php +++ b/Tests/Fixtures/NotMappedType.php @@ -16,7 +16,7 @@ class NotMappedType extends AbstractType { - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('mapped', false); } From 4bbda017fd23c08f18f2de882603e5718c400b73 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 16 Feb 2023 11:55:45 +0100 Subject: [PATCH 086/208] [Contracts] Add missing return types --- Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php b/Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php index 0533883f70..96c39c5cae 100644 --- a/Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/UploadValidatorExtensionTest.php @@ -42,7 +42,7 @@ public function trans($id, array $parameters = [], $domain = null, $locale = nul return 'translated max {{ max }}!'; } - public function setLocale($locale) + public function setLocale($locale): void { } From 79002e4e4cde4561cd91a5ee6d7582ef5103f76e Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Fri, 17 Feb 2023 00:26:18 +0100 Subject: [PATCH 087/208] [Form] Add missing return types to interfaces --- DataMapperInterface.php | 14 +++++++++----- .../DataCollector/FormDataCollectorInterface.php | 14 ++++++++++++++ FormRendererEngineInterface.php | 2 ++ FormRendererInterface.php | 2 ++ FormTypeExtensionInterface.php | 9 +++++++++ RequestHandlerInterface.php | 2 ++ ResolvedFormTypeInterface.php | 6 ++++++ Tests/Extension/Core/Type/FormTypeTest.php | 10 +++++----- 8 files changed, 49 insertions(+), 10 deletions(-) diff --git a/DataMapperInterface.php b/DataMapperInterface.php index b668de3f35..f04137aec6 100644 --- a/DataMapperInterface.php +++ b/DataMapperInterface.php @@ -22,8 +22,10 @@ interface DataMapperInterface * The method is responsible for calling {@link FormInterface::setData()} * on the children of compound forms, defining their underlying model data. * - * @param mixed $viewData View data of the compound form being initialized - * @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances + * @param mixed $viewData View data of the compound form being initialized + * @param \Traversable $forms A list of {@link FormInterface} instances + * + * @return void * * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported */ @@ -52,9 +54,11 @@ public function mapDataToForms(mixed $viewData, \Traversable $forms); * The model data can be an array or an object, so this second argument is always passed * by reference. * - * @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances - * @param mixed $viewData The compound form's view data that get mapped - * its children model data + * @param \Traversable $forms A list of {@link FormInterface} instances + * @param mixed &$viewData The compound form's view data that get mapped + * its children model data + * + * @return void * * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported */ diff --git a/Extension/DataCollector/FormDataCollectorInterface.php b/Extension/DataCollector/FormDataCollectorInterface.php index 0e1d32bfc8..346c101fe3 100644 --- a/Extension/DataCollector/FormDataCollectorInterface.php +++ b/Extension/DataCollector/FormDataCollectorInterface.php @@ -25,26 +25,36 @@ interface FormDataCollectorInterface extends DataCollectorInterface { /** * Stores configuration data of the given form and its children. + * + * @return void */ public function collectConfiguration(FormInterface $form); /** * Stores the default data of the given form and its children. + * + * @return void */ public function collectDefaultData(FormInterface $form); /** * Stores the submitted data of the given form and its children. + * + * @return void */ public function collectSubmittedData(FormInterface $form); /** * Stores the view variables of the given form view and its children. + * + * @return void */ public function collectViewVariables(FormView $view); /** * Specifies that the given objects represent the same conceptual form. + * + * @return void */ public function associateFormWithView(FormInterface $form, FormView $view); @@ -53,6 +63,8 @@ public function associateFormWithView(FormInterface $form, FormView $view); * a tree-like data structure. * * The result can be queried using {@link getData()}. + * + * @return void */ public function buildPreliminaryFormTree(FormInterface $form); @@ -73,6 +85,8 @@ public function buildPreliminaryFormTree(FormInterface $form); * tree, only the view data will be included in the result. If a * corresponding {@link FormInterface} exists otherwise, call * {@link associateFormWithView()} before calling this method. + * + * @return void */ public function buildFinalFormTree(FormInterface $form, FormView $view); diff --git a/FormRendererEngineInterface.php b/FormRendererEngineInterface.php index aa249270a0..e7de3544a1 100644 --- a/FormRendererEngineInterface.php +++ b/FormRendererEngineInterface.php @@ -24,6 +24,8 @@ interface FormRendererEngineInterface * @param FormView $view The view to assign the theme(s) to * @param mixed $themes The theme(s). The type of these themes * is open to the implementation. + * + * @return void */ public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true); diff --git a/FormRendererInterface.php b/FormRendererInterface.php index 240cd14113..8e805727ce 100644 --- a/FormRendererInterface.php +++ b/FormRendererInterface.php @@ -31,6 +31,8 @@ public function getEngine(): FormRendererEngineInterface; * is open to the implementation. * @param bool $useDefaultThemes If true, will use default themes specified * in the renderer + * + * @return void */ public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true); diff --git a/FormTypeExtensionInterface.php b/FormTypeExtensionInterface.php index 3c7b46ce9c..1937834515 100644 --- a/FormTypeExtensionInterface.php +++ b/FormTypeExtensionInterface.php @@ -26,6 +26,8 @@ interface FormTypeExtensionInterface * * @param array $options * + * @return void + * * @see FormTypeInterface::buildForm() */ public function buildForm(FormBuilderInterface $builder, array $options); @@ -38,6 +40,8 @@ public function buildForm(FormBuilderInterface $builder, array $options); * * @param array $options * + * @return void + * * @see FormTypeInterface::buildView() */ public function buildView(FormView $view, FormInterface $form, array $options); @@ -50,10 +54,15 @@ public function buildView(FormView $view, FormInterface $form, array $options); * * @param array $options * + * @return void + * * @see FormTypeInterface::finishView() */ public function finishView(FormView $view, FormInterface $form, array $options); + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver); /** diff --git a/RequestHandlerInterface.php b/RequestHandlerInterface.php index 8eb8f1a688..39fd458ee4 100644 --- a/RequestHandlerInterface.php +++ b/RequestHandlerInterface.php @@ -20,6 +20,8 @@ interface RequestHandlerInterface { /** * Submits a form if it was submitted. + * + * @return void */ public function handleRequest(FormInterface $form, mixed $request = null); diff --git a/ResolvedFormTypeInterface.php b/ResolvedFormTypeInterface.php index f101177701..e0b96a5ac3 100644 --- a/ResolvedFormTypeInterface.php +++ b/ResolvedFormTypeInterface.php @@ -56,6 +56,8 @@ public function createView(FormInterface $form, FormView $parent = null): FormVi /** * Configures a form builder for the type hierarchy. + * + * @return void */ public function buildForm(FormBuilderInterface $builder, array $options); @@ -63,6 +65,8 @@ public function buildForm(FormBuilderInterface $builder, array $options); * Configures a form view for the type hierarchy. * * It is called before the children of the view are built. + * + * @return void */ public function buildView(FormView $view, FormInterface $form, array $options); @@ -70,6 +74,8 @@ public function buildView(FormView $view, FormInterface $form, array $options); * Finishes a form view for the type hierarchy. * * It is called after the children of the view have been built. + * + * @return void */ public function finishView(FormView $view, FormInterface $form, array $options); diff --git a/Tests/Extension/Core/Type/FormTypeTest.php b/Tests/Extension/Core/Type/FormTypeTest.php index cb1bf802a5..be89c559f6 100644 --- a/Tests/Extension/Core/Type/FormTypeTest.php +++ b/Tests/Extension/Core/Type/FormTypeTest.php @@ -883,14 +883,14 @@ public function getCurrency() class MoneyDataMapper implements DataMapperInterface { - public function mapDataToForms($data, $forms) + public function mapDataToForms(mixed $viewData, \Traversable $forms): void { $forms = iterator_to_array($forms); - $forms['amount']->setData($data ? $data->getAmount() : 0); - $forms['currency']->setData($data ? $data->getCurrency() : 'EUR'); + $forms['amount']->setData($viewData ? $viewData->getAmount() : 0); + $forms['currency']->setData($viewData ? $viewData->getCurrency() : 'EUR'); } - public function mapFormsToData($forms, &$data) + public function mapFormsToData(\Traversable $forms, mixed &$viewData): void { $forms = iterator_to_array($forms); @@ -902,7 +902,7 @@ public function mapFormsToData($forms, &$data) throw $failure; } - $data = new Money( + $viewData = new Money( $forms['amount']->getData(), $forms['currency']->getData() ); From f491e481004a58318aa7a19c8247b7ccad88b57e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20ALFAIATE?= Date: Tue, 21 Feb 2023 10:59:37 +0700 Subject: [PATCH 088/208] [Form] Skip password hashing on empty password --- .../EventListener/PasswordHasherListener.php | 4 +++ ...asswordTypePasswordHasherExtensionTest.php | 31 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php index 3fccfd8965..bb74e7792e 100644 --- a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php +++ b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php @@ -37,6 +37,10 @@ public function __construct( public function registerPassword(FormEvent $event) { + if (null === $event->getData() || '' === $event->getData()) { + return; + } + $this->assertNotMapped($event->getForm()); $this->passwords[] = [ diff --git a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php index 895a39c41b..0b745c172f 100644 --- a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php +++ b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php @@ -13,6 +13,7 @@ use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Form\Exception\InvalidConfigurationException; +use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Extension\Core\Type\PasswordType; use Symfony\Component\Form\Extension\Core\Type\RepeatedType; use Symfony\Component\Form\Extension\PasswordHasher\EventListener\PasswordHasherListener; @@ -80,6 +81,36 @@ public function testPasswordHashSuccess() $this->assertSame($user->getPassword(), $hashedPassword); } + public function testPasswordHashSkippedWithEmptyPassword() + { + $oldHashedPassword = 'PreviousHashedPassword'; + + $user = new User(); + $user->setPassword($oldHashedPassword); + + $this->passwordHasher + ->expects($this->never()) + ->method('hashPassword') + ; + + $this->assertEquals($user->getPassword(), $oldHashedPassword); + + $form = $this->factory + ->createBuilder(FormType::class, $user) + ->add('plainPassword', PasswordType::class, [ + 'hash_property_path' => 'password', + 'mapped' => false, + 'required' => false, + ]) + ->getForm() + ; + + $form->submit(['plainPassword' => '']); + + $this->assertTrue($form->isValid()); + $this->assertSame($user->getPassword(), $oldHashedPassword); + } + public function testPasswordHashSuccessWithEmptyData() { $user = new User(); From 0f55d9356eb52e65ff5241d57fcb70a2bd153d56 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault Date: Wed, 22 Feb 2023 21:03:28 +0100 Subject: [PATCH 089/208] Remove unused private methods --- .../Factory/DefaultChoiceListFactoryTest.php | 38 ------------------- 1 file changed, 38 deletions(-) diff --git a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index 35526a98f6..dfbbd2b5b8 100644 --- a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -854,25 +854,6 @@ public function testCreateViewFlatlabelTranslationParametersClosureReceivesValue $this->assertFlatViewWithlabelTranslationParameters($view); } - private function assertScalarListWithChoiceValues(ChoiceListInterface $list) - { - $this->assertSame(['a', 'b', 'c', 'd'], $list->getValues()); - - $this->assertSame([ - 'a' => 'a', - 'b' => 'b', - 'c' => 'c', - 'd' => 'd', - ], $list->getChoices()); - - $this->assertSame([ - 'a' => 'A', - 'b' => 'B', - 'c' => 'C', - 'd' => 'D', - ], $list->getOriginalKeys()); - } - private function assertObjectListWithGeneratedValues(ChoiceListInterface $list) { $this->assertSame(['0', '1', '2', '3'], $list->getValues()); @@ -892,25 +873,6 @@ private function assertObjectListWithGeneratedValues(ChoiceListInterface $list) ], $list->getOriginalKeys()); } - private function assertScalarListWithCustomValues(ChoiceListInterface $list) - { - $this->assertSame(['a', 'b', '1', '2'], $list->getValues()); - - $this->assertSame([ - 'a' => 'a', - 'b' => 'b', - 1 => 'c', - 2 => 'd', - ], $list->getChoices()); - - $this->assertSame([ - 'a' => 'A', - 'b' => 'B', - 1 => 'C', - 2 => 'D', - ], $list->getOriginalKeys()); - } - private function assertObjectListWithCustomValues(ChoiceListInterface $list) { $this->assertSame(['a', 'b', '1', '2'], $list->getValues()); From ce99d4ab880c51c3ddc43119792137642fa85aee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kenjy=20Thi=C3=A9bault?= Date: Fri, 10 Mar 2023 22:15:26 +0100 Subject: [PATCH 090/208] [Form] Improve exception for unsubmitted form --- Form.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Form.php b/Form.php index 9d6344c869..851d56a46d 100644 --- a/Form.php +++ b/Form.php @@ -646,7 +646,7 @@ public function isEmpty(): bool public function isValid(): bool { if (!$this->submitted) { - throw new LogicException('Cannot check if an unsubmitted form is valid. Call Form::isSubmitted() before Form::isValid().'); + throw new LogicException('Cannot check if an unsubmitted form is valid. Call Form::isSubmitted() and ensure that it\'s true before calling Form::isValid().'); } if ($this->isDisabled()) { From 7368b3b45d23a61be4748495eeb0dbe27ed28f27 Mon Sep 17 00:00:00 2001 From: Jordane Vaspard Date: Sat, 26 Nov 2022 15:45:54 +0100 Subject: [PATCH 091/208] [Form][ChoiceType] Add placeholder_attr field option --- CHANGELOG.md | 5 ++ Extension/Core/Type/ChoiceType.php | 6 +- Tests/Extension/Core/Type/ChoiceTypeTest.php | 86 +++++++++++-------- .../Descriptor/resolved_form_type_1.json | 1 + .../Descriptor/resolved_form_type_1.txt | 4 +- 5 files changed, 64 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 68622612e3..cf21889169 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +6.3 +--- + + * Add a `placeholder_attr` option to `ChoiceType` + 6.2 --- diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 2dde39e8af..0fc628a549 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -84,7 +84,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) // Check if the choices already contain the empty value // Only add the placeholder option if this is not the case if (null !== $options['placeholder'] && 0 === \count($choiceList->getChoicesForValues(['']))) { - $placeholderView = new ChoiceView(null, '', $options['placeholder']); + $placeholderView = new ChoiceView(null, '', $options['placeholder'], $options['placeholder_attr']); // "placeholder" is a reserved name $this->addSubForm($builder, 'placeholder', $placeholderView, $options); @@ -237,6 +237,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) 'choices' => $choiceListView->choices, 'separator' => '-------------------', 'placeholder' => null, + 'placeholder_attr' => [], 'choice_translation_domain' => $choiceTranslationDomain, 'choice_translation_parameters' => $options['choice_translation_parameters'], ]); @@ -261,6 +262,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) // Only add the empty value option if this is not the case if (null !== $options['placeholder'] && !$view->vars['placeholder_in_choices']) { $view->vars['placeholder'] = $options['placeholder']; + $view->vars['placeholder_attr'] = $options['placeholder_attr']; } if ($options['multiple'] && !$options['expanded']) { @@ -352,6 +354,7 @@ public function configureOptions(OptionsResolver $resolver) 'group_by' => null, 'empty_data' => $emptyData, 'placeholder' => $placeholderDefault, + 'placeholder_attr' => [], 'error_bubbling' => false, 'compound' => $compound, // The view data is always a string or an array of strings, @@ -375,6 +378,7 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('choice_value', ['null', 'callable', 'string', PropertyPath::class, ChoiceValue::class]); $resolver->setAllowedTypes('choice_attr', ['null', 'array', 'callable', 'string', PropertyPath::class, ChoiceAttr::class]); $resolver->setAllowedTypes('choice_translation_parameters', ['null', 'array', 'callable', ChoiceTranslationParameters::class]); + $resolver->setAllowedTypes('placeholder_attr', ['array']); $resolver->setAllowedTypes('preferred_choices', ['array', \Traversable::class, 'callable', 'string', PropertyPath::class, PreferredChoice::class]); $resolver->setAllowedTypes('group_by', ['null', 'callable', 'string', PropertyPath::class, GroupBy::class]); } diff --git a/Tests/Extension/Core/Type/ChoiceTypeTest.php b/Tests/Extension/Core/Type/ChoiceTypeTest.php index 8109a9c600..7a0b2f5573 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -100,6 +100,14 @@ public function testChoiceLoaderOptionExpectsChoiceLoaderInterface() ]); } + public function testPlaceholderAttrOptionExpectsArray() + { + $this->expectException(InvalidOptionsException::class); + $this->factory->create(static::TESTED_TYPE, null, [ + 'placeholder_attr' => new \stdClass(), + ]); + } + public function testChoiceListAndChoicesCanBeEmpty() { $this->assertInstanceOf(FormInterface::class, $this->factory->create(static::TESTED_TYPE, null, [])); @@ -189,15 +197,19 @@ public function testExpandedChoiceListWithBooleanAndNullValuesAndFalseAsPreSetDa public function testPlaceholderPresentOnNonRequiredExpandedSingleChoice() { + $placeholderAttr = ['attr' => 'value']; + $form = $this->factory->create(static::TESTED_TYPE, null, [ 'multiple' => false, 'expanded' => true, 'required' => false, 'choices' => $this->choices, + 'placeholder_attr' => $placeholderAttr, ]); $this->assertArrayHasKey('placeholder', $form); $this->assertCount(\count($this->choices) + 1, $form, 'Each choice should become a new field'); + $this->assertSame($placeholderAttr, $form->createView()->children['placeholder']->vars['attr']); } public function testPlaceholderNotPresentIfRequired() @@ -1669,36 +1681,40 @@ public function testPlaceholderIsEmptyStringByDefaultIfNotRequired() /** * @dataProvider getOptionsWithPlaceholder */ - public function testPassPlaceholderToView($multiple, $expanded, $required, $placeholder, $viewValue) + public function testPassPlaceholderToView($multiple, $expanded, $required, $placeholder, $placeholderViewValue, $placeholderAttr, $placeholderAttrViewValue) { $view = $this->factory->create(static::TESTED_TYPE, null, [ 'multiple' => $multiple, 'expanded' => $expanded, 'required' => $required, 'placeholder' => $placeholder, + 'placeholder_attr' => $placeholderAttr, 'choices' => $this->choices, ]) ->createView(); - $this->assertSame($viewValue, $view->vars['placeholder']); + $this->assertSame($placeholderViewValue, $view->vars['placeholder']); + $this->assertSame($placeholderAttrViewValue, $view->vars['placeholder_attr']); $this->assertFalse($view->vars['placeholder_in_choices']); } /** * @dataProvider getOptionsWithPlaceholder */ - public function testDontPassPlaceholderIfContainedInChoices($multiple, $expanded, $required, $placeholder, $viewValue) + public function testDontPassPlaceholderIfContainedInChoices($multiple, $expanded, $required, $placeholder, $placeholderViewValue, $placeholderAttr, $placeholderAttrViewValue) { $view = $this->factory->create(static::TESTED_TYPE, null, [ 'multiple' => $multiple, 'expanded' => $expanded, 'required' => $required, 'placeholder' => $placeholder, + 'placeholder_attr' => $placeholderAttr, 'choices' => ['Empty' => '', 'A' => 'a'], ]) ->createView(); $this->assertNull($view->vars['placeholder']); + $this->assertSame([], $view->vars['placeholder_attr']); $this->assertTrue($view->vars['placeholder_in_choices']); } @@ -1706,43 +1722,43 @@ public function getOptionsWithPlaceholder() { return [ // single non-expanded - [false, false, false, 'foobar', 'foobar'], - [false, false, false, '', ''], - [false, false, false, null, null], - [false, false, false, false, null], - [false, false, true, 'foobar', 'foobar'], - [false, false, true, '', ''], - [false, false, true, null, null], - [false, false, true, false, null], + [false, false, false, 'foobar', 'foobar', ['attr' => 'value'], ['attr' => 'value']], + [false, false, false, '', '', ['attr' => 'value'], ['attr' => 'value']], + [false, false, false, null, null, ['attr' => 'value'], []], + [false, false, false, false, null, ['attr' => 'value'], []], + [false, false, true, 'foobar', 'foobar', ['attr' => 'value'], ['attr' => 'value']], + [false, false, true, '', '', ['attr' => 'value'], ['attr' => 'value']], + [false, false, true, null, null, ['attr' => 'value'], []], + [false, false, true, false, null, ['attr' => 'value'], []], // single expanded - [false, true, false, 'foobar', 'foobar'], + [false, true, false, 'foobar', 'foobar', ['attr' => 'value'], ['attr' => 'value']], // radios should never have an empty label - [false, true, false, '', 'None'], - [false, true, false, null, null], - [false, true, false, false, null], + [false, true, false, '', 'None', ['attr' => 'value'], ['attr' => 'value']], + [false, true, false, null, null, ['attr' => 'value'], []], + [false, true, false, false, null, ['attr' => 'value'], []], // required radios should never have a placeholder - [false, true, true, 'foobar', null], - [false, true, true, '', null], - [false, true, true, null, null], - [false, true, true, false, null], + [false, true, true, 'foobar', null, ['attr' => 'value'], []], + [false, true, true, '', null, ['attr' => 'value'], []], + [false, true, true, null, null, ['attr' => 'value'], []], + [false, true, true, false, null, ['attr' => 'value'], []], // multiple non-expanded - [true, false, false, 'foobar', null], - [true, false, false, '', null], - [true, false, false, null, null], - [true, false, false, false, null], - [true, false, true, 'foobar', null], - [true, false, true, '', null], - [true, false, true, null, null], - [true, false, true, false, null], + [true, false, false, 'foobar', null, ['attr' => 'value'], []], + [true, false, false, '', null, ['attr' => 'value'], []], + [true, false, false, null, null, ['attr' => 'value'], []], + [true, false, false, false, null, ['attr' => 'value'], []], + [true, false, true, 'foobar', null, ['attr' => 'value'], []], + [true, false, true, '', null, ['attr' => 'value'], []], + [true, false, true, null, null, ['attr' => 'value'], []], + [true, false, true, false, null, ['attr' => 'value'], []], // multiple expanded - [true, true, false, 'foobar', null], - [true, true, false, '', null], - [true, true, false, null, null], - [true, true, false, false, null], - [true, true, true, 'foobar', null], - [true, true, true, '', null], - [true, true, true, null, null], - [true, true, true, false, null], + [true, true, false, 'foobar', null, ['attr' => 'value'], []], + [true, true, false, '', null, ['attr' => 'value'], []], + [true, true, false, null, null, ['attr' => 'value'], []], + [true, true, false, false, null, ['attr' => 'value'], []], + [true, true, true, 'foobar', null, ['attr' => 'value'], []], + [true, true, true, '', null, ['attr' => 'value'], []], + [true, true, true, null, null, ['attr' => 'value'], []], + [true, true, true, false, null, ['attr' => 'value'], []], ]; } diff --git a/Tests/Fixtures/Descriptor/resolved_form_type_1.json b/Tests/Fixtures/Descriptor/resolved_form_type_1.json index c9f453c8d6..3a9b7a7ecc 100644 --- a/Tests/Fixtures/Descriptor/resolved_form_type_1.json +++ b/Tests/Fixtures/Descriptor/resolved_form_type_1.json @@ -16,6 +16,7 @@ "group_by", "multiple", "placeholder", + "placeholder_attr", "preferred_choices" ], "overridden": { diff --git a/Tests/Fixtures/Descriptor/resolved_form_type_1.txt b/Tests/Fixtures/Descriptor/resolved_form_type_1.txt index c4c4e90180..a15ac42dae 100644 --- a/Tests/Fixtures/Descriptor/resolved_form_type_1.txt +++ b/Tests/Fixtures/Descriptor/resolved_form_type_1.txt @@ -18,8 +18,8 @@ Symfony\Component\Form\Extension\Core\Type\ChoiceType (Block prefix: "choice") group_by data multiple disabled placeholder form_attr - preferred_choices getter - help + placeholder_attr getter + preferred_choices help help_attr help_html help_translation_parameters From 9deab00aa3b8bb288e34fe2a235b69c70970de2f Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 21 Mar 2023 22:03:43 +0100 Subject: [PATCH 092/208] Replace "use-by-ref" by static vars when possible in closures --- ChoiceList/ArrayChoiceList.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ChoiceList/ArrayChoiceList.php b/ChoiceList/ArrayChoiceList.php index ef09ca5837..2dfc497d3d 100644 --- a/ChoiceList/ArrayChoiceList.php +++ b/ChoiceList/ArrayChoiceList.php @@ -72,8 +72,9 @@ public function __construct(iterable $choices, callable $value = null) $this->valueCallback = $value; } else { // Otherwise generate incrementing integers as values - $i = 0; - $value = function () use (&$i) { + $value = function () { + static $i = 0; + return $i++; }; } From 3963819dd03a173f39758986a8aa9338f1fbb20c Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 28 Mar 2023 11:09:35 +0200 Subject: [PATCH 093/208] [Form] Use static closures when possible --- .../Factory/CachingFactoryDecorator.php | 2 +- .../Factory/DefaultChoiceListFactory.php | 9 +++---- .../Factory/PropertyAccessDecorator.php | 14 +++++------ Command/DebugCommand.php | 4 +-- Console/Descriptor/Descriptor.php | 2 +- Extension/Core/Type/CheckboxType.php | 2 +- Extension/Core/Type/ChoiceType.php | 25 ++++++++++--------- Extension/Core/Type/CollectionType.php | 2 +- Extension/Core/Type/ColorType.php | 5 ++-- Extension/Core/Type/CountryType.php | 2 +- Extension/Core/Type/CurrencyType.php | 2 +- Extension/Core/Type/DateIntervalType.php | 12 ++++----- Extension/Core/Type/DateTimeType.php | 16 ++++++------ Extension/Core/Type/DateType.php | 14 +++++------ Extension/Core/Type/FileType.php | 4 +-- Extension/Core/Type/FormType.php | 12 ++++----- Extension/Core/Type/LanguageType.php | 4 +-- Extension/Core/Type/LocaleType.php | 2 +- Extension/Core/Type/MoneyType.php | 2 +- Extension/Core/Type/NumberType.php | 2 +- Extension/Core/Type/TimeType.php | 16 ++++++------ Extension/Core/Type/TimezoneType.php | 8 +++--- Extension/Core/Type/WeekType.php | 12 ++++----- Extension/DataCollector/FormDataCollector.php | 6 ++--- .../Validator/Type/BaseValidatorExtension.php | 2 +- .../Type/FormTypeValidatorExtension.php | 2 +- .../Type/RepeatedTypeValidatorExtension.php | 2 +- .../Type/UploadValidatorExtension.php | 2 +- Extension/Validator/ValidatorTypeGuesser.php | 14 +++++------ FormTypeGuesserChain.php | 8 +++--- .../default_option_with_normalizer.txt | 1 - 31 files changed, 104 insertions(+), 106 deletions(-) diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index 304105cbc2..40c0604ea4 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -54,7 +54,7 @@ public static function generateHash(mixed $value, string $namespace = ''): strin if (\is_object($value)) { $value = spl_object_hash($value); } elseif (\is_array($value)) { - array_walk_recursive($value, function (&$v) { + array_walk_recursive($value, static function (&$v) { if (\is_object($v)) { $v = spl_object_hash($v); } diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index b5b8337047..fb30fc6ded 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -35,8 +35,9 @@ public function createListFromChoices(iterable $choices, callable $value = null, if ($filter) { // filter the choice list lazily return $this->createListFromLoader(new FilterChoiceLoaderDecorator( - new CallbackChoiceLoader(static fn () => $choices - ), $filter), $value); + new CallbackChoiceLoader(static fn () => $choices), + $filter + ), $value); } return new ArrayChoiceList($choices, $value); @@ -133,9 +134,7 @@ public function createView(ChoiceListInterface $list, array|callable $preferredC ); } - uksort($preferredViews, static fn ($a, $b): int => isset($preferredViewsOrder[$a], $preferredViewsOrder[$b]) - ? $preferredViewsOrder[$a] <=> $preferredViewsOrder[$b] - : 0); + uksort($preferredViews, static fn ($a, $b) => isset($preferredViewsOrder[$a], $preferredViewsOrder[$b]) ? $preferredViewsOrder[$a] <=> $preferredViewsOrder[$b] : 0); return new ChoiceListView($otherViews, $preferredViews); } diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index b0b8e479d8..fa66290e34 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -67,7 +67,7 @@ public function createListFromChoices(iterable $choices, mixed $value = null, mi // when such values are passed to // ChoiceListInterface::getValuesForChoices(). Handle this case // so that the call to getValue() doesn't break. - $value = fn ($choice) => \is_object($choice) || \is_array($choice) ? $accessor->getValue($choice, $value) : null; + $value = static fn ($choice) => \is_object($choice) || \is_array($choice) ? $accessor->getValue($choice, $value) : null; } if (\is_string($filter)) { @@ -94,7 +94,7 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value // when such values are passed to // ChoiceListInterface::getValuesForChoices(). Handle this case // so that the call to getValue() doesn't break. - $value = fn ($choice) => \is_object($choice) || \is_array($choice) ? $accessor->getValue($choice, $value) : null; + $value = static fn ($choice) => \is_object($choice) || \is_array($choice) ? $accessor->getValue($choice, $value) : null; } if (\is_string($filter)) { @@ -118,7 +118,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = } if ($label instanceof PropertyPathInterface) { - $label = fn ($choice) => $accessor->getValue($choice, $label); + $label = static fn ($choice) => $accessor->getValue($choice, $label); } if (\is_string($preferredChoices)) { @@ -126,7 +126,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = } if ($preferredChoices instanceof PropertyPathInterface) { - $preferredChoices = function ($choice) use ($accessor, $preferredChoices) { + $preferredChoices = static function ($choice) use ($accessor, $preferredChoices) { try { return $accessor->getValue($choice, $preferredChoices); } catch (UnexpectedTypeException) { @@ -141,7 +141,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = } if ($index instanceof PropertyPathInterface) { - $index = fn ($choice) => $accessor->getValue($choice, $index); + $index = static fn ($choice) => $accessor->getValue($choice, $index); } if (\is_string($groupBy)) { @@ -149,7 +149,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = } if ($groupBy instanceof PropertyPathInterface) { - $groupBy = function ($choice) use ($accessor, $groupBy) { + $groupBy = static function ($choice) use ($accessor, $groupBy) { try { return $accessor->getValue($choice, $groupBy); } catch (UnexpectedTypeException) { @@ -164,7 +164,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = } if ($attr instanceof PropertyPathInterface) { - $attr = fn ($choice) => $accessor->getValue($choice, $attr); + $attr = static fn ($choice) => $accessor->getValue($choice, $attr); } if (\is_string($labelTranslationParameters)) { diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index 9b6b830341..5e4635870a 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -207,7 +207,7 @@ private function getCoreTypes(): array $coreExtension = new CoreExtension(); $loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes'); $coreTypes = $loadTypesRefMethod->invoke($coreExtension); - $coreTypes = array_map(fn (FormTypeInterface $type) => $type::class, $coreTypes); + $coreTypes = array_map(static fn (FormTypeInterface $type) => $type::class, $coreTypes); sort($coreTypes); return $coreTypes; @@ -240,7 +240,7 @@ private function findAlternatives(string $name, array $collection): array } $threshold = 1e3; - $alternatives = array_filter($alternatives, fn ($lev) => $lev < 2 * $threshold); + $alternatives = array_filter($alternatives, static fn ($lev) => $lev < 2 * $threshold); ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE); return array_keys($alternatives); diff --git a/Console/Descriptor/Descriptor.php b/Console/Descriptor/Descriptor.php index 782bad8870..3c54545cf1 100644 --- a/Console/Descriptor/Descriptor.php +++ b/Console/Descriptor/Descriptor.php @@ -149,7 +149,7 @@ protected function filterOptionsByDeprecated(ResolvedFormTypeInterface $type): v } } - $filterByDeprecated = function (array $options) use ($deprecatedOptions) { + $filterByDeprecated = static function (array $options) use ($deprecatedOptions) { foreach ($options as $class => $opts) { if ($deprecated = array_intersect($deprecatedOptions, $opts)) { $options[$class] = $deprecated; diff --git a/Extension/Core/Type/CheckboxType.php b/Extension/Core/Type/CheckboxType.php index b261f926bb..291ede93ef 100644 --- a/Extension/Core/Type/CheckboxType.php +++ b/Extension/Core/Type/CheckboxType.php @@ -51,7 +51,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) */ public function configureOptions(OptionsResolver $resolver) { - $emptyData = fn (FormInterface $form, $viewData) => $viewData; + $emptyData = static fn (FormInterface $form, $viewData) => $viewData; $resolver->setDefaults([ 'value' => '1', diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 9694ed750a..05ef3b9656 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -97,7 +97,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) if ($options['expanded'] || $options['multiple']) { // Make sure that scalar, submitted values are converted to arrays // which can be submitted to the checkboxes/radio buttons - $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($choiceList, $options, &$unknownValues) { + $builder->addEventListener(FormEvents::PRE_SUBMIT, static function (FormEvent $event) use ($choiceList, $options, &$unknownValues) { $form = $event->getForm(); $data = $event->getData(); @@ -166,16 +166,17 @@ public function buildForm(FormBuilderInterface $builder, array $options) if ($options['multiple']) { $messageTemplate = $options['invalid_message'] ?? 'The value {{ value }} is not valid.'; + $translator = $this->translator; - $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use (&$unknownValues, $messageTemplate) { + $builder->addEventListener(FormEvents::POST_SUBMIT, static function (FormEvent $event) use (&$unknownValues, $messageTemplate, $translator) { // Throw exception if unknown values were submitted if (\count($unknownValues) > 0) { $form = $event->getForm(); $clientDataAsString = \is_scalar($form->getViewData()) ? (string) $form->getViewData() : (\is_array($form->getViewData()) ? implode('", "', array_keys($unknownValues)) : \gettype($form->getViewData())); - if (null !== $this->translator) { - $message = $this->translator->trans($messageTemplate, ['{{ value }}' => $clientDataAsString], 'validators'); + if ($translator) { + $message = $translator->trans($messageTemplate, ['{{ value }}' => $clientDataAsString], 'validators'); } else { $message = strtr($messageTemplate, ['{{ value }}' => $clientDataAsString]); } @@ -199,7 +200,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) // To avoid issues when the submitted choices are arrays (i.e. array to string conversions), // we have to ensure that all elements of the submitted choice data are NULL, strings or ints. - $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) { + $builder->addEventListener(FormEvents::PRE_SUBMIT, static function (FormEvent $event) { $data = $event->getData(); if (!\is_array($data)) { @@ -245,9 +246,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) // closure here that is optimized for the value of the form, to // avoid making the type check inside the closure. if ($options['multiple']) { - $view->vars['is_selected'] = fn ($choice, array $values) => \in_array($choice, $values, true); + $view->vars['is_selected'] = static fn ($choice, array $values) => \in_array($choice, $values, true); } else { - $view->vars['is_selected'] = fn ($choice, $value) => $choice === $value; + $view->vars['is_selected'] = static fn ($choice, $value) => $choice === $value; } // Check if the choices already contain the empty value @@ -285,7 +286,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) public function configureOptions(OptionsResolver $resolver) { - $emptyData = function (Options $options) { + $emptyData = static function (Options $options) { if ($options['expanded'] && !$options['multiple']) { return null; } @@ -297,9 +298,9 @@ public function configureOptions(OptionsResolver $resolver) return ''; }; - $placeholderDefault = fn (Options $options) => $options['required'] ? null : ''; + $placeholderDefault = static fn (Options $options) => $options['required'] ? null : ''; - $placeholderNormalizer = function (Options $options, $placeholder) { + $placeholderNormalizer = static function (Options $options, $placeholder) { if ($options['multiple']) { // never use an empty value for this case return null; @@ -318,9 +319,9 @@ public function configureOptions(OptionsResolver $resolver) return $placeholder; }; - $compound = fn (Options $options) => $options['expanded']; + $compound = static fn (Options $options) => $options['expanded']; - $choiceTranslationDomainNormalizer = function (Options $options, $choiceTranslationDomain) { + $choiceTranslationDomainNormalizer = static function (Options $options, $choiceTranslationDomain) { if (true === $choiceTranslationDomain) { return $options['translation_domain']; } diff --git a/Extension/Core/Type/CollectionType.php b/Extension/Core/Type/CollectionType.php index 1654d379a8..27e9a6a019 100644 --- a/Extension/Core/Type/CollectionType.php +++ b/Extension/Core/Type/CollectionType.php @@ -106,7 +106,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) */ public function configureOptions(OptionsResolver $resolver) { - $entryOptionsNormalizer = function (Options $options, $value) { + $entryOptionsNormalizer = static function (Options $options, $value) { $value['block_name'] = 'entry'; return $value; diff --git a/Extension/Core/Type/ColorType.php b/Extension/Core/Type/ColorType.php index 6e205fcbc9..31538fc3c7 100644 --- a/Extension/Core/Type/ColorType.php +++ b/Extension/Core/Type/ColorType.php @@ -42,7 +42,8 @@ public function buildForm(FormBuilderInterface $builder, array $options) return; } - $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void { + $translator = $this->translator; + $builder->addEventListener(FormEvents::PRE_SUBMIT, static function (FormEvent $event) use ($translator): void { $value = $event->getData(); if (null === $value || '' === $value) { return; @@ -56,7 +57,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) $messageParameters = [ '{{ value }}' => \is_scalar($value) ? (string) $value : \gettype($value), ]; - $message = $this->translator ? $this->translator->trans($messageTemplate, $messageParameters, 'validators') : $messageTemplate; + $message = $translator?->trans($messageTemplate, $messageParameters, 'validators') ?? $messageTemplate; $event->getForm()->addError(new FormError($message, $messageTemplate, $messageParameters)); }); diff --git a/Extension/Core/Type/CountryType.php b/Extension/Core/Type/CountryType.php index b647284904..6f872660a0 100644 --- a/Extension/Core/Type/CountryType.php +++ b/Extension/Core/Type/CountryType.php @@ -36,7 +36,7 @@ public function configureOptions(OptionsResolver $resolver) $choiceTranslationLocale = $options['choice_translation_locale']; $alpha3 = $options['alpha3']; - return ChoiceList::loader($this, new IntlCallbackChoiceLoader(fn () => array_flip($alpha3 ? Countries::getAlpha3Names($choiceTranslationLocale) : Countries::getNames($choiceTranslationLocale))), [$choiceTranslationLocale, $alpha3]); + return ChoiceList::loader($this, new IntlCallbackChoiceLoader(static fn () => array_flip($alpha3 ? Countries::getAlpha3Names($choiceTranslationLocale) : Countries::getNames($choiceTranslationLocale))), [$choiceTranslationLocale, $alpha3]); }, 'choice_translation_domain' => false, 'choice_translation_locale' => null, diff --git a/Extension/Core/Type/CurrencyType.php b/Extension/Core/Type/CurrencyType.php index 1c0ac471b8..89edc6f630 100644 --- a/Extension/Core/Type/CurrencyType.php +++ b/Extension/Core/Type/CurrencyType.php @@ -35,7 +35,7 @@ public function configureOptions(OptionsResolver $resolver) $choiceTranslationLocale = $options['choice_translation_locale']; - return ChoiceList::loader($this, new IntlCallbackChoiceLoader(fn () => array_flip(Currencies::getNames($choiceTranslationLocale))), $choiceTranslationLocale); + return ChoiceList::loader($this, new IntlCallbackChoiceLoader(static fn () => array_flip(Currencies::getNames($choiceTranslationLocale))), $choiceTranslationLocale); }, 'choice_translation_domain' => false, 'choice_translation_locale' => null, diff --git a/Extension/Core/Type/DateIntervalType.php b/Extension/Core/Type/DateIntervalType.php index 0e4a7555a0..655ef6682f 100644 --- a/Extension/Core/Type/DateIntervalType.php +++ b/Extension/Core/Type/DateIntervalType.php @@ -168,12 +168,12 @@ public function buildView(FormView $view, FormInterface $form, array $options) */ public function configureOptions(OptionsResolver $resolver) { - $compound = fn (Options $options) => 'single_text' !== $options['widget']; - $emptyData = fn (Options $options) => 'single_text' === $options['widget'] ? '' : []; + $compound = static fn (Options $options) => 'single_text' !== $options['widget']; + $emptyData = static fn (Options $options) => 'single_text' === $options['widget'] ? '' : []; - $placeholderDefault = fn (Options $options) => $options['required'] ? null : ''; + $placeholderDefault = static fn (Options $options) => $options['required'] ? null : ''; - $placeholderNormalizer = function (Options $options, $placeholder) use ($placeholderDefault) { + $placeholderNormalizer = static function (Options $options, $placeholder) use ($placeholderDefault) { if (\is_array($placeholder)) { $default = $placeholderDefault($options); @@ -183,7 +183,7 @@ public function configureOptions(OptionsResolver $resolver) return array_fill_keys(self::TIME_PARTS, $placeholder); }; - $labelsNormalizer = fn (Options $options, array $labels) => array_replace([ + $labelsNormalizer = static fn (Options $options, array $labels) => array_replace([ 'years' => null, 'months' => null, 'days' => null, @@ -192,7 +192,7 @@ public function configureOptions(OptionsResolver $resolver) 'minutes' => null, 'seconds' => null, 'invert' => 'Negative interval', - ], array_filter($labels, fn ($label) => null !== $label)); + ], array_filter($labels, static fn ($label) => null !== $label)); $resolver->setDefaults([ 'with_years' => true, diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index ae47519c53..a0a0c92fe0 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -229,13 +229,13 @@ public function buildView(FormView $view, FormInterface $form, array $options) */ public function configureOptions(OptionsResolver $resolver) { - $compound = fn (Options $options) => 'single_text' !== $options['widget']; + $compound = static fn (Options $options) => 'single_text' !== $options['widget']; // Defaults to the value of "widget" - $dateWidget = fn (Options $options) => 'single_text' === $options['widget'] ? null : $options['widget']; + $dateWidget = static fn (Options $options) => 'single_text' === $options['widget'] ? null : $options['widget']; // Defaults to the value of "widget" - $timeWidget = fn (Options $options) => 'single_text' === $options['widget'] ? null : $options['widget']; + $timeWidget = static fn (Options $options) => 'single_text' === $options['widget'] ? null : $options['widget']; $resolver->setDefaults([ 'input' => 'datetime', @@ -261,7 +261,7 @@ public function configureOptions(OptionsResolver $resolver) 'compound' => $compound, 'date_label' => null, 'time_label' => null, - 'empty_data' => fn (Options $options) => $options['compound'] ? [] : '', + 'empty_data' => static fn (Options $options) => $options['compound'] ? [] : '', 'input_format' => 'Y-m-d H:i:s', 'invalid_message' => 'Please enter a valid date and time.', ]); @@ -308,28 +308,28 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('input_format', 'string'); - $resolver->setNormalizer('date_format', function (Options $options, $dateFormat) { + $resolver->setNormalizer('date_format', static function (Options $options, $dateFormat) { if (null !== $dateFormat && 'single_text' === $options['widget'] && self::HTML5_FORMAT === $options['format']) { throw new LogicException(sprintf('Cannot use the "date_format" option of the "%s" with an HTML5 date.', self::class)); } return $dateFormat; }); - $resolver->setNormalizer('date_widget', function (Options $options, $dateWidget) { + $resolver->setNormalizer('date_widget', static function (Options $options, $dateWidget) { if (null !== $dateWidget && 'single_text' === $options['widget']) { throw new LogicException(sprintf('Cannot use the "date_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class)); } return $dateWidget; }); - $resolver->setNormalizer('time_widget', function (Options $options, $timeWidget) { + $resolver->setNormalizer('time_widget', static function (Options $options, $timeWidget) { if (null !== $timeWidget && 'single_text' === $options['widget']) { throw new LogicException(sprintf('Cannot use the "time_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class)); } return $timeWidget; }); - $resolver->setNormalizer('html5', function (Options $options, $html5) { + $resolver->setNormalizer('html5', static function (Options $options, $html5) { if ($html5 && self::HTML5_FORMAT !== $options['format']) { throw new LogicException(sprintf('Cannot use the "format" option of "%s" when the "html5" option is enabled.', self::class)); } diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index b08a4dd834..5c81097e0e 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -216,11 +216,11 @@ public function finishView(FormView $view, FormInterface $form, array $options) public function configureOptions(OptionsResolver $resolver) { - $compound = fn (Options $options) => 'single_text' !== $options['widget']; + $compound = static fn (Options $options) => 'single_text' !== $options['widget']; - $placeholderDefault = fn (Options $options) => $options['required'] ? null : ''; + $placeholderDefault = static fn (Options $options) => $options['required'] ? null : ''; - $placeholderNormalizer = function (Options $options, $placeholder) use ($placeholderDefault) { + $placeholderNormalizer = static function (Options $options, $placeholder) use ($placeholderDefault) { if (\is_array($placeholder)) { $default = $placeholderDefault($options); @@ -237,7 +237,7 @@ public function configureOptions(OptionsResolver $resolver) ]; }; - $choiceTranslationDomainNormalizer = function (Options $options, $choiceTranslationDomain) { + $choiceTranslationDomainNormalizer = static function (Options $options, $choiceTranslationDomain) { if (\is_array($choiceTranslationDomain)) { $default = false; @@ -254,7 +254,7 @@ public function configureOptions(OptionsResolver $resolver) ]; }; - $format = fn (Options $options) => 'single_text' === $options['widget'] ? self::HTML5_FORMAT : self::DEFAULT_FORMAT; + $format = static fn (Options $options) => 'single_text' === $options['widget'] ? self::HTML5_FORMAT : self::DEFAULT_FORMAT; $resolver->setDefaults([ 'years' => range((int) date('Y') - 5, (int) date('Y') + 5), @@ -277,7 +277,7 @@ public function configureOptions(OptionsResolver $resolver) // this option. 'data_class' => null, 'compound' => $compound, - 'empty_data' => fn (Options $options) => $options['compound'] ? [] : '', + 'empty_data' => static fn (Options $options) => $options['compound'] ? [] : '', 'choice_translation_domain' => false, 'input_format' => 'Y-m-d', 'invalid_message' => 'Please enter a valid date.', @@ -305,7 +305,7 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('days', 'array'); $resolver->setAllowedTypes('input_format', 'string'); - $resolver->setNormalizer('html5', function (Options $options, $html5) { + $resolver->setNormalizer('html5', static function (Options $options, $html5) { if ($html5 && 'single_text' === $options['widget'] && self::HTML5_FORMAT !== $options['format']) { throw new LogicException(sprintf('Cannot use the "format" option of "%s" when the "html5" option is enabled.', self::class)); } diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index 16d212ef0f..6e4b78251d 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -104,10 +104,10 @@ public function configureOptions(OptionsResolver $resolver) { $dataClass = null; if (class_exists(File::class)) { - $dataClass = fn (Options $options) => $options['multiple'] ? null : File::class; + $dataClass = static fn (Options $options) => $options['multiple'] ? null : File::class; } - $emptyData = fn (Options $options) => $options['multiple'] ? [] : null; + $emptyData = static fn (Options $options) => $options['multiple'] ? [] : null; $resolver->setDefaults([ 'compound' => false, diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index 560d1e2cb3..82aa77f0a3 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -136,25 +136,25 @@ public function configureOptions(OptionsResolver $resolver) parent::configureOptions($resolver); // Derive "data_class" option from passed "data" object - $dataClass = fn (Options $options) => isset($options['data']) && \is_object($options['data']) ? $options['data']::class : null; + $dataClass = static fn (Options $options) => isset($options['data']) && \is_object($options['data']) ? $options['data']::class : null; // Derive "empty_data" closure from "data_class" option - $emptyData = function (Options $options) { + $emptyData = static function (Options $options) { $class = $options['data_class']; if (null !== $class) { - return fn (FormInterface $form) => $form->isEmpty() && !$form->isRequired() ? null : new $class(); + return static fn (FormInterface $form) => $form->isEmpty() && !$form->isRequired() ? null : new $class(); } - return fn (FormInterface $form) => $form->getConfig()->getCompound() ? [] : ''; + return static fn (FormInterface $form) => $form->getConfig()->getCompound() ? [] : ''; }; // Wrap "post_max_size_message" in a closure to translate it lazily - $uploadMaxSizeMessage = fn (Options $options) => fn () => $options['post_max_size_message']; + $uploadMaxSizeMessage = static fn (Options $options) => static fn () => $options['post_max_size_message']; // For any form that is not represented by a single HTML control, // errors should bubble up by default - $errorBubbling = fn (Options $options) => $options['compound'] && !$options['inherit_data']; + $errorBubbling = static fn (Options $options) => $options['compound'] && !$options['inherit_data']; // If data is given, the form is locked to that data // (independent of its value) diff --git a/Extension/Core/Type/LanguageType.php b/Extension/Core/Type/LanguageType.php index 0c6faafec6..eeb9e591a1 100644 --- a/Extension/Core/Type/LanguageType.php +++ b/Extension/Core/Type/LanguageType.php @@ -37,7 +37,7 @@ public function configureOptions(OptionsResolver $resolver) $useAlpha3Codes = $options['alpha3']; $choiceSelfTranslation = $options['choice_self_translation']; - return ChoiceList::loader($this, new IntlCallbackChoiceLoader(function () use ($choiceTranslationLocale, $useAlpha3Codes, $choiceSelfTranslation) { + return ChoiceList::loader($this, new IntlCallbackChoiceLoader(static function () use ($choiceTranslationLocale, $useAlpha3Codes, $choiceSelfTranslation) { if (true === $choiceSelfTranslation) { foreach (Languages::getLanguageCodes() as $alpha2Code) { try { @@ -65,7 +65,7 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('choice_translation_locale', ['null', 'string']); $resolver->setAllowedTypes('alpha3', 'bool'); - $resolver->setNormalizer('choice_self_translation', function (Options $options, $value) { + $resolver->setNormalizer('choice_self_translation', static function (Options $options, $value) { if (true === $value && $options['choice_translation_locale']) { throw new LogicException('Cannot use the "choice_self_translation" and "choice_translation_locale" options at the same time. Remove one of them.'); } diff --git a/Extension/Core/Type/LocaleType.php b/Extension/Core/Type/LocaleType.php index 5086b0b0e6..e98134febd 100644 --- a/Extension/Core/Type/LocaleType.php +++ b/Extension/Core/Type/LocaleType.php @@ -35,7 +35,7 @@ public function configureOptions(OptionsResolver $resolver) $choiceTranslationLocale = $options['choice_translation_locale']; - return ChoiceList::loader($this, new IntlCallbackChoiceLoader(fn () => array_flip(Locales::getNames($choiceTranslationLocale))), $choiceTranslationLocale); + return ChoiceList::loader($this, new IntlCallbackChoiceLoader(static fn () => array_flip(Locales::getNames($choiceTranslationLocale))), $choiceTranslationLocale); }, 'choice_translation_domain' => false, 'choice_translation_locale' => null, diff --git a/Extension/Core/Type/MoneyType.php b/Extension/Core/Type/MoneyType.php index aea35410c1..27c1dbb49b 100644 --- a/Extension/Core/Type/MoneyType.php +++ b/Extension/Core/Type/MoneyType.php @@ -84,7 +84,7 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('html5', 'bool'); - $resolver->setNormalizer('grouping', function (Options $options, $value) { + $resolver->setNormalizer('grouping', static function (Options $options, $value) { if ($value && $options['html5']) { throw new LogicException('Cannot use the "grouping" option when the "html5" option is enabled.'); } diff --git a/Extension/Core/Type/NumberType.php b/Extension/Core/Type/NumberType.php index 3ddfbfeb1c..578991f9fd 100644 --- a/Extension/Core/Type/NumberType.php +++ b/Extension/Core/Type/NumberType.php @@ -85,7 +85,7 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('scale', ['null', 'int']); $resolver->setAllowedTypes('html5', 'bool'); - $resolver->setNormalizer('grouping', function (Options $options, $value) { + $resolver->setNormalizer('grouping', static function (Options $options, $value) { if (true === $value && $options['html5']) { throw new LogicException('Cannot use the "grouping" option when the "html5" option is enabled.'); } diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index a22f2122cd..cc734e50a9 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -61,7 +61,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) } if ('single_text' === $options['widget']) { - $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $e) use ($options) { + $builder->addEventListener(FormEvents::PRE_SUBMIT, static function (FormEvent $e) use ($options) { $data = $e->getData(); if ($data && preg_match('/^(?P\d{2}):(?P\d{2})(?::(?P\d{2})(?:\.\d+)?)?$/', $data, $matches)) { if ($options['with_seconds']) { @@ -79,7 +79,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) if (null !== $options['reference_date']) { $parseFormat = 'Y-m-d '.$format; - $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($options) { + $builder->addEventListener(FormEvents::PRE_SUBMIT, static function (FormEvent $event) use ($options) { $data = $event->getData(); if (preg_match('/^\d{2}:\d{2}(:\d{2})?$/', $data)) { @@ -242,11 +242,11 @@ public function buildView(FormView $view, FormInterface $form, array $options) */ public function configureOptions(OptionsResolver $resolver) { - $compound = fn (Options $options) => 'single_text' !== $options['widget']; + $compound = static fn (Options $options) => 'single_text' !== $options['widget']; - $placeholderDefault = fn (Options $options) => $options['required'] ? null : ''; + $placeholderDefault = static fn (Options $options) => $options['required'] ? null : ''; - $placeholderNormalizer = function (Options $options, $placeholder) use ($placeholderDefault) { + $placeholderNormalizer = static function (Options $options, $placeholder) use ($placeholderDefault) { if (\is_array($placeholder)) { $default = $placeholderDefault($options); @@ -263,7 +263,7 @@ public function configureOptions(OptionsResolver $resolver) ]; }; - $choiceTranslationDomainNormalizer = function (Options $options, $choiceTranslationDomain) { + $choiceTranslationDomainNormalizer = static function (Options $options, $choiceTranslationDomain) { if (\is_array($choiceTranslationDomain)) { $default = false; @@ -327,13 +327,13 @@ public function configureOptions(OptionsResolver $resolver) // representation is not \DateTime, but an array, we need to unset // this option. 'data_class' => null, - 'empty_data' => fn (Options $options) => $options['compound'] ? [] : '', + 'empty_data' => static fn (Options $options) => $options['compound'] ? [] : '', 'compound' => $compound, 'choice_translation_domain' => false, 'invalid_message' => 'Please enter a valid time.', ]); - $resolver->setNormalizer('view_timezone', function (Options $options, $viewTimezone): ?string { + $resolver->setNormalizer('view_timezone', static function (Options $options, $viewTimezone): ?string { if (null !== $options['model_timezone'] && $viewTimezone !== $options['model_timezone'] && null === $options['reference_date']) { throw new LogicException('Using different values for the "model_timezone" and "view_timezone" options without configuring a reference date is not supported.'); } diff --git a/Extension/Core/Type/TimezoneType.php b/Extension/Core/Type/TimezoneType.php index 0827fcfc5a..a5d4bc61c0 100644 --- a/Extension/Core/Type/TimezoneType.php +++ b/Extension/Core/Type/TimezoneType.php @@ -54,10 +54,10 @@ public function configureOptions(OptionsResolver $resolver) $choiceTranslationLocale = $options['choice_translation_locale']; - return ChoiceList::loader($this, new IntlCallbackChoiceLoader(fn () => self::getIntlTimezones($input, $choiceTranslationLocale)), [$input, $choiceTranslationLocale]); + return ChoiceList::loader($this, new IntlCallbackChoiceLoader(static fn () => self::getIntlTimezones($input, $choiceTranslationLocale)), [$input, $choiceTranslationLocale]); } - return ChoiceList::lazy($this, fn () => self::getPhpTimezones($input), $input); + return ChoiceList::lazy($this, static fn () => self::getPhpTimezones($input), $input); }, 'choice_translation_domain' => false, 'choice_translation_locale' => null, @@ -69,7 +69,7 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('intl', ['bool']); $resolver->setAllowedTypes('choice_translation_locale', ['null', 'string']); - $resolver->setNormalizer('choice_translation_locale', function (Options $options, $value) { + $resolver->setNormalizer('choice_translation_locale', static function (Options $options, $value) { if (null !== $value && !$options['intl']) { throw new LogicException('The "choice_translation_locale" option can only be used if the "intl" option is set to true.'); } @@ -78,7 +78,7 @@ public function configureOptions(OptionsResolver $resolver) }); $resolver->setAllowedValues('input', ['string', 'datetimezone', 'intltimezone']); - $resolver->setNormalizer('input', function (Options $options, $value) { + $resolver->setNormalizer('input', static function (Options $options, $value) { if ('intltimezone' === $value && !class_exists(\IntlTimeZone::class)) { throw new LogicException('Cannot use "intltimezone" input because the PHP intl extension is not available.'); } diff --git a/Extension/Core/Type/WeekType.php b/Extension/Core/Type/WeekType.php index f0d8f96467..8027a41a99 100644 --- a/Extension/Core/Type/WeekType.php +++ b/Extension/Core/Type/WeekType.php @@ -100,11 +100,11 @@ public function buildView(FormView $view, FormInterface $form, array $options) */ public function configureOptions(OptionsResolver $resolver) { - $compound = fn (Options $options) => 'single_text' !== $options['widget']; + $compound = static fn (Options $options) => 'single_text' !== $options['widget']; - $placeholderDefault = fn (Options $options) => $options['required'] ? null : ''; + $placeholderDefault = static fn (Options $options) => $options['required'] ? null : ''; - $placeholderNormalizer = function (Options $options, $placeholder) use ($placeholderDefault) { + $placeholderNormalizer = static function (Options $options, $placeholder) use ($placeholderDefault) { if (\is_array($placeholder)) { $default = $placeholderDefault($options); @@ -120,7 +120,7 @@ public function configureOptions(OptionsResolver $resolver) ]; }; - $choiceTranslationDomainNormalizer = function (Options $options, $choiceTranslationDomain) { + $choiceTranslationDomainNormalizer = static function (Options $options, $choiceTranslationDomain) { if (\is_array($choiceTranslationDomain)) { $default = false; @@ -144,7 +144,7 @@ public function configureOptions(OptionsResolver $resolver) 'placeholder' => $placeholderDefault, 'html5' => static fn (Options $options) => 'single_text' === $options['widget'], 'error_bubbling' => false, - 'empty_data' => fn (Options $options) => $options['compound'] ? [] : '', + 'empty_data' => static fn (Options $options) => $options['compound'] ? [] : '', 'compound' => $compound, 'choice_translation_domain' => false, 'invalid_message' => 'Please enter a valid week.', @@ -152,7 +152,7 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setNormalizer('placeholder', $placeholderNormalizer); $resolver->setNormalizer('choice_translation_domain', $choiceTranslationDomainNormalizer); - $resolver->setNormalizer('html5', function (Options $options, $html5) { + $resolver->setNormalizer('html5', static function (Options $options, $html5) { if ($html5 && 'single_text' !== $options['widget']) { throw new LogicException(sprintf('The "widget" option of "%s" must be set to "single_text" when the "html5" option is enabled.', self::class)); } diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index b93bfd82a1..ffce3ac137 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -219,7 +219,7 @@ public function __sleep(): array protected function getCasters(): array { return parent::getCasters() + [ - \Exception::class => function (\Exception $e, array $a, Stub $s) { + \Exception::class => static function (\Exception $e, array $a, Stub $s) { foreach (["\0Exception\0previous", "\0Exception\0trace"] as $k) { if (isset($a[$k])) { unset($a[$k]); @@ -229,12 +229,12 @@ protected function getCasters(): array return $a; }, - FormInterface::class => fn (FormInterface $f, array $a) => [ + FormInterface::class => static fn (FormInterface $f, array $a) => [ Caster::PREFIX_VIRTUAL.'name' => $f->getName(), Caster::PREFIX_VIRTUAL.'type_class' => new ClassStub($f->getConfig()->getType()->getInnerType()::class), ], FormView::class => StubCaster::cutInternals(...), - ConstraintViolationInterface::class => fn (ConstraintViolationInterface $v, array $a) => [ + ConstraintViolationInterface::class => static fn (ConstraintViolationInterface $v, array $a) => [ Caster::PREFIX_VIRTUAL.'root' => $v->getRoot(), Caster::PREFIX_VIRTUAL.'path' => $v->getPropertyPath(), Caster::PREFIX_VIRTUAL.'value' => $v->getInvalidValue(), diff --git a/Extension/Validator/Type/BaseValidatorExtension.php b/Extension/Validator/Type/BaseValidatorExtension.php index 2abc466fe3..ea01d03699 100644 --- a/Extension/Validator/Type/BaseValidatorExtension.php +++ b/Extension/Validator/Type/BaseValidatorExtension.php @@ -30,7 +30,7 @@ abstract class BaseValidatorExtension extends AbstractTypeExtension public function configureOptions(OptionsResolver $resolver) { // Make sure that validation groups end up as null, closure or array - $validationGroupsNormalizer = function (Options $options, $groups) { + $validationGroupsNormalizer = static function (Options $options, $groups) { if (false === $groups) { return []; } diff --git a/Extension/Validator/Type/FormTypeValidatorExtension.php b/Extension/Validator/Type/FormTypeValidatorExtension.php index 4602918c3a..54eebaf63e 100644 --- a/Extension/Validator/Type/FormTypeValidatorExtension.php +++ b/Extension/Validator/Type/FormTypeValidatorExtension.php @@ -53,7 +53,7 @@ public function configureOptions(OptionsResolver $resolver) parent::configureOptions($resolver); // Constraint should always be converted to an array - $constraintsNormalizer = fn (Options $options, $constraints) => \is_object($constraints) ? [$constraints] : (array) $constraints; + $constraintsNormalizer = static fn (Options $options, $constraints) => \is_object($constraints) ? [$constraints] : (array) $constraints; $resolver->setDefaults([ 'error_mapping' => [], diff --git a/Extension/Validator/Type/RepeatedTypeValidatorExtension.php b/Extension/Validator/Type/RepeatedTypeValidatorExtension.php index 2e2c21426a..d41dc0168c 100644 --- a/Extension/Validator/Type/RepeatedTypeValidatorExtension.php +++ b/Extension/Validator/Type/RepeatedTypeValidatorExtension.php @@ -27,7 +27,7 @@ class RepeatedTypeValidatorExtension extends AbstractTypeExtension public function configureOptions(OptionsResolver $resolver) { // Map errors to the first field - $errorMapping = fn (Options $options) => ['.' => $options['first_name']]; + $errorMapping = static fn (Options $options) => ['.' => $options['first_name']]; $resolver->setDefaults([ 'error_mapping' => $errorMapping, diff --git a/Extension/Validator/Type/UploadValidatorExtension.php b/Extension/Validator/Type/UploadValidatorExtension.php index 70034135bf..b7a19ed26a 100644 --- a/Extension/Validator/Type/UploadValidatorExtension.php +++ b/Extension/Validator/Type/UploadValidatorExtension.php @@ -39,7 +39,7 @@ public function configureOptions(OptionsResolver $resolver) { $translator = $this->translator; $translationDomain = $this->translationDomain; - $resolver->setNormalizer('upload_max_size_message', fn (Options $options, $message) => fn () => $translator->trans($message(), [], $translationDomain)); + $resolver->setNormalizer('upload_max_size_message', static fn (Options $options, $message) => static fn () => $translator->trans($message(), [], $translationDomain)); } public static function getExtendedTypes(): iterable diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index 039955b7d4..9a74a125ed 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -66,26 +66,24 @@ public function __construct(MetadataFactoryInterface $metadataFactory) public function guessType(string $class, string $property): ?TypeGuess { - return $this->guess($class, $property, fn (Constraint $constraint) => $this->guessTypeForConstraint($constraint)); + return $this->guess($class, $property, $this->guessTypeForConstraint(...)); } public function guessRequired(string $class, string $property): ?ValueGuess { - return $this->guess($class, $property, function (Constraint $constraint) { - return $this->guessRequiredForConstraint($constraint); - // If we don't find any constraint telling otherwise, we can assume - // that a field is not required (with LOW_CONFIDENCE) - }, false); + // If we don't find any constraint telling otherwise, we can assume + // that a field is not required (with LOW_CONFIDENCE) + return $this->guess($class, $property, $this->guessRequiredForConstraint(...), false); } public function guessMaxLength(string $class, string $property): ?ValueGuess { - return $this->guess($class, $property, fn (Constraint $constraint) => $this->guessMaxLengthForConstraint($constraint)); + return $this->guess($class, $property, $this->guessMaxLengthForConstraint(...)); } public function guessPattern(string $class, string $property): ?ValueGuess { - return $this->guess($class, $property, fn (Constraint $constraint) => $this->guessPatternForConstraint($constraint)); + return $this->guess($class, $property, $this->guessPatternForConstraint(...)); } /** diff --git a/FormTypeGuesserChain.php b/FormTypeGuesserChain.php index 2ac8e3c263..ed94ece6e9 100644 --- a/FormTypeGuesserChain.php +++ b/FormTypeGuesserChain.php @@ -45,22 +45,22 @@ public function __construct(iterable $guessers) public function guessType(string $class, string $property): ?TypeGuess { - return $this->guess(fn ($guesser) => $guesser->guessType($class, $property)); + return $this->guess(static fn ($guesser) => $guesser->guessType($class, $property)); } public function guessRequired(string $class, string $property): ?ValueGuess { - return $this->guess(fn ($guesser) => $guesser->guessRequired($class, $property)); + return $this->guess(static fn ($guesser) => $guesser->guessRequired($class, $property)); } public function guessMaxLength(string $class, string $property): ?ValueGuess { - return $this->guess(fn ($guesser) => $guesser->guessMaxLength($class, $property)); + return $this->guess(static fn ($guesser) => $guesser->guessMaxLength($class, $property)); } public function guessPattern(string $class, string $property): ?ValueGuess { - return $this->guess(fn ($guesser) => $guesser->guessPattern($class, $property)); + return $this->guess(static fn ($guesser) => $guesser->guessPattern($class, $property)); } /** diff --git a/Tests/Fixtures/Descriptor/default_option_with_normalizer.txt b/Tests/Fixtures/Descriptor/default_option_with_normalizer.txt index 4a226f576d..0f6f1f40e7 100644 --- a/Tests/Fixtures/Descriptor/default_option_with_normalizer.txt +++ b/Tests/Fixtures/Descriptor/default_option_with_normalizer.txt @@ -20,7 +20,6 @@ Symfony\Component\Form\Extension\Core\Type\ChoiceType (choice_translation_domain Normalizers [ %s Closure(%s class:%s - this: %s file: %s line: %s } %s From 1909c4afe6961801a1c24ebbcf786550cabb09f8 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 28 Mar 2023 19:29:22 +0200 Subject: [PATCH 094/208] [Form] fix missing static closure --- ChoiceList/ArrayChoiceList.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ChoiceList/ArrayChoiceList.php b/ChoiceList/ArrayChoiceList.php index 2dfc497d3d..2af19b0bf8 100644 --- a/ChoiceList/ArrayChoiceList.php +++ b/ChoiceList/ArrayChoiceList.php @@ -64,7 +64,7 @@ public function __construct(iterable $choices, callable $value = null) } if (null === $value && $this->castableToString($choices)) { - $value = fn ($choice) => false === $choice ? '0' : (string) $choice; + $value = static fn ($choice) => false === $choice ? '0' : (string) $choice; } if (null !== $value) { @@ -72,7 +72,7 @@ public function __construct(iterable $choices, callable $value = null) $this->valueCallback = $value; } else { // Otherwise generate incrementing integers as values - $value = function () { + $value = static function () { static $i = 0; return $i++; From 751efa84f868337c63e29560c02cff7ae27d874b Mon Sep 17 00:00:00 2001 From: Thorry84 Date: Mon, 27 Mar 2023 17:45:10 +0200 Subject: [PATCH 095/208] [Form] CollectionType apply prototypeOptions to ResizeFormListener new fields --- .../Core/EventListener/ResizeFormListener.php | 6 +++-- Extension/Core/Type/CollectionType.php | 4 +++- .../Core/Type/CollectionTypeTest.php | 23 +++++++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index a524e15574..f68d5b6d2c 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -26,18 +26,20 @@ class ResizeFormListener implements EventSubscriberInterface { protected $type; protected $options; + protected $prototypeOptions; protected $allowAdd; protected $allowDelete; private \Closure|bool $deleteEmpty; - public function __construct(string $type, array $options = [], bool $allowAdd = false, bool $allowDelete = false, bool|callable $deleteEmpty = false) + public function __construct(string $type, array $options = [], bool $allowAdd = false, bool $allowDelete = false, bool|callable $deleteEmpty = false, array $prototypeOptions = null) { $this->type = $type; $this->allowAdd = $allowAdd; $this->allowDelete = $allowDelete; $this->options = $options; $this->deleteEmpty = \is_bool($deleteEmpty) ? $deleteEmpty : $deleteEmpty(...); + $this->prototypeOptions = $prototypeOptions ?? $options; } public static function getSubscribedEvents(): array @@ -96,7 +98,7 @@ public function preSubmit(FormEvent $event) if (!$form->has($name)) { $form->add($name, $this->type, array_replace([ 'property_path' => '['.$name.']', - ], $this->options)); + ], $this->prototypeOptions)); } } } diff --git a/Extension/Core/Type/CollectionType.php b/Extension/Core/Type/CollectionType.php index c310441cc7..f93c36abbb 100644 --- a/Extension/Core/Type/CollectionType.php +++ b/Extension/Core/Type/CollectionType.php @@ -23,6 +23,7 @@ class CollectionType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { + $prototypeOptions = null; if ($options['allow_add'] && $options['prototype']) { $prototypeOptions = array_replace([ 'required' => $options['required'], @@ -42,7 +43,8 @@ public function buildForm(FormBuilderInterface $builder, array $options) $options['entry_options'], $options['allow_add'], $options['allow_delete'], - $options['delete_empty'] + $options['delete_empty'], + $prototypeOptions ); $builder->addEventSubscriber($resizeListener); diff --git a/Tests/Extension/Core/Type/CollectionTypeTest.php b/Tests/Extension/Core/Type/CollectionTypeTest.php index c7e10307b2..8162611048 100644 --- a/Tests/Extension/Core/Type/CollectionTypeTest.php +++ b/Tests/Extension/Core/Type/CollectionTypeTest.php @@ -447,6 +447,29 @@ public function testPrototypeOptionsOverrideEntryOptions() $this->assertSame('foo', $form->createView()->vars['prototype']->vars['help']); } + public function testPrototypeOptionsAppliedToNewFields() + { + $form = $this->factory->create(static::TESTED_TYPE, ['first'], [ + 'allow_add' => true, + 'prototype' => true, + 'entry_type' => TextTypeTest::TESTED_TYPE, + 'entry_options' => [ + 'disabled' => true, + ], + 'prototype_options' => [ + 'disabled' => false, + ], + ]); + + $form->submit(['first_changed', 'second']); + + $this->assertTrue($form->has('0')); + $this->assertTrue($form->has('1')); + $this->assertSame('first', $form[0]->getData()); + $this->assertSame('second', $form[1]->getData()); + $this->assertSame(['first', 'second'], $form->getData()); + } + public function testEntriesBlockPrefixes() { $collectionView = $this->factory->createNamed('fields', static::TESTED_TYPE, [''], [ From 6eada4eca980cc616c8d24ba90f055f7a9e2781b Mon Sep 17 00:00:00 2001 From: Yassine Guedidi Date: Sun, 2 Apr 2023 04:08:55 +0200 Subject: [PATCH 096/208] Apply operator_linebreak PHP-CS-Fixer rule --- Form.php | 6 +++--- Guess/Guess.php | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Form.php b/Form.php index 851d56a46d..a4b76506a2 100644 --- a/Form.php +++ b/Form.php @@ -636,11 +636,11 @@ public function isEmpty(): bool return $isEmptyCallback($this->modelData); } - return FormUtil::isEmpty($this->modelData) || + return FormUtil::isEmpty($this->modelData) // arrays, countables - (is_countable($this->modelData) && 0 === \count($this->modelData)) || + || (is_countable($this->modelData) && 0 === \count($this->modelData)) // traversables that are not countable - ($this->modelData instanceof \Traversable && 0 === iterator_count($this->modelData)); + || ($this->modelData instanceof \Traversable && 0 === iterator_count($this->modelData)); } public function isValid(): bool diff --git a/Guess/Guess.php b/Guess/Guess.php index abe09cb39f..fc19ed9cee 100644 --- a/Guess/Guess.php +++ b/Guess/Guess.php @@ -80,8 +80,8 @@ public static function getBestGuess(array $guesses): ?static */ public function __construct(int $confidence) { - if (self::VERY_HIGH_CONFIDENCE !== $confidence && self::HIGH_CONFIDENCE !== $confidence && - self::MEDIUM_CONFIDENCE !== $confidence && self::LOW_CONFIDENCE !== $confidence) { + if (self::VERY_HIGH_CONFIDENCE !== $confidence && self::HIGH_CONFIDENCE !== $confidence + && self::MEDIUM_CONFIDENCE !== $confidence && self::LOW_CONFIDENCE !== $confidence) { throw new InvalidArgumentException('The confidence should be one of the constants defined in Guess.'); } From f60e331c6f72455335c4788594a13b429f4b4d8d Mon Sep 17 00:00:00 2001 From: Antoine Lamirault Date: Mon, 27 Mar 2023 20:06:57 +0200 Subject: [PATCH 097/208] Harmonize command formats and ensure autocompletion is same --- Command/DebugCommand.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index 5e4635870a..4a142e2965 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -64,7 +64,7 @@ protected function configure() new InputArgument('class', InputArgument::OPTIONAL, 'The form type class'), new InputArgument('option', InputArgument::OPTIONAL, 'The form type option'), new InputOption('show-deprecated', null, InputOption::VALUE_NONE, 'Display deprecated options in form types'), - new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt or json)', 'txt'), + new InputOption('format', null, InputOption::VALUE_REQUIRED, sprintf('The output format ("%s")', implode('", "', $this->getAvailableFormatOptions())), 'txt'), ]) ->setHelp(<<<'EOF' The %command.name% command displays information about form types. @@ -261,8 +261,7 @@ public function complete(CompletionInput $input, CompletionSuggestions $suggesti } if ($input->mustSuggestOptionValuesFor('format')) { - $helper = new DescriptorHelper(); - $suggestions->suggestValues($helper->getFormats()); + $suggestions->suggestValues($this->getAvailableFormatOptions()); } } @@ -283,4 +282,9 @@ private function completeOptions(string $class, CompletionSuggestions $suggestio $resolvedType = $this->formRegistry->getType($class); $suggestions->suggestValues($resolvedType->getOptionsResolver()->getDefinedOptions()); } + + private function getAvailableFormatOptions(): array + { + return (new DescriptorHelper())->getFormats(); + } } From a123512b46caea497ab8d96d9dbdbdaaf416a606 Mon Sep 17 00:00:00 2001 From: Thorry84 Date: Tue, 18 Apr 2023 21:07:28 +0200 Subject: [PATCH 098/208] [Form] Fix "prototype_data" option creating duplicates instead of new lines --- Extension/Core/Type/CollectionType.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Extension/Core/Type/CollectionType.php b/Extension/Core/Type/CollectionType.php index f93c36abbb..6e4d0381de 100644 --- a/Extension/Core/Type/CollectionType.php +++ b/Extension/Core/Type/CollectionType.php @@ -23,12 +23,13 @@ class CollectionType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { - $prototypeOptions = null; + $resizePrototypeOptions = null; if ($options['allow_add'] && $options['prototype']) { + $resizePrototypeOptions = array_replace($options['entry_options'], $options['prototype_options']); $prototypeOptions = array_replace([ 'required' => $options['required'], 'label' => $options['prototype_name'].'label__', - ], array_replace($options['entry_options'], $options['prototype_options'])); + ], $resizePrototypeOptions); if (null !== $options['prototype_data']) { $prototypeOptions['data'] = $options['prototype_data']; @@ -44,7 +45,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) $options['allow_add'], $options['allow_delete'], $options['delete_empty'], - $prototypeOptions + $resizePrototypeOptions ); $builder->addEventSubscriber($resizeListener); From acdaab8bf1d664fe732a6d851faf3143f780de0e Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Wed, 19 Apr 2023 11:03:56 +0200 Subject: [PATCH 099/208] [Form] Don't render seconds for HTML5 date pickers unless "with_seconds" is explicitly set --- CHANGELOG.md | 1 + ...ateTimeToHtml5LocalDateTimeTransformer.php | 8 ++++++- Extension/Core/Type/DateTimeType.php | 11 ++++++--- Extension/Core/Type/TimeType.php | 8 +++++-- Tests/AbstractLayoutTestCase.php | 2 +- ...imeToHtml5LocalDateTimeTransformerTest.php | 24 +++++++++++-------- .../Extension/Core/Type/DateTimeTypeTest.php | 10 ++++---- composer.json | 2 +- 8 files changed, 43 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf21889169..f07efb05d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ CHANGELOG 6.3 --- + * Don't render seconds for HTML5 date pickers unless "with_seconds" is explicitly set * Add a `placeholder_attr` option to `ChoiceType` 6.2 diff --git a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php index 40cd1b89df..a59ad9cb72 100644 --- a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php @@ -23,6 +23,12 @@ class DateTimeToHtml5LocalDateTimeTransformer extends BaseDateTimeTransformer { public const HTML5_FORMAT = 'Y-m-d\\TH:i:s'; + public const HTML5_FORMAT_NO_SECONDS = 'Y-m-d\\TH:i'; + + public function __construct(string $inputTimezone = null, string $outputTimezone = null, private bool $withSeconds = false) + { + parent::__construct($inputTimezone, $outputTimezone); + } /** * Transforms a \DateTime into a local date and time string. @@ -54,7 +60,7 @@ public function transform(mixed $dateTime): string $dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone)); } - return $dateTime->format(self::HTML5_FORMAT); + return $dateTime->format($this->withSeconds ? self::HTML5_FORMAT : self::HTML5_FORMAT_NO_SECONDS); } /** diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index a0a0c92fe0..7a52acc720 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -79,7 +79,8 @@ public function buildForm(FormBuilderInterface $builder, array $options) if (self::HTML5_FORMAT === $pattern) { $builder->addViewTransformer(new DateTimeToHtml5LocalDateTimeTransformer( $options['model_timezone'], - $options['view_timezone'] + $options['view_timezone'], + $options['with_seconds'] )); } else { $builder->addViewTransformer(new DateTimeToLocalizedStringTransformer( @@ -218,8 +219,12 @@ public function buildView(FormView $view, FormInterface $form, array $options) // adding the HTML attribute step if not already defined. // Otherwise the browser will not display and so not send the seconds // therefore the value will always be considered as invalid. - if ($options['with_seconds'] && !isset($view->vars['attr']['step'])) { - $view->vars['attr']['step'] = 1; + if (!isset($view->vars['attr']['step'])) { + if ($options['with_seconds']) { + $view->vars['attr']['step'] = 1; + } elseif (!$options['with_minutes']) { + $view->vars['attr']['step'] = 3600; + } } } } diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index cc734e50a9..249c229957 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -231,8 +231,12 @@ public function buildView(FormView $view, FormInterface $form, array $options) // adding the HTML attribute step if not already defined. // Otherwise the browser will not display and so not send the seconds // therefore the value will always be considered as invalid. - if ($options['with_seconds'] && !isset($view->vars['attr']['step'])) { - $view->vars['attr']['step'] = 1; + if (!isset($view->vars['attr']['step'])) { + if ($options['with_seconds']) { + $view->vars['attr']['step'] = 1; + } elseif (!$options['with_minutes']) { + $view->vars['attr']['step'] = 3600; + } } } } diff --git a/Tests/AbstractLayoutTestCase.php b/Tests/AbstractLayoutTestCase.php index 744212d1f4..098e971ec6 100644 --- a/Tests/AbstractLayoutTestCase.php +++ b/Tests/AbstractLayoutTestCase.php @@ -1523,7 +1523,7 @@ public function testDateTimeWithWidgetSingleText() '/input [@type="datetime-local"] [@name="name"] - [@value="2011-02-03T04:05:06"] + [@value="2011-02-03T04:05"] ' ); } diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php index 8dffb13e2f..bcea2b8296 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformerTest.php @@ -23,12 +23,16 @@ class DateTimeToHtml5LocalDateTimeTransformerTest extends BaseDateTimeTransforme public static function transformProvider() { return [ - ['UTC', 'UTC', '2010-02-03 04:05:06 UTC', '2010-02-03T04:05:06'], - ['UTC', 'UTC', null, ''], - ['America/New_York', 'Asia/Hong_Kong', '2010-02-03 04:05:06 America/New_York', '2010-02-03T17:05:06'], - ['America/New_York', 'Asia/Hong_Kong', null, ''], - ['UTC', 'Asia/Hong_Kong', '2010-02-03 04:05:06 UTC', '2010-02-03T12:05:06'], - ['America/New_York', 'UTC', '2010-02-03 04:05:06 America/New_York', '2010-02-03T09:05:06'], + ['UTC', 'UTC', '2010-02-03 04:05:06 UTC', '2010-02-03T04:05:06', true], + ['UTC', 'UTC', null, '', true], + ['America/New_York', 'Asia/Hong_Kong', '2010-02-03 04:05:06 America/New_York', '2010-02-03T17:05:06', true], + ['America/New_York', 'Asia/Hong_Kong', null, '', true], + ['UTC', 'Asia/Hong_Kong', '2010-02-03 04:05:06 UTC', '2010-02-03T12:05:06', true], + ['America/New_York', 'UTC', '2010-02-03 04:05:06 America/New_York', '2010-02-03T09:05:06', true], + ['UTC', 'UTC', '2010-02-03 04:05:06 UTC', '2010-02-03T04:05', false], + ['America/New_York', 'Asia/Hong_Kong', '2010-02-03 04:05:06 America/New_York', '2010-02-03T17:05', false], + ['UTC', 'Asia/Hong_Kong', '2010-02-03 04:05:06 UTC', '2010-02-03T12:05', false], + ['America/New_York', 'UTC', '2010-02-03 04:05:06 America/New_York', '2010-02-03T09:05', false], ]; } @@ -55,9 +59,9 @@ public static function reverseTransformProvider() /** * @dataProvider transformProvider */ - public function testTransform($fromTz, $toTz, $from, $to) + public function testTransform($fromTz, $toTz, $from, $to, bool $withSeconds) { - $transformer = new DateTimeToHtml5LocalDateTimeTransformer($fromTz, $toTz); + $transformer = new DateTimeToHtml5LocalDateTimeTransformer($fromTz, $toTz, $withSeconds); $this->assertSame($to, $transformer->transform(null !== $from ? new \DateTime($from) : null)); } @@ -65,9 +69,9 @@ public function testTransform($fromTz, $toTz, $from, $to) /** * @dataProvider transformProvider */ - public function testTransformDateTimeImmutable($fromTz, $toTz, $from, $to) + public function testTransformDateTimeImmutable($fromTz, $toTz, $from, $to, bool $withSeconds) { - $transformer = new DateTimeToHtml5LocalDateTimeTransformer($fromTz, $toTz); + $transformer = new DateTimeToHtml5LocalDateTimeTransformer($fromTz, $toTz, $withSeconds); $this->assertSame($to, $transformer->transform(null !== $from ? new \DateTimeImmutable($from) : null)); } diff --git a/Tests/Extension/Core/Type/DateTimeTypeTest.php b/Tests/Extension/Core/Type/DateTimeTypeTest.php index e30bd416a8..e7ffc24fa7 100644 --- a/Tests/Extension/Core/Type/DateTimeTypeTest.php +++ b/Tests/Extension/Core/Type/DateTimeTypeTest.php @@ -252,7 +252,7 @@ public function testSubmitDifferentTimezonesDateTime() $outputTime->setTimezone(new \DateTimeZone('America/New_York')); $this->assertEquals($outputTime, $form->getData()); - $this->assertEquals('2010-06-02T03:04:00', $form->getViewData()); + $this->assertEquals('2010-06-02T03:04', $form->getViewData()); } public function testSubmitDifferentTimezonesDateTimeImmutable() @@ -272,7 +272,7 @@ public function testSubmitDifferentTimezonesDateTimeImmutable() $this->assertInstanceOf(\DateTimeImmutable::class, $form->getData()); $this->assertEquals($outputTime, $form->getData()); - $this->assertEquals('2010-06-02T03:04:00', $form->getViewData()); + $this->assertEquals('2010-06-02T03:04', $form->getViewData()); } public function testSubmitStringSingleText() @@ -287,7 +287,7 @@ public function testSubmitStringSingleText() $form->submit('2010-06-02T03:04:00'); $this->assertEquals('2010-06-02 03:04:00', $form->getData()); - $this->assertEquals('2010-06-02T03:04:00', $form->getViewData()); + $this->assertEquals('2010-06-02T03:04', $form->getViewData()); } public function testSubmitStringSingleTextWithSeconds() @@ -709,10 +709,10 @@ public function testSubmitNullUsesDateEmptyData($widget, $emptyData, $expectedDa public static function provideEmptyData() { $expectedData = \DateTime::createFromFormat('Y-m-d H:i', '2018-11-11 21:23'); - $lazyEmptyData = static fn (FormInterface $form) => $form->getConfig()->getCompound() ? ['date' => ['year' => '2018', 'month' => '11', 'day' => '11'], 'time' => ['hour' => '21', 'minute' => '23']] : '2018-11-11T21:23:00'; + $lazyEmptyData = static fn (FormInterface $form) => $form->getConfig()->getCompound() ? ['date' => ['year' => '2018', 'month' => '11', 'day' => '11'], 'time' => ['hour' => '21', 'minute' => '23']] : '2018-11-11T21:23'; return [ - 'Simple field' => ['single_text', '2018-11-11T21:23:00', $expectedData], + 'Simple field' => ['single_text', '2018-11-11T21:23', $expectedData], 'Compound text field' => ['text', ['date' => ['year' => '2018', 'month' => '11', 'day' => '11'], 'time' => ['hour' => '21', 'minute' => '23']], $expectedData], 'Compound choice field' => ['choice', ['date' => ['year' => '2018', 'month' => '11', 'day' => '11'], 'time' => ['hour' => '21', 'minute' => '23']], $expectedData], 'Simple field lazy' => ['single_text', $lazyEmptyData, $expectedData], diff --git a/composer.json b/composer.json index 5512aa4d18..df506d699b 100644 --- a/composer.json +++ b/composer.json @@ -53,7 +53,7 @@ "symfony/http-kernel": "<5.4", "symfony/translation": "<5.4", "symfony/translation-contracts": "<2.5", - "symfony/twig-bridge": "<5.4.21|>=6,<6.2.7" + "symfony/twig-bridge": "<6.3" }, "suggest": { "symfony/validator": "For form validation.", From 9b87b8b9cd05e460d1f4b440db86fc64aafe316a Mon Sep 17 00:00:00 2001 From: MrYamous Date: Sun, 12 Mar 2023 00:50:02 +0100 Subject: [PATCH 100/208] deprecate not configuring widget option for DateType, DateTimeType, TimeType --- Extension/Core/Type/DateTimeType.php | 7 ++++++- Extension/Core/Type/DateType.php | 7 ++++++- Extension/Core/Type/TimeType.php | 7 ++++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index 7a52acc720..8bd6ec471a 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -248,7 +248,12 @@ public function configureOptions(OptionsResolver $resolver) 'view_timezone' => null, 'format' => self::HTML5_FORMAT, 'date_format' => null, - 'widget' => null, + 'widget' => function (Options $options) { + trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option is deprecated. It will default to "single_text" in Symfony 7.0.'); + + return null; + // return 'single_text'; + }, 'date_widget' => $dateWidget, 'time_widget' => $timeWidget, 'with_minutes' => true, diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index 5c81097e0e..3d01546f95 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -260,7 +260,12 @@ public function configureOptions(OptionsResolver $resolver) 'years' => range((int) date('Y') - 5, (int) date('Y') + 5), 'months' => range(1, 12), 'days' => range(1, 31), - 'widget' => 'choice', + 'widget' => function (Options $options) { + trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option explicitly is deprecated, its default value will change to "single_text" in 7.0.'); + + return 'choice'; + // return 'single_text'; + }, 'input' => 'datetime', 'format' => $format, 'model_timezone' => null, diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 249c229957..cad07d9299 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -312,7 +312,12 @@ public function configureOptions(OptionsResolver $resolver) 'hours' => range(0, 23), 'minutes' => range(0, 59), 'seconds' => range(0, 59), - 'widget' => 'choice', + 'widget' => function (Options $options) { + trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option explicitly is deprecated, its default value will change to "single_text" in 7.0.'); + + return 'choice'; + // return 'single_text'; + }, 'input' => 'datetime', 'input_format' => 'H:i:s', 'with_minutes' => true, From fad0f3dde98505d91c4ab208230f4beb794d7792 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 18 Apr 2023 23:21:31 +0200 Subject: [PATCH 101/208] [Form] Fix deprecation layer --- CHANGELOG.md | 1 + Extension/Core/Type/DateTimeType.php | 49 +++++++------------ Extension/Core/Type/DateType.php | 5 +- Extension/Core/Type/TimeType.php | 5 +- Tests/AbstractLayoutTestCase.php | 16 ++++-- Tests/Extension/Core/CoreExtensionTest.php | 2 +- .../Extension/Core/Type/BirthdayTypeTest.php | 1 + .../Extension/Core/Type/DateTimeTypeTest.php | 23 +++++++-- Tests/Extension/Core/Type/DateTypeTest.php | 39 +++++++++++++-- Tests/Extension/Core/Type/TimeTypeTest.php | 45 ++++++++++++++++- .../BirthdayTypeValidatorExtensionTest.php | 2 +- .../DateTimeTypeValidatorExtensionTest.php | 2 +- .../Type/DateTypeValidatorExtensionTest.php | 2 +- .../Type/TimeTypeValidatorExtensionTest.php | 2 +- 14 files changed, 140 insertions(+), 54 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f07efb05d4..1ff39c9726 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ CHANGELOG * Don't render seconds for HTML5 date pickers unless "with_seconds" is explicitly set * Add a `placeholder_attr` option to `ChoiceType` + * Deprecate not configuring the "widget" option of date/time form types, it will default to "single_text" in v7 6.2 --- diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index 8bd6ec471a..32c58447cd 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -148,18 +148,13 @@ public function buildForm(FormBuilderInterface $builder, array $options) $timeOptions['label'] = false; } - if (null !== $options['date_widget']) { - $dateOptions['widget'] = $options['date_widget']; - } + $dateOptions['widget'] = $options['date_widget'] ?? $options['widget'] ?? 'choice'; + $timeOptions['widget'] = $options['time_widget'] ?? $options['widget'] ?? 'choice'; if (null !== $options['date_label']) { $dateOptions['label'] = $options['date_label']; } - if (null !== $options['time_widget']) { - $timeOptions['widget'] = $options['time_widget']; - } - if (null !== $options['time_label']) { $timeOptions['label'] = $options['time_label']; } @@ -236,26 +231,15 @@ public function configureOptions(OptionsResolver $resolver) { $compound = static fn (Options $options) => 'single_text' !== $options['widget']; - // Defaults to the value of "widget" - $dateWidget = static fn (Options $options) => 'single_text' === $options['widget'] ? null : $options['widget']; - - // Defaults to the value of "widget" - $timeWidget = static fn (Options $options) => 'single_text' === $options['widget'] ? null : $options['widget']; - $resolver->setDefaults([ 'input' => 'datetime', 'model_timezone' => null, 'view_timezone' => null, 'format' => self::HTML5_FORMAT, 'date_format' => null, - 'widget' => function (Options $options) { - trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option is deprecated. It will default to "single_text" in Symfony 7.0.'); - - return null; - // return 'single_text'; - }, - 'date_widget' => $dateWidget, - 'time_widget' => $timeWidget, + 'widget' => null, + 'date_widget' => null, + 'time_widget' => null, 'with_minutes' => true, 'with_seconds' => false, 'html5' => true, @@ -325,19 +309,20 @@ public function configureOptions(OptionsResolver $resolver) return $dateFormat; }); - $resolver->setNormalizer('date_widget', static function (Options $options, $dateWidget) { - if (null !== $dateWidget && 'single_text' === $options['widget']) { - throw new LogicException(sprintf('Cannot use the "date_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class)); - } - - return $dateWidget; - }); - $resolver->setNormalizer('time_widget', static function (Options $options, $timeWidget) { - if (null !== $timeWidget && 'single_text' === $options['widget']) { - throw new LogicException(sprintf('Cannot use the "time_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class)); + $resolver->setNormalizer('widget', static function (Options $options, $widget) { + if ('single_text' === $widget) { + if (null !== $options['date_widget']) { + throw new LogicException(sprintf('Cannot use the "date_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class)); + } + if (null !== $options['time_widget']) { + throw new LogicException(sprintf('Cannot use the "time_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class)); + } + } elseif (null === $widget && null === $options['date_widget'] && null === $options['time_widget']) { + trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option of form type "datetime" is deprecated. It will default to "single_text" in Symfony 7.0.'); + // return 'single_text'; } - return $timeWidget; + return $widget; }); $resolver->setNormalizer('html5', static function (Options $options, $html5) { if ($html5 && self::HTML5_FORMAT !== $options['format']) { diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index 3d01546f95..5c079f137d 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -260,11 +260,10 @@ public function configureOptions(OptionsResolver $resolver) 'years' => range((int) date('Y') - 5, (int) date('Y') + 5), 'months' => range(1, 12), 'days' => range(1, 31), - 'widget' => function (Options $options) { - trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option explicitly is deprecated, its default value will change to "single_text" in 7.0.'); + 'widget' => static function (Options $options) { + trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option of form type "date" is deprecated. It will default to "single_text" in Symfony 7.0.'); return 'choice'; - // return 'single_text'; }, 'input' => 'datetime', 'format' => $format, diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index cad07d9299..c7d5276960 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -312,11 +312,10 @@ public function configureOptions(OptionsResolver $resolver) 'hours' => range(0, 23), 'minutes' => range(0, 59), 'seconds' => range(0, 59), - 'widget' => function (Options $options) { - trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option explicitly is deprecated, its default value will change to "single_text" in 7.0.'); + 'widget' => static function (Options $options) { + trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option of form type "time" is deprecated. It will default to "single_text" in Symfony 7.0.'); return 'choice'; - // return 'single_text'; }, 'input' => 'datetime', 'input_format' => 'H:i:s', diff --git a/Tests/AbstractLayoutTestCase.php b/Tests/AbstractLayoutTestCase.php index 098e971ec6..33799bfcc1 100644 --- a/Tests/AbstractLayoutTestCase.php +++ b/Tests/AbstractLayoutTestCase.php @@ -175,7 +175,7 @@ public function testLabelWithoutTranslation() public function testLabelOnForm() { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType'); + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType', null, ['widget' => 'choice']); $view = $form->createView(); $this->renderWidget($view, ['label' => 'foo']); $html = $this->renderLabel($view); @@ -1327,6 +1327,7 @@ public function testDateTime() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', date('Y').'-02-03 04:05:06', [ 'input' => 'string', 'with_seconds' => false, + 'widget' => 'choice', ]); $this->assertWidgetMatchesXpath($form->createView(), [], @@ -1367,6 +1368,7 @@ public function testDateTimeWithPlaceholderGlobal() 'input' => 'string', 'placeholder' => 'Change&Me', 'required' => false, + 'widget' => 'choice', ]); $this->assertWidgetMatchesXpath($form->createView(), [], @@ -1408,6 +1410,7 @@ public function testDateTimeWithHourAndMinute() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', $data, [ 'input' => 'array', 'required' => false, + 'widget' => 'choice', ]); $this->assertWidgetMatchesXpath($form->createView(), [], @@ -1447,6 +1450,7 @@ public function testDateTimeWithSeconds() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', date('Y').'-02-03 04:05:06', [ 'input' => 'string', 'with_seconds' => true, + 'widget' => 'choice', ]); $this->assertWidgetMatchesXpath($form->createView(), [], @@ -1654,7 +1658,7 @@ public function testDateSingleText() public function testDateErrorBubbling() { $form = $this->factory->createNamedBuilder('form', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('date', 'Symfony\Component\Form\Extension\Core\Type\DateType') + ->add('date', 'Symfony\Component\Form\Extension\Core\Type\DateType', ['widget' => 'choice']) ->getForm(); $form->get('date')->addError(new FormError('[trans]Error![/trans]')); $view = $form->createView(); @@ -1667,6 +1671,7 @@ public function testBirthDay() { $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\BirthdayType', '2000-02-03', [ 'input' => 'string', + 'widget' => 'choice', ]); $this->assertWidgetMatchesXpath($form->createView(), [], @@ -1693,6 +1698,7 @@ public function testBirthDayWithPlaceholder() 'input' => 'string', 'placeholder' => '', 'required' => false, + 'widget' => 'choice', ]); $this->assertWidgetMatchesXpath($form->createView(), [], @@ -2127,6 +2133,7 @@ public function testTime() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TimeType', '04:05:06', [ 'input' => 'string', 'with_seconds' => false, + 'widget' => 'choice', ]); $this->assertWidgetMatchesXpath($form->createView(), [], @@ -2151,6 +2158,7 @@ public function testTimeWithSeconds() $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TimeType', '04:05:06', [ 'input' => 'string', 'with_seconds' => true, + 'widget' => 'choice', ]); $this->assertWidgetMatchesXpath($form->createView(), [], @@ -2230,6 +2238,7 @@ public function testTimeWithPlaceholderGlobal() 'input' => 'string', 'placeholder' => 'Change&Me', 'required' => false, + 'widget' => 'choice', ]); $this->assertWidgetMatchesXpath($form->createView(), [], @@ -2255,6 +2264,7 @@ public function testTimeWithPlaceholderOnYear() 'input' => 'string', 'required' => false, 'placeholder' => ['hour' => 'Change&Me'], + 'widget' => 'choice', ]); $this->assertWidgetMatchesXpath($form->createView(), [], @@ -2277,7 +2287,7 @@ public function testTimeWithPlaceholderOnYear() public function testTimeErrorBubbling() { $form = $this->factory->createNamedBuilder('form', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('time', 'Symfony\Component\Form\Extension\Core\Type\TimeType') + ->add('time', 'Symfony\Component\Form\Extension\Core\Type\TimeType', ['widget' => 'choice']) ->getForm(); $form->get('time')->addError(new FormError('[trans]Error![/trans]')); $view = $form->createView(); diff --git a/Tests/Extension/Core/CoreExtensionTest.php b/Tests/Extension/Core/CoreExtensionTest.php index ff85149e21..91b1e75086 100644 --- a/Tests/Extension/Core/CoreExtensionTest.php +++ b/Tests/Extension/Core/CoreExtensionTest.php @@ -24,7 +24,7 @@ public function testTransformationFailuresAreConvertedIntoFormErrors() ->getFormFactory(); $form = $formFactory->createBuilder() - ->add('foo', 'Symfony\Component\Form\Extension\Core\Type\DateType') + ->add('foo', 'Symfony\Component\Form\Extension\Core\Type\DateType', ['widget' => 'choice']) ->getForm(); $form->submit('foo'); diff --git a/Tests/Extension/Core/Type/BirthdayTypeTest.php b/Tests/Extension/Core/Type/BirthdayTypeTest.php index 47028ac014..0484571411 100644 --- a/Tests/Extension/Core/Type/BirthdayTypeTest.php +++ b/Tests/Extension/Core/Type/BirthdayTypeTest.php @@ -25,6 +25,7 @@ public function testSetInvalidYearsOption() $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'years' => 'bad value', + 'widget' => 'choice', ]); } } diff --git a/Tests/Extension/Core/Type/DateTimeTypeTest.php b/Tests/Extension/Core/Type/DateTimeTypeTest.php index e7ffc24fa7..a2058596ee 100644 --- a/Tests/Extension/Core/Type/DateTimeTypeTest.php +++ b/Tests/Extension/Core/Type/DateTimeTypeTest.php @@ -330,7 +330,7 @@ public function testInitializeWithDateTime() { // Throws an exception if "data_class" option is not explicitly set // to null in the type - $this->assertInstanceOf(FormInterface::class, $this->factory->create(static::TESTED_TYPE, new \DateTime())); + $this->assertInstanceOf(FormInterface::class, $this->factory->create(static::TESTED_TYPE, new \DateTime(), ['widget' => 'choice'])); } public function testSingleTextWidgetShouldUseTheRightInputType() @@ -348,6 +348,7 @@ public function testPassDefaultPlaceholderToViewIfNotRequired() $view = $this->factory->create(static::TESTED_TYPE, null, [ 'required' => false, 'with_seconds' => true, + 'widget' => 'choice', ]) ->createView(); @@ -364,6 +365,7 @@ public function testPassNoPlaceholderToViewIfRequired() $view = $this->factory->create(static::TESTED_TYPE, null, [ 'required' => true, 'with_seconds' => true, + 'widget' => 'choice', ]) ->createView(); @@ -380,6 +382,7 @@ public function testPassPlaceholderAsString() $view = $this->factory->create(static::TESTED_TYPE, null, [ 'placeholder' => 'Empty', 'with_seconds' => true, + 'widget' => 'choice', ]) ->createView(); @@ -403,6 +406,7 @@ public function testPassPlaceholderAsArray() 'second' => 'Empty second', ], 'with_seconds' => true, + 'widget' => 'choice', ]) ->createView(); @@ -425,6 +429,7 @@ public function testPassPlaceholderAsPartialArrayAddEmptyIfNotRequired() 'second' => 'Empty second', ], 'with_seconds' => true, + 'widget' => 'choice', ]) ->createView(); @@ -447,6 +452,7 @@ public function testPassPlaceholderAsPartialArrayAddNullIfRequired() 'second' => 'Empty second', ], 'with_seconds' => true, + 'widget' => 'choice', ]) ->createView(); @@ -536,7 +542,7 @@ public function testSingleTextWidgetWithCustomNonHtml5Format() public function testDateTypeChoiceErrorsBubbleUp() { $error = new FormError('Invalid!'); - $form = $this->factory->create(static::TESTED_TYPE, null); + $form = $this->factory->create(static::TESTED_TYPE, null, ['widget' => 'choice']); $form['date']->addError($error); @@ -549,6 +555,7 @@ public function testDateTypeSingleTextErrorsBubbleUp() $error = new FormError('Invalid!'); $form = $this->factory->create(static::TESTED_TYPE, null, [ 'date_widget' => 'single_text', + 'time_widget' => 'choice', ]); $form['date']->addError($error); @@ -560,7 +567,7 @@ public function testDateTypeSingleTextErrorsBubbleUp() public function testTimeTypeChoiceErrorsBubbleUp() { $error = new FormError('Invalid!'); - $form = $this->factory->create(static::TESTED_TYPE, null); + $form = $this->factory->create(static::TESTED_TYPE, null, ['widget' => 'choice']); $form['time']->addError($error); @@ -573,6 +580,7 @@ public function testTimeTypeSingleTextErrorsBubbleUp() $error = new FormError('Invalid!'); $form = $this->factory->create(static::TESTED_TYPE, null, [ 'time_widget' => 'single_text', + 'date_widget' => 'choice', ]); $form['time']->addError($error); @@ -585,6 +593,7 @@ public function testPassDefaultChoiceTranslationDomain() { $form = $this->factory->create(static::TESTED_TYPE, null, [ 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -602,6 +611,7 @@ public function testPassChoiceTranslationDomainAsString() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'choice_translation_domain' => 'messages', 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -623,6 +633,7 @@ public function testPassChoiceTranslationDomainAsArray() 'second' => 'test', ], 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -675,6 +686,7 @@ public function testSubmitNullUsesDefaultEmptyData($emptyData = [], $expectedDat { $form = $this->factory->create(static::TESTED_TYPE, null, [ 'empty_data' => $emptyData, + 'widget' => 'choice', ]); $form->submit(null); @@ -735,4 +747,9 @@ public function testSubmitStringWithCustomInputFormat() $this->assertSame('14/01/2018 21:29:00 +00:00', $form->getData()); } + + protected function getTestOptions(): array + { + return ['widget' => 'choice']; + } } diff --git a/Tests/Extension/Core/Type/DateTypeTest.php b/Tests/Extension/Core/Type/DateTypeTest.php index 0527e48904..abda1a6c07 100644 --- a/Tests/Extension/Core/Type/DateTypeTest.php +++ b/Tests/Extension/Core/Type/DateTypeTest.php @@ -50,6 +50,7 @@ public function testInvalidInputOption() $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'input' => 'fake_input', + 'widget' => 'choice', ]); } @@ -379,6 +380,7 @@ public function testDatePatternWithFormatOption($format, $pattern) { $view = $this->factory->create(static::TESTED_TYPE, null, [ 'format' => $format, + 'widget' => 'choice', ]) ->createView(); @@ -416,6 +418,7 @@ public function testThrowExceptionIfFormatDoesNotContainYearMonthAndDay() $this->factory->create(static::TESTED_TYPE, null, [ 'months' => [6, 7], 'format' => 'yy', + 'widget' => 'choice', ]); } @@ -435,6 +438,7 @@ public function testThrowExceptionIfFormatIsNoConstant() $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'format' => 105, + 'widget' => 'choice', ]); } @@ -443,6 +447,7 @@ public function testThrowExceptionIfFormatIsInvalid() $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'format' => [], + 'widget' => 'choice', ]); } @@ -451,6 +456,7 @@ public function testThrowExceptionIfYearsIsInvalid() $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'years' => 'bad value', + 'widget' => 'choice', ]); } @@ -459,6 +465,7 @@ public function testThrowExceptionIfMonthsIsInvalid() $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'months' => 'bad value', + 'widget' => 'choice', ]); } @@ -467,6 +474,7 @@ public function testThrowExceptionIfDaysIsInvalid() $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'days' => 'bad value', + 'widget' => 'choice', ]); } @@ -523,6 +531,7 @@ public function testYearsOption() { $form = $this->factory->create(static::TESTED_TYPE, null, [ 'years' => [2010, 2011], + 'widget' => 'choice', ]); $view = $form->createView(); @@ -539,6 +548,7 @@ public function testMonthsOption() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'months' => [6, 7], 'format' => \IntlDateFormatter::SHORT, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -559,6 +569,7 @@ public function testMonthsOptionShortFormat() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'months' => [1, 4], 'format' => 'dd.MMM.yy', + 'widget' => 'choice', ]); $view = $form->createView(); @@ -579,6 +590,7 @@ public function testMonthsOptionLongFormat() $view = $this->factory->create(static::TESTED_TYPE, null, [ 'months' => [1, 4], 'format' => 'dd.MMMM.yy', + 'widget' => 'choice', ]) ->createView(); @@ -598,6 +610,7 @@ public function testMonthsOptionLongFormatWithDifferentTimezone() $view = $this->factory->create(static::TESTED_TYPE, null, [ 'months' => [1, 4], 'format' => 'dd.MMMM.yy', + 'widget' => 'choice', ]) ->createView(); @@ -612,6 +625,7 @@ public function testIsDayWithinRangeReturnsTrueIfWithin() \Locale::setDefault('en'); $view = $this->factory->create(static::TESTED_TYPE, null, [ 'days' => [6, 7], + 'widget' => 'choice', ]) ->createView(); @@ -679,7 +693,7 @@ public function testPassDatePatternToView() \Locale::setDefault('de_AT'); - $view = $this->factory->create(static::TESTED_TYPE) + $view = $this->factory->create(static::TESTED_TYPE, null, ['widget' => 'choice']) ->createView(); $this->assertSame('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']); @@ -694,6 +708,7 @@ public function testPassDatePatternToViewDifferentFormat() $view = $this->factory->create(static::TESTED_TYPE, null, [ 'format' => \IntlDateFormatter::LONG, + 'widget' => 'choice', ]) ->createView(); @@ -704,6 +719,7 @@ public function testPassDatePatternToViewDifferentPattern() { $view = $this->factory->create(static::TESTED_TYPE, null, [ 'format' => 'MMyyyydd', + 'widget' => 'choice', ]) ->createView(); @@ -714,6 +730,7 @@ public function testPassDatePatternToViewDifferentPatternWithSeparators() { $view = $this->factory->create(static::TESTED_TYPE, null, [ 'format' => 'MM*yyyy*dd', + 'widget' => 'choice', ]) ->createView(); @@ -740,6 +757,7 @@ public function testDatePatternFormatWithQuotedStrings() $view = $this->factory->create(static::TESTED_TYPE, null, [ // EEEE, d 'de' MMMM 'de' y 'format' => \IntlDateFormatter::FULL, + 'widget' => 'choice', ]) ->createView(); @@ -760,7 +778,7 @@ public function testInitializeWithDateTime() { // Throws an exception if "data_class" option is not explicitly set // to null in the type - $this->assertInstanceOf(FormInterface::class, $this->factory->create(static::TESTED_TYPE, new \DateTime())); + $this->assertInstanceOf(FormInterface::class, $this->factory->create(static::TESTED_TYPE, new \DateTime(), ['widget' => 'choice'])); } public function testSingleTextWidgetShouldUseTheRightInputType() @@ -777,6 +795,7 @@ public function testPassDefaultPlaceholderToViewIfNotRequired() { $view = $this->factory->create(static::TESTED_TYPE, null, [ 'required' => false, + 'widget' => 'choice', ]) ->createView(); @@ -789,6 +808,7 @@ public function testPassNoPlaceholderToViewIfRequired() { $view = $this->factory->create(static::TESTED_TYPE, null, [ 'required' => true, + 'widget' => 'choice', ]) ->createView(); @@ -800,6 +820,7 @@ public function testPassNoPlaceholderToViewIfRequired() public function testPassPlaceholderAsString() { $view = $this->factory->create(static::TESTED_TYPE, null, [ + 'widget' => 'choice', 'placeholder' => 'Empty', ]) ->createView(); @@ -812,6 +833,7 @@ public function testPassPlaceholderAsString() public function testPassPlaceholderAsArray() { $view = $this->factory->create(static::TESTED_TYPE, null, [ + 'widget' => 'choice', 'placeholder' => [ 'year' => 'Empty year', 'month' => 'Empty month', @@ -828,6 +850,7 @@ public function testPassPlaceholderAsArray() public function testPassPlaceholderAsPartialArrayAddEmptyIfNotRequired() { $view = $this->factory->create(static::TESTED_TYPE, null, [ + 'widget' => 'choice', 'required' => false, 'placeholder' => [ 'year' => 'Empty year', @@ -844,6 +867,7 @@ public function testPassPlaceholderAsPartialArrayAddEmptyIfNotRequired() public function testPassPlaceholderAsPartialArrayAddNullIfRequired() { $view = $this->factory->create(static::TESTED_TYPE, null, [ + 'widget' => 'choice', 'required' => true, 'placeholder' => [ 'year' => 'Empty year', @@ -956,6 +980,7 @@ public function testDayErrorsBubbleUp($widget) public function testYears() { $view = $this->factory->create(static::TESTED_TYPE, null, [ + 'widget' => 'choice', 'years' => [1900, 2000, 2040], ]) ->createView(); @@ -970,7 +995,7 @@ public function testYears() public function testPassDefaultChoiceTranslationDomain() { - $form = $this->factory->create(static::TESTED_TYPE); + $form = $this->factory->create(static::TESTED_TYPE, null, ['widget' => 'choice']); $view = $form->createView(); $this->assertFalse($view['year']->vars['choice_translation_domain']); @@ -981,6 +1006,7 @@ public function testPassDefaultChoiceTranslationDomain() public function testPassChoiceTranslationDomainAsString() { $form = $this->factory->create(static::TESTED_TYPE, null, [ + 'widget' => 'choice', 'choice_translation_domain' => 'messages', ]); @@ -993,6 +1019,7 @@ public function testPassChoiceTranslationDomainAsString() public function testPassChoiceTranslationDomainAsArray() { $form = $this->factory->create(static::TESTED_TYPE, null, [ + 'widget' => 'choice', 'choice_translation_domain' => [ 'year' => 'foo', 'day' => 'test', @@ -1025,6 +1052,7 @@ public function testSubmitNullWithSingleText() public function testSubmitNullUsesDefaultEmptyData($emptyData = [], $expectedData = null) { $form = $this->factory->create(static::TESTED_TYPE, null, [ + 'widget' => 'choice', 'empty_data' => $emptyData, ]); $form->submit(null); @@ -1083,4 +1111,9 @@ public function testSubmitStringWithCustomInputFormat() $this->assertSame('14/01/2018', $form->getData()); } + + protected function getTestOptions(): array + { + return ['widget' => 'choice']; + } } diff --git a/Tests/Extension/Core/Type/TimeTypeTest.php b/Tests/Extension/Core/Type/TimeTypeTest.php index cfc3e979a0..4ed930bbd5 100644 --- a/Tests/Extension/Core/Type/TimeTypeTest.php +++ b/Tests/Extension/Core/Type/TimeTypeTest.php @@ -28,6 +28,7 @@ public function testSubmitDateTime() 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'input' => 'datetime', + 'widget' => 'choice', ]); $input = [ @@ -49,6 +50,7 @@ public function testSubmitDateTimeImmutable() 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'input' => 'datetime_immutable', + 'widget' => 'choice', ]); $input = [ @@ -71,6 +73,7 @@ public function testSubmitString() 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'input' => 'string', + 'widget' => 'choice', ]); $input = [ @@ -106,6 +109,7 @@ public function testSubmitTimestamp() 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'input' => 'timestamp', + 'widget' => 'choice', ]); $input = [ @@ -127,6 +131,7 @@ public function testSubmitArray() 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'input' => 'array', + 'widget' => 'choice', ]); $input = [ @@ -288,6 +293,7 @@ public function testPreSetDataDifferentTimezones() 'input' => 'datetime', 'with_seconds' => true, 'reference_date' => new \DateTimeImmutable('2019-01-01', new \DateTimeZone('UTC')), + 'widget' => 'choice', ]); $form->setData(new \DateTime('2022-01-01 15:09:10', new \DateTimeZone('UTC'))); @@ -307,6 +313,7 @@ public function testPreSetDataDifferentTimezonesDuringDaylightSavingTime() 'input' => 'datetime', 'with_seconds' => true, 'reference_date' => new \DateTimeImmutable('2019-07-12', new \DateTimeZone('UTC')), + 'widget' => 'choice', ]); $form->setData(new \DateTime('2022-04-29 15:09:10', new \DateTimeZone('UTC'))); @@ -358,6 +365,7 @@ public function testSubmitDifferentTimezones() 'input' => 'datetime', 'with_seconds' => true, 'reference_date' => new \DateTimeImmutable('2019-01-01', new \DateTimeZone('UTC')), + 'widget' => 'choice', ]); $form->submit([ 'hour' => '16', @@ -376,6 +384,7 @@ public function testSubmitDifferentTimezonesDuringDaylightSavingTime() 'input' => 'datetime', 'with_seconds' => true, 'reference_date' => new \DateTimeImmutable('2019-07-12', new \DateTimeZone('UTC')), + 'widget' => 'choice', ]); $form->submit([ 'hour' => '16', @@ -456,6 +465,7 @@ public function testSetDataWithoutMinutes() 'view_timezone' => 'UTC', 'input' => 'datetime', 'with_minutes' => false, + 'widget' => 'choice', ]); $form->setData(new \DateTime('03:04:05 UTC')); @@ -470,6 +480,7 @@ public function testSetDataWithSeconds() 'view_timezone' => 'UTC', 'input' => 'datetime', 'with_seconds' => true, + 'widget' => 'choice', ]); $form->setData(new \DateTime('03:04:05 UTC')); @@ -485,6 +496,7 @@ public function testSetDataDifferentTimezones() 'input' => 'string', 'with_seconds' => true, 'reference_date' => new \DateTimeImmutable('2013-01-01 00:00:00', new \DateTimeZone('America/New_York')), + 'widget' => 'choice', ]); $dateTime = new \DateTime('2013-01-01 12:04:05'); @@ -512,6 +524,7 @@ public function testSetDataDifferentTimezonesDateTime() 'input' => 'datetime', 'with_seconds' => true, 'reference_date' => new \DateTimeImmutable('now', new \DateTimeZone('America/New_York')), + 'widget' => 'choice', ]); $dateTime = new \DateTime('12:04:05'); @@ -540,6 +553,7 @@ public function testSetDataDifferentTimezonesDuringDaylightSavingTime() 'input' => 'datetime', 'with_seconds' => true, 'reference_date' => new \DateTimeImmutable('2019-07-12', new \DateTimeZone('UTC')), + 'widget' => 'choice', ]); $form->setData(new \DateTime('2019-07-24 14:09:10', new \DateTimeZone('UTC'))); @@ -557,6 +571,7 @@ public function testSetDataDifferentTimezonesWithoutReferenceDate() 'view_timezone' => 'Europe/Berlin', 'input' => 'datetime', 'with_seconds' => true, + 'widget' => 'choice', ]); $form->setData(new \DateTime('2019-07-24 14:09:10', new \DateTimeZone('UTC'))); @@ -568,6 +583,7 @@ public function testHoursOption() { $form = $this->factory->create(static::TESTED_TYPE, null, [ 'hours' => [6, 7], + 'widget' => 'choice', ]); $view = $form->createView(); @@ -582,6 +598,7 @@ public function testIsMinuteWithinRangeReturnsTrueIfWithin() { $form = $this->factory->create(static::TESTED_TYPE, null, [ 'minutes' => [6, 7], + 'widget' => 'choice', ]); $view = $form->createView(); @@ -597,6 +614,7 @@ public function testIsSecondWithinRangeReturnsTrueIfWithin() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'seconds' => [6, 7], 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -733,7 +751,7 @@ public function testInitializeWithDateTime() { // Throws an exception if "data_class" option is not explicitly set // to null in the type - $this->assertInstanceOf(FormInterface::class, $this->factory->create(static::TESTED_TYPE, new \DateTime())); + $this->assertInstanceOf(FormInterface::class, $this->factory->create(static::TESTED_TYPE, new \DateTime(), ['widget' => 'choice'])); } public function testSingleTextWidgetShouldUseTheRightInputType() @@ -789,6 +807,7 @@ public function testPassDefaultPlaceholderToViewIfNotRequired() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'required' => false, 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -802,6 +821,7 @@ public function testPassNoPlaceholderToViewIfRequired() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'required' => true, 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -815,6 +835,7 @@ public function testPassPlaceholderAsString() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'placeholder' => 'Empty', 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -832,6 +853,7 @@ public function testPassPlaceholderAsArray() 'second' => 'Empty second', ], 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -849,6 +871,7 @@ public function testPassPlaceholderAsPartialArrayAddEmptyIfNotRequired() 'second' => 'Empty second', ], 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -866,6 +889,7 @@ public function testPassPlaceholderAsPartialArrayAddNullIfRequired() 'second' => 'Empty second', ], 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -934,6 +958,7 @@ public function testInitializeWithSecondsAndWithoutMinutes() $this->factory->create(static::TESTED_TYPE, null, [ 'with_minutes' => false, 'with_seconds' => true, + 'widget' => 'choice', ]); } @@ -942,6 +967,7 @@ public function testThrowExceptionIfHoursIsInvalid() $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'hours' => 'bad value', + 'widget' => 'choice', ]); } @@ -950,6 +976,7 @@ public function testThrowExceptionIfMinutesIsInvalid() $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'minutes' => 'bad value', + 'widget' => 'choice', ]); } @@ -958,6 +985,7 @@ public function testThrowExceptionIfSecondsIsInvalid() $this->expectException(InvalidOptionsException::class); $this->factory->create(static::TESTED_TYPE, null, [ 'seconds' => 'bad value', + 'widget' => 'choice', ]); } @@ -968,6 +996,7 @@ public function testReferenceDateTimezoneMustMatchModelTimezone() 'model_timezone' => 'UTC', 'view_timezone' => 'Europe/Berlin', 'reference_date' => new \DateTimeImmutable('now', new \DateTimeZone('Europe/Berlin')), + 'widget' => 'choice', ]); } @@ -976,6 +1005,7 @@ public function testModelTimezoneDefaultToReferenceDateTimezoneIfProvided() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'view_timezone' => 'Europe/Berlin', 'reference_date' => new \DateTimeImmutable('now', new \DateTimeZone('Europe/Berlin')), + 'widget' => 'choice', ]); $this->assertSame('Europe/Berlin', $form->getConfig()->getOption('model_timezone')); @@ -985,6 +1015,7 @@ public function testViewTimezoneDefaultsToModelTimezoneIfProvided() { $form = $this->factory->create(static::TESTED_TYPE, null, [ 'model_timezone' => 'Europe/Berlin', + 'widget' => 'choice', ]); $this->assertSame('Europe/Berlin', $form->getConfig()->getOption('view_timezone')); @@ -992,7 +1023,7 @@ public function testViewTimezoneDefaultsToModelTimezoneIfProvided() public function testPassDefaultChoiceTranslationDomain() { - $form = $this->factory->create(static::TESTED_TYPE); + $form = $this->factory->create(static::TESTED_TYPE, null, ['widget' => 'choice']); $view = $form->createView(); $this->assertFalse($view['hour']->vars['choice_translation_domain']); @@ -1004,6 +1035,7 @@ public function testPassChoiceTranslationDomainAsString() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'choice_translation_domain' => 'messages', 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -1020,6 +1052,7 @@ public function testPassChoiceTranslationDomainAsArray() 'second' => 'test', ], 'with_seconds' => true, + 'widget' => 'choice', ]); $view = $form->createView(); @@ -1039,6 +1072,7 @@ public function testSubmitNullUsesDefaultEmptyData($emptyData = [], $expectedDat { $form = $this->factory->create(static::TESTED_TYPE, null, [ 'empty_data' => $emptyData, + 'widget' => 'choice', ]); $form->submit(null); @@ -1055,6 +1089,7 @@ public function testArrayTimeWithReferenceDoesNotUseReferenceTimeOnZero() 'view_timezone' => 'Europe/Berlin', 'reference_date' => new \DateTimeImmutable('01-01-2021 12:34:56', new \DateTimeZone('UTC')), 'input' => 'array', + 'widget' => 'choice', ]); $input = [ @@ -1082,6 +1117,7 @@ public function testArrayTimeWithReferenceDoesUseReferenceDateOnModelTransform() 'view_timezone' => 'Europe/Berlin', 'reference_date' => new \DateTimeImmutable('01-05-2021 12:34:56', new \DateTimeZone('UTC')), 'input' => 'array', + 'widget' => 'choice', ]); $this->assertSame($input, $form->getData()); @@ -1124,4 +1160,9 @@ public static function provideEmptyData() 'Compound choice field lazy' => ['choice', $lazyEmptyData, $expectedData], ]; } + + protected function getTestOptions(): array + { + return ['widget' => 'choice']; + } } diff --git a/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php index 7ef39bde14..9fb1e24219 100644 --- a/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/BirthdayTypeValidatorExtensionTest.php @@ -20,7 +20,7 @@ class BirthdayTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase protected function createForm(array $options = []) { - return $this->factory->create(BirthdayType::class, null, $options); + return $this->factory->create(BirthdayType::class, null, $options + ['widget' => 'choice']); } public function testInvalidMessage() diff --git a/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php index a8206e40c3..df601ab870 100644 --- a/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/DateTimeTypeValidatorExtensionTest.php @@ -20,7 +20,7 @@ class DateTimeTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase protected function createForm(array $options = []) { - return $this->factory->create(DateTimeType::class, null, $options); + return $this->factory->create(DateTimeType::class, null, $options + ['widget' => 'choice']); } public function testInvalidMessage() diff --git a/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php index 32594430dc..163fe91fd0 100644 --- a/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/DateTypeValidatorExtensionTest.php @@ -20,7 +20,7 @@ class DateTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase protected function createForm(array $options = []) { - return $this->factory->create(DateType::class, null, $options); + return $this->factory->create(DateType::class, null, $options + ['widget' => 'choice']); } public function testInvalidMessage() diff --git a/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php index 09893b98a1..ab85366e17 100644 --- a/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/TimeTypeValidatorExtensionTest.php @@ -20,7 +20,7 @@ class TimeTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase protected function createForm(array $options = []) { - return $this->factory->create(TimeType::class, null, $options); + return $this->factory->create(TimeType::class, null, $options + ['widget' => 'choice']); } public function testInvalidMessage() From 5252dea200ebcb7e45ea0b905d58f90ac4785b58 Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Fri, 11 Mar 2022 23:40:38 +0100 Subject: [PATCH 102/208] [Serializer] Add types to private and internal properties --- ChoiceList/View/ChoiceGroupView.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ChoiceList/View/ChoiceGroupView.php b/ChoiceList/View/ChoiceGroupView.php index 453601a6f7..64fe3baec3 100644 --- a/ChoiceList/View/ChoiceGroupView.php +++ b/ChoiceList/View/ChoiceGroupView.php @@ -26,7 +26,7 @@ class ChoiceGroupView implements \IteratorAggregate /** * Creates a new choice group view. * - * @param array $choices the choice views in the group + * @param array $choices the choice views in the group */ public function __construct(string $label, array $choices = []) { From 6e876a75b08c19a3132f8c645d49edb222775fa2 Mon Sep 17 00:00:00 2001 From: Artyum Petrov <17199757+artyuum@users.noreply.github.com> Date: Thu, 20 Apr 2023 19:24:19 +0400 Subject: [PATCH 103/208] Add "composer require..." in all exception messages when needed --- composer.json | 6 ------ 1 file changed, 6 deletions(-) diff --git a/composer.json b/composer.json index df506d699b..1401929459 100644 --- a/composer.json +++ b/composer.json @@ -55,12 +55,6 @@ "symfony/translation-contracts": "<2.5", "symfony/twig-bridge": "<6.3" }, - "suggest": { - "symfony/validator": "For form validation.", - "symfony/security-core": "For hashing users passwords.", - "symfony/security-csrf": "For protecting forms against CSRF attacks.", - "symfony/twig-bridge": "For templating with Twig." - }, "autoload": { "psr-4": { "Symfony\\Component\\Form\\": "" }, "exclude-from-classmap": [ From b0ee14e81b5dd404938a23ecddfe2f0003e787da Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Sat, 18 Feb 2023 13:05:04 +0100 Subject: [PATCH 104/208] Add CI check ensuring interfaces have return types --- .../Validator/ViolationMapper/ViolationMapperInterface.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Extension/Validator/ViolationMapper/ViolationMapperInterface.php b/Extension/Validator/ViolationMapper/ViolationMapperInterface.php index 57ed1c84ce..a72d41df9e 100644 --- a/Extension/Validator/ViolationMapper/ViolationMapperInterface.php +++ b/Extension/Validator/ViolationMapper/ViolationMapperInterface.php @@ -24,6 +24,8 @@ interface ViolationMapperInterface * the given form. * * @param bool $allowNonSynchronized Whether to allow mapping to non-synchronized forms + * + * @return void */ public function mapViolation(ConstraintViolation $violation, FormInterface $form, bool $allowNonSynchronized = false); } From 8428ce62223eb87b4228a8574ff98677e7e8ea7f Mon Sep 17 00:00:00 2001 From: Romain Monteil Date: Sun, 23 Apr 2023 12:45:22 +0200 Subject: [PATCH 105/208] [Form] Move classes to Twig bridge --- Tests/AbstractDivLayoutTestCase.php | 930 -------- Tests/AbstractLayoutTestCase.php | 2925 ------------------------- Tests/AbstractTableLayoutTestCase.php | 536 ----- 3 files changed, 4391 deletions(-) delete mode 100644 Tests/AbstractDivLayoutTestCase.php delete mode 100644 Tests/AbstractLayoutTestCase.php delete mode 100644 Tests/AbstractTableLayoutTestCase.php diff --git a/Tests/AbstractDivLayoutTestCase.php b/Tests/AbstractDivLayoutTestCase.php deleted file mode 100644 index 32468895d9..0000000000 --- a/Tests/AbstractDivLayoutTestCase.php +++ /dev/null @@ -1,930 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Form\Tests; - -use Symfony\Component\Form\FormError; -use Symfony\Component\Security\Csrf\CsrfToken; - -abstract class AbstractDivLayoutTestCase extends AbstractLayoutTestCase -{ - public function testRow() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $form->addError(new FormError('[trans]Error![/trans]')); - $view = $form->createView(); - $html = $this->renderRow($view); - - $this->assertMatchesXpath($html, - '/div - [ - ./label[@for="name"] - /following-sibling::ul - [./li[.="[trans]Error![/trans]"]] - [count(./li)=1] - /following-sibling::input[@id="name"] - ] -' - ); - } - - public function testRowOverrideVariables() - { - $view = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType')->createView(); - $html = $this->renderRow($view, [ - 'attr' => ['class' => 'my&class'], - 'label' => 'foo&bar', - 'label_attr' => ['class' => 'my&label&class'], - ]); - - $this->assertMatchesXpath($html, - '/div - [ - ./label[@for="name"][@class="my&label&class required"][.="[trans]foo&bar[/trans]"] - /following-sibling::input[@id="name"][@class="my&class"] - ] -' - ); - } - - public function testRepeatedRow() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType'); - $form->addError(new FormError('[trans]Error![/trans]')); - $view = $form->createView(); - $html = $this->renderRow($view); - - // The errors of the form are not rendered by intention! - // In practice, repeated fields cannot have errors as all errors - // on them are mapped to the first child. - // (see RepeatedTypeValidatorExtension) - - $this->assertMatchesXpath($html, - '/div - [ - ./label[@for="name_first"] - /following-sibling::input[@id="name_first"] - ] -/following-sibling::div - [ - ./label[@for="name_second"] - /following-sibling::input[@id="name_second"] - ] -' - ); - } - - public function testButtonRow() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ButtonType'); - $view = $form->createView(); - $html = $this->renderRow($view); - - $this->assertMatchesXpath($html, - '/div - [ - ./button[@type="button"][@name="name"] - ] - [count(//label)=0] -' - ); - } - - public function testRest() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('field1', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('field2', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType') - ->add('field3', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('field4', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm() - ->createView(); - - // Render field2 row -> does not implicitly call renderWidget because - // it is a repeated field! - $this->renderRow($view['field2']); - - // Render field3 widget - $this->renderWidget($view['field3']); - - // Rest should only contain field1 and field4 - $html = $this->renderRest($view); - - $this->assertMatchesXpath($html, - '/div - [ - ./label[@for="name_field1"] - /following-sibling::input[@type="text"][@id="name_field1"] - ] -/following-sibling::div - [ - ./label[@for="name_field4"] - /following-sibling::input[@type="text"][@id="name_field4"] - ] - [count(../div)=2] - [count(..//label)=2] - [count(..//input)=3] -/following-sibling::input - [@type="hidden"] - [@id="name__token"] -' - ); - } - - public function testRestWithChildrenForms() - { - $child1 = $this->factory->createNamedBuilder('child1', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('field1', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('field2', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - - $child2 = $this->factory->createNamedBuilder('child2', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('field1', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('field2', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - - $view = $this->factory->createNamedBuilder('parent', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add($child1) - ->add($child2) - ->getForm() - ->createView(); - - // Render child1.field1 row - $this->renderRow($view['child1']['field1']); - - // Render child2.field2 widget (remember that widget don't render label) - $this->renderWidget($view['child2']['field2']); - - // Rest should only contain child1.field2 and child2.field1 - $html = $this->renderRest($view); - - $this->assertMatchesXpath($html, - '/div - [ - ./label[not(@for)] - /following-sibling::div[@id="parent_child1"] - [ - ./div - [ - ./label[@for="parent_child1_field2"] - /following-sibling::input[@id="parent_child1_field2"] - ] - ] - ] - -/following-sibling::div - [ - ./label[not(@for)] - /following-sibling::div[@id="parent_child2"] - [ - ./div - [ - ./label[@for="parent_child2_field1"] - /following-sibling::input[@id="parent_child2_field1"] - ] - ] - ] - [count(//label)=4] - [count(//input[@type="text"])=2] -/following-sibling::input[@type="hidden"][@id="parent__token"] -' - ); - } - - public function testRestAndRepeatedWithRow() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('first', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('password', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType') - ->getForm() - ->createView(); - - $this->renderRow($view['password']); - - $html = $this->renderRest($view); - - $this->assertMatchesXpath($html, - '/div - [ - ./label[@for="name_first"] - /following-sibling::input[@type="text"][@id="name_first"] - ] - [count(.//input)=1] -/following-sibling::input - [@type="hidden"] - [@id="name__token"] -' - ); - } - - public function testRestAndRepeatedWithRowPerChild() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('first', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('password', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType') - ->getForm() - ->createView(); - - $this->renderRow($view['password']['first']); - $this->renderRow($view['password']['second']); - - $html = $this->renderRest($view); - - $this->assertMatchesXpath($html, - '/div - [ - ./label[@for="name_first"] - /following-sibling::input[@type="text"][@id="name_first"] - ] - [count(.//input)=1] - [count(.//label)=1] -/following-sibling::input - [@type="hidden"] - [@id="name__token"] -' - ); - } - - public function testRestAndRepeatedWithWidgetPerChild() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('first', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('password', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType') - ->getForm() - ->createView(); - - // The password form is considered as rendered as all its children - // are rendered - $this->renderWidget($view['password']['first']); - $this->renderWidget($view['password']['second']); - - $html = $this->renderRest($view); - - $this->assertMatchesXpath($html, - '/div - [ - ./label[@for="name_first"] - /following-sibling::input[@type="text"][@id="name_first"] - ] - [count(//input)=2] - [count(//label)=1] -/following-sibling::input - [@type="hidden"] - [@id="name__token"] -' - ); - } - - public function testCollection() - { - $form = $this->factory->createNamed('names', 'Symfony\Component\Form\Extension\Core\Type\CollectionType', ['a', 'b'], [ - 'entry_type' => 'Symfony\Component\Form\Extension\Core\Type\TextType', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div[./input[@type="text"][@value="a"]] - /following-sibling::div[./input[@type="text"][@value="b"]] - ] - [count(./div[./input])=2] -' - ); - } - - // https://github.com/symfony/symfony/issues/5038 - public function testCollectionWithAlternatingRowTypes() - { - $data = [ - ['title' => 'a'], - ['title' => 'b'], - ]; - $form = $this->factory->createNamed('names', 'Symfony\Component\Form\Extension\Core\Type\CollectionType', $data, [ - 'entry_type' => 'Symfony\Component\Form\Tests\Fixtures\AlternatingRowType', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div[./div/div/input[@type="text"][@value="a"]] - /following-sibling::div[./div/div/textarea[.="b"]] - ] - [count(./div[./div/div/input])=1] - [count(./div[./div/div/textarea])=1] -' - ); - } - - public function testEmptyCollection() - { - $form = $this->factory->createNamed('names', 'Symfony\Component\Form\Extension\Core\Type\CollectionType', [], [ - 'entry_type' => 'Symfony\Component\Form\Extension\Core\Type\TextType', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [./input[@type="hidden"][@id="names__token"]] - [count(./div)=0] -' - ); - } - - public function testCollectionRow() - { - $collection = $this->factory->createNamedBuilder( - 'collection', - 'Symfony\Component\Form\Extension\Core\Type\CollectionType', - ['a', 'b'], - ['entry_type' => 'Symfony\Component\Form\Extension\Core\Type\TextType'] - ); - - $form = $this->factory->createNamedBuilder('form', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add($collection) - ->getForm(); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div - [ - ./label[not(@for)] - /following-sibling::div - [ - ./div - [ - ./label[@for="form_collection_0"] - /following-sibling::input[@type="text"][@value="a"] - ] - /following-sibling::div - [ - ./label[@for="form_collection_1"] - /following-sibling::input[@type="text"][@value="b"] - ] - ] - ] - /following-sibling::input[@type="hidden"][@id="form__token"] - ] - [count(.//input)=3] -' - ); - } - - public function testForm() - { - $form = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->setMethod('PUT') - ->setAction('http://example.com') - ->add('firstName', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('lastName', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm(); - - // include ampersands everywhere to validate escaping - $html = $this->renderForm($form->createView(), [ - 'id' => 'my&id', - 'attr' => ['class' => 'my&class'], - ]); - - $this->assertMatchesXpath($html, - '/form - [ - ./input[@type="hidden"][@name="_method"][@value="PUT"] - /following-sibling::div - [ - ./div - [ - ./label[@for="name_firstName"] - /following-sibling::input[@type="text"][@id="name_firstName"] - ] - /following-sibling::div - [ - ./label[@for="name_lastName"] - /following-sibling::input[@type="text"][@id="name_lastName"] - ] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(.//input)=3] - [@id="my&id"] - [@class="my&class"] - ] - [@method="post"] - [@action="http://example.com"] - [@class="my&class"] -' - ); - } - - public function testFormWidget() - { - $form = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('firstName', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('lastName', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm(); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div - [ - ./label[@for="name_firstName"] - /following-sibling::input[@type="text"][@id="name_firstName"] - ] - /following-sibling::div - [ - ./label[@for="name_lastName"] - /following-sibling::input[@type="text"][@id="name_lastName"] - ] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(.//input)=3] -' - ); - } - - // https://github.com/symfony/symfony/issues/2308 - public function testNestedFormError() - { - $form = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add($this->factory - ->createNamedBuilder('child', 'Symfony\Component\Form\Extension\Core\Type\FormType', null, ['error_bubbling' => false]) - ->add('grandChild', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ) - ->getForm(); - - $form->get('child')->addError(new FormError('[trans]Error![/trans]')); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div/label - /following-sibling::ul[./li[.="[trans]Error![/trans]"]] - ] - [count(.//li[.="[trans]Error![/trans]"])=1] -' - ); - } - - public function testCsrf() - { - $this->csrfTokenManager->expects($this->any()) - ->method('getToken') - ->willReturn(new CsrfToken('token_id', 'foo&bar')); - - $form = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add($this->factory - // No CSRF protection on nested forms - ->createNamedBuilder('child', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add($this->factory->createNamedBuilder('grandchild', 'Symfony\Component\Form\Extension\Core\Type\TextType')) - ) - ->getForm(); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div - /following-sibling::input[@type="hidden"][@id="name__token"][@value="foo&bar"] - ] - [count(.//input[@type="hidden"])=1] -' - ); - } - - public function testRepeated() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType', 'foobar', [ - 'type' => 'Symfony\Component\Form\Extension\Core\Type\TextType', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div - [ - ./label[@for="name_first"] - /following-sibling::input[@type="text"][@id="name_first"] - ] - /following-sibling::div - [ - ./label[@for="name_second"] - /following-sibling::input[@type="text"][@id="name_second"] - ] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(.//input)=3] -' - ); - } - - public function testRepeatedWithCustomOptions() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType', null, [ - // the global required value cannot be overridden - 'first_options' => ['label' => 'Test', 'required' => false], - 'second_options' => ['label' => 'Test2'], - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div - [ - ./label[@for="name_first"][.="[trans]Test[/trans]"] - /following-sibling::input[@type="text"][@id="name_first"][@required="required"] - ] - /following-sibling::div - [ - ./label[@for="name_second"][.="[trans]Test2[/trans]"] - /following-sibling::input[@type="text"][@id="name_second"][@required="required"] - ] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(.//input)=3] -' - ); - } - - public function testSearchInputName() - { - $form = $this->factory->createNamedBuilder('full', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('name', 'Symfony\Component\Form\Extension\Core\Type\SearchType') - ->getForm(); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div - [ - ./label[@for="full_name"] - /following-sibling::input[@type="search"][@id="full_name"][@name="full[name]"] - ] - /following-sibling::input[@type="hidden"][@id="full__token"] - ] - [count(//input)=2] -' - ); - } - - public function testLabelHasNoId() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $html = $this->renderRow($form->createView()); - - $this->assertMatchesXpath($html, - '/div - [ - ./label[@for="name"][not(@id)] - /following-sibling::input[@id="name"] - ] -' - ); - } - - public function testLabelIsNotRenderedWhenSetToFalse() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'label' => false, - ]); - $html = $this->renderRow($form->createView()); - - $this->assertMatchesXpath($html, - '/div - [ - ./input[@id="name"] - ] - [count(//label)=0] -' - ); - } - - /** - * @dataProvider themeBlockInheritanceProvider - */ - public function testThemeBlockInheritance($theme) - { - $view = $this->factory - ->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\EmailType') - ->createView() - ; - - $this->setTheme($view, $theme); - - $this->assertMatchesXpath( - $this->renderWidget($view), - '/input[@type="email"][@rel="theme"]' - ); - } - - /** - * @dataProvider themeInheritanceProvider - */ - public function testThemeInheritance($parentTheme, $childTheme) - { - $child = $this->factory->createNamedBuilder('child', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('field', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - - $view = $this->factory->createNamedBuilder('parent', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('field', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add($child) - ->getForm() - ->createView() - ; - - $this->setTheme($view, $parentTheme); - $this->setTheme($view['child'], $childTheme); - - $this->assertWidgetMatchesXpath($view, [], - '/div - [ - ./div - [ - ./label[.="parent"] - /following-sibling::input[@type="text"] - ] - /following-sibling::div - [ - ./label[.="child"] - /following-sibling::div - [ - ./div - [ - ./label[.="child"] - /following-sibling::input[@type="text"] - ] - ] - ] - /following-sibling::input[@type="hidden"] - ] -' - ); - } - - /** - * The block "_name_child_label" should be overridden in the theme of the - * implemented driver. - */ - public function testCollectionRowWithCustomBlock() - { - $collection = ['one', 'two', 'three']; - $form = $this->factory->createNamedBuilder('names', 'Symfony\Component\Form\Extension\Core\Type\CollectionType', $collection) - ->getForm(); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div[./label[.="Custom label: [trans]0[/trans]"]] - /following-sibling::div[./label[.="Custom label: [trans]1[/trans]"]] - /following-sibling::div[./label[.="Custom label: [trans]2[/trans]"]] - ] -' - ); - } - - /** - * The block "_name_c_entry_label" should be overridden in the theme of the - * implemented driver. - */ - public function testChoiceRowWithCustomBlock() - { - $form = $this->factory->createNamedBuilder('name_c', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', 'a', [ - 'choices' => ['ChoiceA' => 'a', 'ChoiceB' => 'b'], - 'expanded' => true, - ]) - ->getForm(); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./label[.="Custom name label: [trans]ChoiceA[/trans]"] - /following-sibling::label[.="Custom name label: [trans]ChoiceB[/trans]"] - ] -' - ); - } - - public function testSingleChoiceExpandedWithLabelsAsFalse() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'choice_label' => false, - 'multiple' => false, - 'expanded' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] - /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][@value="&b"][not(@checked)] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=3] - [count(./label)=1] -' - ); - } - - public function testSingleChoiceExpandedWithLabelsSetByCallable() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b', 'Choice&C' => '&c'], - 'choice_label' => function ($choice, $label, $value) { - if ('&b' === $choice) { - return false; - } - - return 'label.'.$value; - }, - 'multiple' => false, - 'expanded' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] - /following-sibling::label[@for="name_0"][.="[trans]label.&a[/trans]"] - /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][@value="&b"][not(@checked)] - /following-sibling::input[@type="radio"][@name="name"][@id="name_2"][@value="&c"][not(@checked)] - /following-sibling::label[@for="name_2"][.="[trans]label.&c[/trans]"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=4] - [count(./label)=3] -' - ); - } - - public function testSingleChoiceExpandedWithLabelsSetFalseByCallable() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'choice_label' => fn () => false, - 'multiple' => false, - 'expanded' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] - /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][@value="&b"][not(@checked)] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=3] - [count(./label)=1] -' - ); - } - - public function testMultipleChoiceExpandedWithLabelsAsFalse() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a'], [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'choice_label' => false, - 'multiple' => true, - 'expanded' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="checkbox"][@name="name[]"][@id="name_0"][@value="&a"][@checked] - /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_1"][@value="&b"][not(@checked)] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=3] - [count(./label)=1] -' - ); - } - - public function testMultipleChoiceExpandedWithLabelsSetByCallable() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a'], [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b', 'Choice&C' => '&c'], - 'choice_label' => function ($choice, $label, $value) { - if ('&b' === $choice) { - return false; - } - - return 'label.'.$value; - }, - 'multiple' => true, - 'expanded' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="checkbox"][@name="name[]"][@id="name_0"][@value="&a"][@checked] - /following-sibling::label[@for="name_0"][.="[trans]label.&a[/trans]"] - /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_1"][@value="&b"][not(@checked)] - /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_2"][@value="&c"][not(@checked)] - /following-sibling::label[@for="name_2"][.="[trans]label.&c[/trans]"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=4] - [count(./label)=3] -' - ); - } - - public function testMultipleChoiceExpandedWithLabelsSetFalseByCallable() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a'], [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'choice_label' => fn () => false, - 'multiple' => true, - 'expanded' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="checkbox"][@name="name[]"][@id="name_0"][@value="&a"][@checked] - /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_1"][@value="&b"][not(@checked)] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=3] - [count(./label)=1] -' - ); - } - - public function testFormEndWithRest() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('field1', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('field2', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm() - ->createView(); - - $this->renderWidget($view['field1']); - - // Rest should only contain field2 - $html = $this->renderEnd($view); - - // Insert the start tag, the end tag should be rendered by the helper - $this->assertMatchesXpath('
'.$html, - '/form - [ - ./div - [ - ./label[@for="name_field2"] - /following-sibling::input[@type="text"][@id="name_field2"] - ] - /following-sibling::input - [@type="hidden"] - [@id="name__token"] - ] -' - ); - } - - public function testFormEndWithoutRest() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('field1', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('field2', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm() - ->createView(); - - $this->renderWidget($view['field1']); - - // Rest should only contain field2, but isn't rendered - $html = $this->renderEnd($view, ['render_rest' => false]); - - $this->assertEquals('
', $html); - } - - public function testWidgetContainerAttributes() - { - $form = $this->factory->createNamed('form', 'Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'attr' => ['class' => 'foobar', 'data-foo' => 'bar'], - ]); - - $form->add('text', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - - $html = $this->renderWidget($form->createView()); - - // compare plain HTML to check the whitespace - $this->assertStringContainsString('
', $html); - } - - public function testWidgetContainerAttributeNameRepeatedIfTrue() - { - $form = $this->factory->createNamed('form', 'Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'attr' => ['foo' => true], - ]); - - $html = $this->renderWidget($form->createView()); - - // foo="foo" - $this->assertStringContainsString('
', $html); - } -} diff --git a/Tests/AbstractLayoutTestCase.php b/Tests/AbstractLayoutTestCase.php deleted file mode 100644 index 33799bfcc1..0000000000 --- a/Tests/AbstractLayoutTestCase.php +++ /dev/null @@ -1,2925 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Form\Tests; - -use PHPUnit\Framework\SkippedTestError; -use Symfony\Component\Form\Extension\Core\Type\PercentType; -use Symfony\Component\Form\Extension\Core\Type\SubmitType; -use Symfony\Component\Form\Extension\Csrf\CsrfExtension; -use Symfony\Component\Form\FormError; -use Symfony\Component\Form\FormView; -use Symfony\Component\Form\Test\FormIntegrationTestCase; -use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; -use Symfony\Component\Translation\TranslatableMessage; -use Symfony\Contracts\Translation\TranslatableInterface; -use Symfony\Contracts\Translation\TranslatorInterface; - -abstract class AbstractLayoutTestCase extends FormIntegrationTestCase -{ - use VersionAwareTest; - - protected $csrfTokenManager; - protected $testableFeatures = []; - private $defaultLocale; - - protected function setUp(): void - { - if (!\extension_loaded('intl')) { - $this->markTestSkipped('Extension intl is required.'); - } - - $this->defaultLocale = \Locale::getDefault(); - \Locale::setDefault('en'); - - $this->csrfTokenManager = $this->createMock(CsrfTokenManagerInterface::class); - - parent::setUp(); - } - - protected function getExtensions() - { - return [ - new CsrfExtension($this->csrfTokenManager), - ]; - } - - protected function tearDown(): void - { - $this->csrfTokenManager = null; - \Locale::setDefault($this->defaultLocale); - - parent::tearDown(); - } - - protected function assertXpathNodeValue(\DOMElement $element, $expression, $nodeValue) - { - $xpath = new \DOMXPath($element->ownerDocument); - $nodeList = $xpath->evaluate($expression); - $this->assertEquals(1, $nodeList->length); - $this->assertEquals($nodeValue, $nodeList->item(0)->nodeValue); - } - - protected function assertMatchesXpath($html, $expression, $count = 1) - { - $dom = new \DOMDocument('UTF-8'); - try { - // Wrap in node so we can load HTML with multiple tags at - // the top level - $dom->loadXML(''.$html.''); - } catch (\Exception $e) { - $this->fail(sprintf( - "Failed loading HTML:\n\n%s\n\nError: %s", - $html, - $e->getMessage() - )); - } - $xpath = new \DOMXPath($dom); - $nodeList = $xpath->evaluate('/root'.$expression); - - if ($nodeList->length != $count) { - $dom->formatOutput = true; - $this->fail(sprintf( - "Failed asserting that \n\n%s\n\nmatches exactly %s. Matches %s in \n\n%s", - $expression, - 1 == $count ? 'once' : $count.' times', - 1 == $nodeList->length ? 'once' : $nodeList->length.' times', - // strip away and - substr($dom->saveHTML(), 6, -8) - )); - } else { - $this->addToAssertionCount(1); - } - } - - protected function assertWidgetMatchesXpath(FormView $view, array $vars, $xpath) - { - // include ampersands everywhere to validate escaping - $html = $this->renderWidget($view, array_merge([ - 'id' => 'my&id', - 'attr' => ['class' => 'my&class'], - ], $vars)); - - if (!isset($vars['id'])) { - $xpath = trim($xpath).' - [@id="my&id"]'; - } - - if (!isset($vars['attr']['class'])) { - $xpath .= ' - [@class="my&class"]'; - } - - $this->assertMatchesXpath($html, $xpath); - } - - abstract protected function renderForm(FormView $view, array $vars = []); - - abstract protected function renderLabel(FormView $view, $label = null, array $vars = []); - - protected function renderHelp(FormView $view) - { - $this->markTestSkipped(sprintf('%s::renderHelp() is not implemented.', static::class)); - } - - abstract protected function renderErrors(FormView $view); - - abstract protected function renderWidget(FormView $view, array $vars = []); - - abstract protected function renderRow(FormView $view, array $vars = []); - - abstract protected function renderRest(FormView $view, array $vars = []); - - abstract protected function renderStart(FormView $view, array $vars = []); - - abstract protected function renderEnd(FormView $view, array $vars = []); - - abstract protected function setTheme(FormView $view, array $themes, $useDefaultThemes = true); - - public function testLabel() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $view = $form->createView(); - $this->renderWidget($view, ['label' => 'foo']); - $html = $this->renderLabel($view); - - $this->assertMatchesXpath($html, - '/label - [@for="name"] - [.="[trans]Name[/trans]"] -' - ); - } - - public function testLabelWithoutTranslation() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'translation_domain' => false, - ]); - - $this->assertMatchesXpath($this->renderLabel($form->createView()), - '/label - [@for="name"] - [.="Name"] -' - ); - } - - public function testLabelOnForm() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType', null, ['widget' => 'choice']); - $view = $form->createView(); - $this->renderWidget($view, ['label' => 'foo']); - $html = $this->renderLabel($view); - - $this->assertMatchesXpath($html, - '/label - [@class="required"] - [.="[trans]Name[/trans]"] -' - ); - } - - public function testLabelWithCustomTextPassedAsOption() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'label' => 'Custom label', - ]); - $html = $this->renderLabel($form->createView()); - - $this->assertMatchesXpath($html, - '/label - [@for="name"] - [.="[trans]Custom label[/trans]"] -' - ); - } - - public function testLabelWithCustomTextPassedDirectly() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $html = $this->renderLabel($form->createView(), 'Custom label'); - - $this->assertMatchesXpath($html, - '/label - [@for="name"] - [.="[trans]Custom label[/trans]"] -' - ); - } - - public function testLabelWithCustomTextPassedAsOptionAndDirectly() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'label' => 'Custom label', - ]); - $html = $this->renderLabel($form->createView(), 'Overridden label'); - - $this->assertMatchesXpath($html, - '/label - [@for="name"] - [.="[trans]Overridden label[/trans]"] -' - ); - } - - public function testLabelDoesNotRenderFieldAttributes() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $html = $this->renderLabel($form->createView(), null, [ - 'attr' => [ - 'class' => 'my&class', - ], - ]); - - $this->assertMatchesXpath($html, - '/label - [@for="name"] - [@class="required"] -' - ); - } - - public function testLabelWithCustomAttributesPassedDirectly() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $html = $this->renderLabel($form->createView(), null, [ - 'label_attr' => [ - 'class' => 'my&class', - ], - ]); - - $this->assertMatchesXpath($html, - '/label - [@for="name"] - [@class="my&class required"] -' - ); - } - - public function testLabelWithCustomTextAndCustomAttributesPassedDirectly() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $html = $this->renderLabel($form->createView(), 'Custom label', [ - 'label_attr' => [ - 'class' => 'my&class', - ], - ]); - - $this->assertMatchesXpath($html, - '/label - [@for="name"] - [@class="my&class required"] - [.="[trans]Custom label[/trans]"] -' - ); - } - - // https://github.com/symfony/symfony/issues/5029 - public function testLabelWithCustomTextAsOptionAndCustomAttributesPassedDirectly() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'label' => 'Custom label', - ]); - $html = $this->renderLabel($form->createView(), null, [ - 'label_attr' => [ - 'class' => 'my&class', - ], - ]); - - $this->assertMatchesXpath($html, - '/label - [@for="name"] - [@class="my&class required"] - [.="[trans]Custom label[/trans]"] -' - ); - } - - public function testLabelFormatName() - { - $form = $this->factory->createNamedBuilder('myform') - ->add('myfield', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm(); - $view = $form->get('myfield')->createView(); - $html = $this->renderLabel($view, null, ['label_format' => 'form.%name%']); - - $this->assertMatchesXpath($html, - '/label - [@for="myform_myfield"] - [.="[trans]form.myfield[/trans]"] -' - ); - } - - public function testLabelFormatId() - { - $form = $this->factory->createNamedBuilder('myform') - ->add('myfield', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm(); - $view = $form->get('myfield')->createView(); - $html = $this->renderLabel($view, null, ['label_format' => 'form.%id%']); - - $this->assertMatchesXpath($html, - '/label - [@for="myform_myfield"] - [.="[trans]form.myform_myfield[/trans]"] -' - ); - } - - public function testLabelFormatAsFormOption() - { - $options = ['label_format' => 'form.%name%']; - - $form = $this->factory->createNamedBuilder('myform', 'Symfony\Component\Form\Extension\Core\Type\FormType', null, $options) - ->add('myfield', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm(); - $view = $form->get('myfield')->createView(); - $html = $this->renderLabel($view); - - $this->assertMatchesXpath($html, - '/label - [@for="myform_myfield"] - [.="[trans]form.myfield[/trans]"] -' - ); - } - - public function testLabelFormatOverriddenOption() - { - $options = ['label_format' => 'form.%name%']; - - $form = $this->factory->createNamedBuilder('myform', 'Symfony\Component\Form\Extension\Core\Type\FormType', null, $options) - ->add('myfield', 'Symfony\Component\Form\Extension\Core\Type\TextType', ['label_format' => 'field.%name%']) - ->getForm(); - $view = $form->get('myfield')->createView(); - $html = $this->renderLabel($view); - - $this->assertMatchesXpath($html, - '/label - [@for="myform_myfield"] - [.="[trans]field.myfield[/trans]"] -' - ); - } - - public function testLabelWithoutTranslationOnButton() - { - $form = $this->factory->createNamedBuilder('myform', 'Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'translation_domain' => false, - ]) - ->add('mybutton', 'Symfony\Component\Form\Extension\Core\Type\ButtonType') - ->getForm(); - $view = $form->get('mybutton')->createView(); - $html = $this->renderWidget($view); - - $this->assertMatchesXpath($html, - '/button - [@type="button"] - [@name="myform[mybutton]"] - [.="Mybutton"] -' - ); - } - - public function testLabelFormatOnButton() - { - $form = $this->factory->createNamedBuilder('myform') - ->add('mybutton', 'Symfony\Component\Form\Extension\Core\Type\ButtonType') - ->getForm(); - $view = $form->get('mybutton')->createView(); - $html = $this->renderWidget($view, ['label_format' => 'form.%name%']); - - $this->assertMatchesXpath($html, - '/button - [@type="button"] - [@name="myform[mybutton]"] - [.="[trans]form.mybutton[/trans]"] -' - ); - } - - public function testLabelFormatOnButtonId() - { - $form = $this->factory->createNamedBuilder('myform') - ->add('mybutton', 'Symfony\Component\Form\Extension\Core\Type\ButtonType') - ->getForm(); - $view = $form->get('mybutton')->createView(); - $html = $this->renderWidget($view, ['label_format' => 'form.%id%']); - - $this->assertMatchesXpath($html, - '/button - [@type="button"] - [@name="myform[mybutton]"] - [.="[trans]form.myform_mybutton[/trans]"] -' - ); - } - - public function testHelp() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'help' => 'Help text test!', - ]); - $view = $form->createView(); - $html = $this->renderHelp($view); - - $this->assertMatchesXpath($html, - '/*[self::div or self::p] - [@id="name_help"] - [@class="help-text"] - [.="[trans]Help text test![/trans]"] -' - ); - } - - public function testHelpNotSet() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $view = $form->createView(); - $html = $this->renderHelp($view); - - $this->assertMatchesXpath($html, '/p', 0); - } - - public function testHelpSetLinkFromWidget() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'help' => 'Help text test!', - ]); - $view = $form->createView(); - $html = $this->renderRow($view); - - // Test if renderHelp method is implemented (throw SkippedTestError if not) - $this->renderHelp($view); - - $this->assertMatchesXpath($html, - '//input - [@aria-describedby="name_help"] -' - ); - } - - public function testHelpNotSetNotLinkedFromWidget() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $view = $form->createView(); - $html = $this->renderRow($view); - - // Test if renderHelp method is implemented (throw SkippedTestError if not) - $this->renderHelp($view); - - $this->assertMatchesXpath($html, - '//input - [not(@aria-describedby)] -' - ); - } - - public function testErrors() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $form->addError(new FormError('[trans]Error 1[/trans]')); - $form->addError(new FormError('[trans]Error 2[/trans]')); - $view = $form->createView(); - $html = $this->renderErrors($view); - - $this->assertMatchesXpath($html, - '/ul - [ - ./li[.="[trans]Error 1[/trans]"] - /following-sibling::li[.="[trans]Error 2[/trans]"] - ] - [count(./li)=2] -' - ); - } - - public function testOverrideWidgetBlock() - { - // see custom_widgets.html.twig - $form = $this->factory->createNamed('text_id', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $html = $this->renderWidget($form->createView()); - - $this->assertMatchesXpath($html, - '/div - [ - ./input - [@type="text"] - [@id="text_id"] - ] - [@id="container"] -' - ); - } - - public function testCheckedCheckbox() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', true); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="checkbox"] - [@name="name"] - [@checked="checked"] - [@value="1"] -' - ); - } - - public function testUncheckedCheckbox() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', false); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="checkbox"] - [@name="name"] - [not(@checked)] -' - ); - } - - public function testCheckboxWithValue() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType', false, [ - 'value' => 'foo&bar', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="checkbox"] - [@name="name"] - [@value="foo&bar"] -' - ); - } - - public function testSingleChoice() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'multiple' => false, - 'expanded' => false, - ]); - - // If the field is collapsed, has no "multiple" attribute, is required but - // has *no* empty value, the "required" must not be added, otherwise - // the resulting HTML is invalid. - // https://github.com/symfony/symfony/issues/8942 - - // HTML 5 spec - // http://www.w3.org/html/wg/drafts/html/master/forms.html#placeholder-label-option - - // "If a select element has a required attribute specified, does not - // have a multiple attribute specified, and has a display size of 1, - // then the select element must have a placeholder label option." - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [not(@required)] - [ - ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=2] -' - ); - } - - public function testSelectWithSizeBiggerThanOneCanBeRequired() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, [ - 'choices' => ['a', 'b'], - 'multiple' => false, - 'expanded' => false, - 'attr' => ['size' => 2], - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [@required="required"] - [@size="2"] - [count(./option)=2] -' - ); - } - - public function testSingleChoiceWithoutTranslation() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'multiple' => false, - 'expanded' => false, - 'choice_translation_domain' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [not(@required)] - [ - ./option[@value="&a"][@selected="selected"][.="Choice&A"] - /following-sibling::option[@value="&b"][not(@selected)][.="Choice&B"] - ] - [count(./option)=2] -' - ); - } - - public function testSingleChoiceWithPlaceholderWithoutTranslation() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'multiple' => false, - 'expanded' => false, - 'required' => false, - 'translation_domain' => false, - 'placeholder' => 'Placeholder&Not&Translated', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [not(@required)] - [ - ./option[@value=""][not(@selected)][not(@disabled)][.="Placeholder&Not&Translated"] - /following-sibling::option[@value="&a"][@selected="selected"][.="Choice&A"] - /following-sibling::option[@value="&b"][not(@selected)][.="Choice&B"] - ] - [count(./option)=3] -' - ); - } - - public function testSingleChoiceAttributes() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'choice_attr' => ['Choice&B' => ['class' => 'foo&bar']], - 'multiple' => false, - 'expanded' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [not(@required)] - [ - ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][@class="foo&bar"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=2] -' - ); - } - - public function testSingleChoiceAttributesWithMainAttributes() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'multiple' => false, - 'expanded' => false, - 'attr' => ['class' => 'bar&baz'], - ]); - - $this->assertWidgetMatchesXpath($form->createView(), ['attr' => ['class' => 'bar&baz']], - '/select - [@name="name"] - [@class="bar&baz"] - [not(@required)] - [ - ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"][not(@id)][not(@name)] - /following-sibling::option[@value="&b"][not(@class)][not(@selected)][.="[trans]Choice&B[/trans]"][not(@id)][not(@name)] - ] - [count(./option)=2] -' - ); - } - - public function testSingleExpandedChoiceAttributesWithMainAttributes() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'multiple' => false, - 'expanded' => true, - 'attr' => ['class' => 'bar&baz'], - ]); - - $this->assertWidgetMatchesXpath($form->createView(), ['attr' => ['class' => 'bar&baz']], - '/div - [@class="bar&baz"] - [ - ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] - /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] - /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][@value="&b"][not(@checked)] - /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=3] -' - ); - } - - public function testSingleChoiceWithPreferred() - { - $this->requiresFeatureSet(404); - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'preferred_choices' => ['&b'], - 'multiple' => false, - 'expanded' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), ['separator' => '-- sep --'], - '/select - [@name="name"] - [not(@required)] - [ - ./option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - /following-sibling::option[@disabled="disabled"][not(@selected)][.="-- sep --"] - /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=4] -' - ); - } - - public function testSingleChoiceWithPreferredAndNoSeparator() - { - $this->requiresFeatureSet(404); - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'preferred_choices' => ['&b'], - 'multiple' => false, - 'expanded' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), ['separator' => null], - '/select - [@name="name"] - [not(@required)] - [ - ./option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=3] -' - ); - } - - public function testSingleChoiceWithPreferredAndBlankSeparator() - { - $this->requiresFeatureSet(404); - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'preferred_choices' => ['&b'], - 'multiple' => false, - 'expanded' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), ['separator' => ''], - '/select - [@name="name"] - [not(@required)] - [ - ./option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - /following-sibling::option[@disabled="disabled"][not(@selected)][.=""] - /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=4] -' - ); - } - - public function testChoiceWithOnlyPreferred() - { - $this->requiresFeatureSet(404); - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'preferred_choices' => ['&a', '&b'], - 'multiple' => false, - 'expanded' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [count(./option)=5] -' - ); - } - - public function testSingleChoiceNonRequired() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'required' => false, - 'multiple' => false, - 'expanded' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [not(@required)] - [ - ./option[@value=""][.=""] - /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=3] -' - ); - } - - public function testSingleChoiceNonRequiredNoneSelected() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'required' => false, - 'multiple' => false, - 'expanded' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [not(@required)] - [ - ./option[@value=""][.=""] - /following-sibling::option[@value="&a"][not(@selected)][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=3] -' - ); - } - - public function testSingleChoiceNonRequiredWithPlaceholder() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'multiple' => false, - 'expanded' => false, - 'required' => false, - 'placeholder' => 'Select&Anything&Not&Me', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [not(@required)] - [ - ./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Select&Anything&Not&Me[/trans]"] - /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=3] -' - ); - } - - public function testSingleChoiceRequiredWithPlaceholder() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'required' => true, - 'multiple' => false, - 'expanded' => false, - 'placeholder' => 'Test&Me', - ]); - - // The "disabled" attribute was removed again due to a bug in the - // BlackBerry 10 browser. - // See https://github.com/symfony/symfony/pull/7678 - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [@required="required"] - [ - ./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Test&Me[/trans]"] - /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=3] -' - ); - } - - public function testSingleChoiceRequiredWithPlaceholderViaView() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'required' => true, - 'multiple' => false, - 'expanded' => false, - ]); - - // The "disabled" attribute was removed again due to a bug in the - // BlackBerry 10 browser. - // See https://github.com/symfony/symfony/pull/7678 - $this->assertWidgetMatchesXpath($form->createView(), ['placeholder' => ''], - '/select - [@name="name"] - [@required="required"] - [ - ./option[@value=""][not(@selected)][not(@disabled)][.=""] - /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=3] -' - ); - } - - public function testSingleChoiceGrouped() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => [ - 'Group&1' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'Group&2' => ['Choice&C' => '&c'], - ], - 'multiple' => false, - 'expanded' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [./optgroup[@label="[trans]Group&1[/trans]"] - [ - ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=2] - ] - [./optgroup[@label="[trans]Group&2[/trans]"] - [./option[@value="&c"][not(@selected)][.="[trans]Choice&C[/trans]"]] - [count(./option)=1] - ] - [count(./optgroup)=2] -' - ); - } - - public function testMultipleChoice() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a'], [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'required' => true, - 'multiple' => true, - 'expanded' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name[]"] - [@required="required"] - [@multiple="multiple"] - [ - ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=2] -' - ); - } - - public function testMultipleChoiceAttributes() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a'], [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'choice_attr' => ['Choice&B' => ['class' => 'foo&bar']], - 'required' => true, - 'multiple' => true, - 'expanded' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name[]"] - [@required="required"] - [@multiple="multiple"] - [ - ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][@class="foo&bar"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=2] -' - ); - } - - public function testMultipleChoiceSkipsPlaceholder() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a'], [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'multiple' => true, - 'expanded' => false, - 'placeholder' => 'Test&Me', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name[]"] - [@multiple="multiple"] - [ - ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=2] -' - ); - } - - public function testMultipleChoiceNonRequired() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a'], [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'required' => false, - 'multiple' => true, - 'expanded' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name[]"] - [@multiple="multiple"] - [ - ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"] - /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"] - ] - [count(./option)=2] -' - ); - } - - public function testSingleChoiceExpanded() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'multiple' => false, - 'expanded' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] - /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] - /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][@value="&b"][not(@checked)] - /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=3] -' - ); - } - - public function testSingleChoiceExpandedWithoutTranslation() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'multiple' => false, - 'expanded' => true, - 'choice_translation_domain' => false, - 'placeholder' => 'Placeholder&Not&Translated', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] - /following-sibling::label[@for="name_0"][.="Choice&A"] - /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][@value="&b"][not(@checked)] - /following-sibling::label[@for="name_1"][.="Choice&B"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=3] -' - ); - } - - public function testSingleChoiceExpandedAttributes() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'choice_attr' => ['Choice&B' => ['class' => 'foo&bar']], - 'multiple' => false, - 'expanded' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked] - /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] - /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][@value="&b"][@class="foo&bar"][not(@checked)] - /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=3] -' - ); - } - - public function testSingleChoiceExpandedWithPlaceholder() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'multiple' => false, - 'expanded' => true, - 'placeholder' => 'Test&Me', - 'required' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="radio"][@name="name"][@id="name_placeholder"][not(@checked)] - /following-sibling::label[@for="name_placeholder"][.="[trans]Test&Me[/trans]"] - /following-sibling::input[@type="radio"][@name="name"][@id="name_0"][@checked] - /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] - /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][not(@checked)] - /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=4] -' - ); - } - - public function testSingleChoiceExpandedWithPlaceholderWithoutTranslation() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'], - 'multiple' => false, - 'expanded' => true, - 'required' => false, - 'choice_translation_domain' => false, - 'placeholder' => 'Placeholder&Not&Translated', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="radio"][@name="name"][@id="name_placeholder"][not(@checked)] - /following-sibling::label[@for="name_placeholder"][.="Placeholder&Not&Translated"] - /following-sibling::input[@type="radio"][@name="name"][@id="name_0"][@checked] - /following-sibling::label[@for="name_0"][.="Choice&A"] - /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][not(@checked)] - /following-sibling::label[@for="name_1"][.="Choice&B"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=4] -' - ); - } - - public function testSingleChoiceExpandedWithBooleanValue() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', true, [ - 'choices' => ['Choice&A' => '1', 'Choice&B' => '0'], - 'multiple' => false, - 'expanded' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="radio"][@name="name"][@id="name_0"][@checked] - /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] - /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][not(@checked)] - /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=3] -' - ); - } - - public function testMultipleChoiceExpanded() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a', '&c'], [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b', 'Choice&C' => '&c'], - 'multiple' => true, - 'expanded' => true, - 'required' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="checkbox"][@name="name[]"][@id="name_0"][@checked][not(@required)] - /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] - /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_1"][not(@checked)][not(@required)] - /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"] - /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_2"][@checked][not(@required)] - /following-sibling::label[@for="name_2"][.="[trans]Choice&C[/trans]"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=4] -' - ); - } - - public function testMultipleChoiceExpandedWithoutTranslation() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a', '&c'], [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b', 'Choice&C' => '&c'], - 'multiple' => true, - 'expanded' => true, - 'required' => true, - 'choice_translation_domain' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="checkbox"][@name="name[]"][@id="name_0"][@checked][not(@required)] - /following-sibling::label[@for="name_0"][.="Choice&A"] - /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_1"][not(@checked)][not(@required)] - /following-sibling::label[@for="name_1"][.="Choice&B"] - /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_2"][@checked][not(@required)] - /following-sibling::label[@for="name_2"][.="Choice&C"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=4] -' - ); - } - - public function testMultipleChoiceExpandedAttributes() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a', '&c'], [ - 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b', 'Choice&C' => '&c'], - 'choice_attr' => ['Choice&B' => ['class' => 'foo&bar']], - 'multiple' => true, - 'expanded' => true, - 'required' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input[@type="checkbox"][@name="name[]"][@id="name_0"][@checked][not(@required)] - /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"] - /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_1"][@class="foo&bar"][not(@checked)][not(@required)] - /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"] - /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_2"][@checked][not(@required)] - /following-sibling::label[@for="name_2"][.="[trans]Choice&C[/trans]"] - /following-sibling::input[@type="hidden"][@id="name__token"] - ] - [count(./input)=4] -' - ); - } - - public function testCountry() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CountryType', 'AT'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [./option[@value="AT"][@selected="selected"][.="Austria"]] - [count(./option)>200] -' - ); - } - - public function testCountryWithPlaceholder() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CountryType', 'AT', [ - 'placeholder' => 'Select&Country', - 'required' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Select&Country[/trans]"]] - [./option[@value="AT"][@selected="selected"][.="Austria"]] - [count(./option)>201] -' - ); - } - - public function testDateTime() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', date('Y').'-02-03 04:05:06', [ - 'input' => 'string', - 'with_seconds' => false, - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div - [@id="name_date"] - [ - ./select - [@id="name_date_month"] - [./option[@value="2"][@selected="selected"]] - /following-sibling::select - [@id="name_date_day"] - [./option[@value="3"][@selected="selected"]] - /following-sibling::select - [@id="name_date_year"] - [./option[@value="'.date('Y').'"][@selected="selected"]] - ] - /following-sibling::div - [@id="name_time"] - [ - ./select - [@id="name_time_hour"] - [./option[@value="4"][@selected="selected"]] - /following-sibling::select - [@id="name_time_minute"] - [./option[@value="5"][@selected="selected"]] - ] - ] - [count(.//select)=5] -' - ); - } - - public function testDateTimeWithPlaceholderGlobal() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', null, [ - 'input' => 'string', - 'placeholder' => 'Change&Me', - 'required' => false, - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div - [@id="name_date"] - [ - ./select - [@id="name_date_month"] - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]] - /following-sibling::select - [@id="name_date_day"] - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]] - /following-sibling::select - [@id="name_date_year"] - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]] - ] - /following-sibling::div - [@id="name_time"] - [ - ./select - [@id="name_time_hour"] - [./option[@value=""][.="[trans]Change&Me[/trans]"]] - /following-sibling::select - [@id="name_time_minute"] - [./option[@value=""][.="[trans]Change&Me[/trans]"]] - ] - ] - [count(.//select)=5] -' - ); - } - - public function testDateTimeWithHourAndMinute() - { - $data = ['year' => date('Y'), 'month' => '2', 'day' => '3', 'hour' => '4', 'minute' => '5']; - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', $data, [ - 'input' => 'array', - 'required' => false, - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div - [@id="name_date"] - [ - ./select - [@id="name_date_month"] - [./option[@value="2"][@selected="selected"]] - /following-sibling::select - [@id="name_date_day"] - [./option[@value="3"][@selected="selected"]] - /following-sibling::select - [@id="name_date_year"] - [./option[@value="'.date('Y').'"][@selected="selected"]] - ] - /following-sibling::div - [@id="name_time"] - [ - ./select - [@id="name_time_hour"] - [./option[@value="4"][@selected="selected"]] - /following-sibling::select - [@id="name_time_minute"] - [./option[@value="5"][@selected="selected"]] - ] - ] - [count(.//select)=5] -' - ); - } - - public function testDateTimeWithSeconds() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', date('Y').'-02-03 04:05:06', [ - 'input' => 'string', - 'with_seconds' => true, - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./div - [@id="name_date"] - [ - ./select - [@id="name_date_month"] - [./option[@value="2"][@selected="selected"]] - /following-sibling::select - [@id="name_date_day"] - [./option[@value="3"][@selected="selected"]] - /following-sibling::select - [@id="name_date_year"] - [./option[@value="'.date('Y').'"][@selected="selected"]] - ] - /following-sibling::div - [@id="name_time"] - [ - ./select - [@id="name_time_hour"] - [./option[@value="4"][@selected="selected"]] - /following-sibling::select - [@id="name_time_minute"] - [./option[@value="5"][@selected="selected"]] - /following-sibling::select - [@id="name_time_second"] - [./option[@value="6"][@selected="selected"]] - ] - ] - [count(.//select)=6] -' - ); - } - - public function testDateTimeSingleText() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', '2011-02-03 04:05:06', [ - 'input' => 'string', - 'date_widget' => 'single_text', - 'time_widget' => 'single_text', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input - [@type="date"] - [@id="name_date"] - [@name="name[date]"] - [@value="2011-02-03"] - /following-sibling::input - [@type="time"] - [@id="name_time"] - [@name="name[time]"] - [@value="04:05"] - ] -' - ); - } - - public function testDateTimeWithWidgetSingleText() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', '2011-02-03 04:05:06', [ - 'input' => 'string', - 'widget' => 'single_text', - 'model_timezone' => 'UTC', - 'view_timezone' => 'UTC', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="datetime-local"] - [@name="name"] - [@value="2011-02-03T04:05"] -' - ); - } - - public function testDateChoice() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType', date('Y').'-02-03', [ - 'input' => 'string', - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./select - [@id="name_month"] - [./option[@value="2"][@selected="selected"]] - /following-sibling::select - [@id="name_day"] - [./option[@value="3"][@selected="selected"]] - /following-sibling::select - [@id="name_year"] - [./option[@value="'.date('Y').'"][@selected="selected"]] - ] - [count(./select)=3] -' - ); - } - - public function testDateChoiceWithPlaceholderGlobal() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType', null, [ - 'input' => 'string', - 'widget' => 'choice', - 'placeholder' => 'Change&Me', - 'required' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./select - [@id="name_month"] - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]] - /following-sibling::select - [@id="name_day"] - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]] - /following-sibling::select - [@id="name_year"] - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]] - ] - [count(./select)=3] -' - ); - } - - public function testDateChoiceWithPlaceholderOnYear() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType', null, [ - 'input' => 'string', - 'widget' => 'choice', - 'required' => false, - 'placeholder' => ['year' => 'Change&Me'], - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./select - [@id="name_month"] - [./option[@value="1"]] - /following-sibling::select - [@id="name_day"] - [./option[@value="1"]] - /following-sibling::select - [@id="name_year"] - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]] - ] - [count(./select)=3] -' - ); - } - - public function testDateText() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType', '2011-02-03', [ - 'input' => 'string', - 'widget' => 'text', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input - [@id="name_month"] - [@type="text"] - [@value="2"] - /following-sibling::input - [@id="name_day"] - [@type="text"] - [@value="3"] - /following-sibling::input - [@id="name_year"] - [@type="text"] - [@value="2011"] - ] - [count(./input)=3] -' - ); - } - - public function testDateSingleText() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType', '2011-02-03', [ - 'input' => 'string', - 'widget' => 'single_text', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="date"] - [@name="name"] - [@value="2011-02-03"] -' - ); - } - - public function testDateErrorBubbling() - { - $form = $this->factory->createNamedBuilder('form', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('date', 'Symfony\Component\Form\Extension\Core\Type\DateType', ['widget' => 'choice']) - ->getForm(); - $form->get('date')->addError(new FormError('[trans]Error![/trans]')); - $view = $form->createView(); - - $this->assertEmpty($this->renderErrors($view)); - $this->assertNotEmpty($this->renderErrors($view['date'])); - } - - public function testBirthDay() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\BirthdayType', '2000-02-03', [ - 'input' => 'string', - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./select - [@id="name_month"] - [./option[@value="2"][@selected="selected"]] - /following-sibling::select - [@id="name_day"] - [./option[@value="3"][@selected="selected"]] - /following-sibling::select - [@id="name_year"] - [./option[@value="2000"][@selected="selected"]] - ] - [count(./select)=3] -' - ); - } - - public function testBirthDayWithPlaceholder() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\BirthdayType', '1950-01-01', [ - 'input' => 'string', - 'placeholder' => '', - 'required' => false, - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./select - [@id="name_month"] - [./option[@value=""][not(@selected)][not(@disabled)][.=""]] - [./option[@value="1"][@selected="selected"]] - /following-sibling::select - [@id="name_day"] - [./option[@value=""][not(@selected)][not(@disabled)][.=""]] - [./option[@value="1"][@selected="selected"]] - /following-sibling::select - [@id="name_year"] - [./option[@value=""][not(@selected)][not(@disabled)][.=""]] - [./option[@value="1950"][@selected="selected"]] - ] - [count(./select)=3] -' - ); - } - - public function testEmail() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\EmailType', 'foo&bar'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="email"] - [@name="name"] - [@value="foo&bar"] - [not(@maxlength)] -' - ); - } - - public function testEmailWithMaxLength() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\EmailType', 'foo&bar', [ - 'attr' => ['maxlength' => 123], - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="email"] - [@name="name"] - [@value="foo&bar"] - [@maxlength="123"] -' - ); - } - - public function testFile() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\FileType'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="file"] -' - ); - } - - public function testHidden() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\HiddenType', 'foo&bar'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="hidden"] - [@name="name"] - [@value="foo&bar"] -' - ); - } - - public function testDisabled() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'disabled' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="text"] - [@name="name"] - [@disabled="disabled"] -' - ); - } - - public function testInteger() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\IntegerType', 123); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="number"] - [@name="name"] - [@value="123"] -' - ); - } - - public function testIntegerTypeWithGroupingRendersAsTextInput() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\IntegerType', 123, [ - 'grouping' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="text"] - [@name="name"] - [@value="123"] -' - ); - } - - public function testLanguage() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\LanguageType', 'de'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [./option[@value="de"][@selected="selected"][.="German"]] - [count(./option)>200] -' - ); - } - - public function testLocale() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\LocaleType', 'de_AT'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [./option[@value="de_AT"][@selected="selected"][.="German (Austria)"]] - [count(./option)>200] -' - ); - } - - public function testMoney() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\MoneyType', 1234.56, [ - 'currency' => 'EUR', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="text"] - [@name="name"] - [@value="1234.56"] - [contains(.., "€")] -' - ); - } - - public function testNumber() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\NumberType', 1234.56); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="text"] - [@name="name"] - [@value="1234.56"] -' - ); - } - - public function testRenderNumberWithHtml5NumberType() - { - $this->requiresFeatureSet(403); - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\NumberType', 1234.56, [ - 'html5' => true, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="number"] - [@step="any"] - [@name="name"] - [@value="1234.56"] -' - ); - } - - public function testRenderNumberWithHtml5NumberTypeAndStepAttribute() - { - $this->requiresFeatureSet(403); - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\NumberType', 1234.56, [ - 'html5' => true, - 'attr' => ['step' => '0.1'], - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="number"] - [@step="0.1"] - [@name="name"] - [@value="1234.56"] -' - ); - } - - public function testPassword() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\PasswordType', 'foo&bar'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="password"] - [@name="name"] -' - ); - } - - public function testPasswordSubmittedWithNotAlwaysEmpty() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\PasswordType', null, [ - 'always_empty' => false, - ]); - $form->submit('foo&bar'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="password"] - [@name="name"] - [@value="foo&bar"] -' - ); - } - - public function testPasswordWithMaxLength() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\PasswordType', 'foo&bar', [ - 'attr' => ['maxlength' => 123], - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="password"] - [@name="name"] - [@maxlength="123"] -' - ); - } - - public function testPercent() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\PercentType', 0.1, ['rounding_mode' => \NumberFormatter::ROUND_CEILING]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="text"] - [@name="name"] - [@value="10"] - [contains(.., "%")] -' - ); - } - - public function testPercentNoSymbol() - { - $this->requiresFeatureSet(403); - - $form = $this->factory->createNamed('name', PercentType::class, 0.1, ['symbol' => false, 'rounding_mode' => \NumberFormatter::ROUND_CEILING]); - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="text"] - [@name="name"] - [@value="10"] - [not(contains(.., "%"))] -' - ); - } - - public function testPercentCustomSymbol() - { - $this->requiresFeatureSet(403); - - $form = $this->factory->createNamed('name', PercentType::class, 0.1, ['symbol' => '‱', 'rounding_mode' => \NumberFormatter::ROUND_CEILING]); - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="text"] - [@name="name"] - [@value="10"] - [contains(.., "‱")] -' - ); - } - - public function testCheckedRadio() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RadioType', true); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="radio"] - [@name="name"] - [@checked="checked"] - [@value="1"] -' - ); - } - - public function testUncheckedRadio() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RadioType', false); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="radio"] - [@name="name"] - [not(@checked)] -' - ); - } - - public function testRadioWithValue() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RadioType', false, [ - 'value' => 'foo&bar', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="radio"] - [@name="name"] - [@value="foo&bar"] -' - ); - } - - public function testRange() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RangeType', 42, ['attr' => ['min' => 5]]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="range"] - [@name="name"] - [@value="42"] - [@min="5"] -' - ); - } - - public function testRangeWithMinMaxValues() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RangeType', 42, ['attr' => ['min' => 5, 'max' => 57]]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="range"] - [@name="name"] - [@value="42"] - [@min="5"] - [@max="57"] -' - ); - } - - public function testTextarea() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextareaType', 'foo&bar', [ - 'attr' => ['pattern' => 'foo'], - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/textarea - [@name="name"] - [not(@pattern)] - [.="foo&bar"] -' - ); - } - - public function testText() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', 'foo&bar'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="text"] - [@name="name"] - [@value="foo&bar"] - [not(@maxlength)] -' - ); - } - - public function testTextWithMaxLength() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', 'foo&bar', [ - 'attr' => ['maxlength' => 123], - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="text"] - [@name="name"] - [@value="foo&bar"] - [@maxlength="123"] -' - ); - } - - public function testSearch() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\SearchType', 'foo&bar'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="search"] - [@name="name"] - [@value="foo&bar"] - [not(@maxlength)] -' - ); - } - - public function testTime() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TimeType', '04:05:06', [ - 'input' => 'string', - 'with_seconds' => false, - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./select - [@id="name_hour"] - [not(@size)] - [./option[@value="4"][@selected="selected"]] - /following-sibling::select - [@id="name_minute"] - [not(@size)] - [./option[@value="5"][@selected="selected"]] - ] - [count(./select)=2] -' - ); - } - - public function testTimeWithSeconds() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TimeType', '04:05:06', [ - 'input' => 'string', - 'with_seconds' => true, - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./select - [@id="name_hour"] - [not(@size)] - [./option[@value="4"][@selected="selected"]] - [count(./option)>23] - /following-sibling::select - [@id="name_minute"] - [not(@size)] - [./option[@value="5"][@selected="selected"]] - [count(./option)>59] - /following-sibling::select - [@id="name_second"] - [not(@size)] - [./option[@value="6"][@selected="selected"]] - [count(./option)>59] - ] - [count(./select)=3] -' - ); - } - - public function testTimeText() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TimeType', '04:05:06', [ - 'input' => 'string', - 'widget' => 'text', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./input - [@type="text"] - [@id="name_hour"] - [@name="name[hour]"] - [@value="04"] - [@size="1"] - [@required="required"] - /following-sibling::input - [@type="text"] - [@id="name_minute"] - [@name="name[minute]"] - [@value="05"] - [@size="1"] - [@required="required"] - ] - [count(./input)=2] -' - ); - } - - public function testTimeSingleText() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TimeType', '04:05:06', [ - 'input' => 'string', - 'widget' => 'single_text', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="time"] - [@name="name"] - [@value="04:05"] - [not(@size)] -' - ); - } - - public function testTimeWithPlaceholderGlobal() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TimeType', null, [ - 'input' => 'string', - 'placeholder' => 'Change&Me', - 'required' => false, - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./select - [@id="name_hour"] - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]] - [count(./option)>24] - /following-sibling::select - [@id="name_minute"] - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]] - [count(./option)>60] - ] - [count(./select)=2] -' - ); - } - - public function testTimeWithPlaceholderOnYear() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TimeType', null, [ - 'input' => 'string', - 'required' => false, - 'placeholder' => ['hour' => 'Change&Me'], - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/div - [ - ./select - [@id="name_hour"] - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]] - [count(./option)>24] - /following-sibling::select - [@id="name_minute"] - [./option[@value="1"]] - [count(./option)>59] - ] - [count(./select)=2] -' - ); - } - - public function testTimeErrorBubbling() - { - $form = $this->factory->createNamedBuilder('form', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('time', 'Symfony\Component\Form\Extension\Core\Type\TimeType', ['widget' => 'choice']) - ->getForm(); - $form->get('time')->addError(new FormError('[trans]Error![/trans]')); - $view = $form->createView(); - - $this->assertEmpty($this->renderErrors($view)); - $this->assertNotEmpty($this->renderErrors($view['time'])); - } - - public function testTimezone() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TimezoneType', 'Europe/Vienna'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [@name="name"] - [not(@required)] - [./option[@value="Europe/Vienna"][@selected="selected"][.="Europe / Vienna"]] - [count(./option)>200] -' - ); - } - - public function testTimezoneWithPlaceholder() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TimezoneType', null, [ - 'placeholder' => 'Select&Timezone', - 'required' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/select - [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Select&Timezone[/trans]"]] - [count(./option)>201] -' - ); - } - - public function testUrlWithDefaultProtocol() - { - $url = 'http://www.example.com?foo1=bar1&foo2=bar2'; - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\UrlType', $url, ['default_protocol' => 'http']); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="text"] - [@name="name"] - [@value="http://www.example.com?foo1=bar1&foo2=bar2"] - [@inputmode="url"] -' - ); - } - - public function testUrlWithoutDefaultProtocol() - { - $url = 'http://www.example.com?foo1=bar1&foo2=bar2'; - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\UrlType', $url, ['default_protocol' => null]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="url"] - [@name="name"] - [@value="http://www.example.com?foo1=bar1&foo2=bar2"] -' - ); - } - - public function testCollectionPrototype() - { - $form = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType', ['items' => ['one', 'two', 'three']]) - ->add('items', 'Symfony\Component\Form\Extension\Core\Type\CollectionType', ['allow_add' => true]) - ->getForm() - ->createView(); - - $html = $this->renderWidget($form); - - $this->assertMatchesXpath($html, - '//div[@id="name_items"][@data-prototype] - | - //table[@id="name_items"][@data-prototype]' - ); - } - - public function testEmptyRootFormName() - { - $form = $this->factory->createNamedBuilder('', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('child', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm(); - - $this->assertMatchesXpath($this->renderWidget($form->createView()), - '//input[@type="hidden"][@id="_token"][@name="_token"] - | - //input[@type="text"][@id="child"][@name="child"]', 2); - } - - public function testButton() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ButtonType'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/button[@type="button"][@name="name"][.="[trans]Name[/trans]"]' - ); - } - - public function testButtonLabelIsEmpty() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ButtonType'); - - $this->assertSame('', $this->renderLabel($form->createView())); - } - - public function testButtonlabelWithoutTranslation() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ButtonType', null, [ - 'translation_domain' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/button[@type="button"][@name="name"][.="Name"]' - ); - } - - public function testSubmit() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\SubmitType'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/button[@type="submit"][@name="name"]' - ); - } - - public function testReset() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ResetType'); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/button[@type="reset"][@name="name"]' - ); - } - - public function testStartTag() - { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'method' => 'get', - 'action' => 'http://example.com/directory', - ]); - - $html = $this->renderStart($form->createView()); - - $this->assertSame('
', $html); - } - - public function testStartTagForPutRequest() - { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'method' => 'put', - 'action' => 'http://example.com/directory', - ]); - - $html = $this->renderStart($form->createView()); - - $this->assertMatchesXpath($html.'
', - '/form - [./input[@type="hidden"][@name="_method"][@value="PUT"]] - [@method="post"] - [@action="http://example.com/directory"]' - ); - } - - public function testStartTagWithOverriddenVars() - { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'method' => 'put', - 'action' => 'http://example.com/directory', - ]); - - $html = $this->renderStart($form->createView(), [ - 'method' => 'post', - 'action' => 'http://foo.com/directory', - ]); - - $this->assertSame('
', $html); - } - - public function testStartTagForMultipartForm() - { - $form = $this->factory->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'method' => 'get', - 'action' => 'http://example.com/directory', - ]) - ->add('file', 'Symfony\Component\Form\Extension\Core\Type\FileType') - ->getForm(); - - $html = $this->renderStart($form->createView()); - - $this->assertSame('', $html); - } - - public function testStartTagWithExtraAttributes() - { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'method' => 'get', - 'action' => 'http://example.com/directory', - ]); - - $html = $this->renderStart($form->createView(), [ - 'attr' => ['class' => 'foobar'], - ]); - - $this->assertSame('', $html); - } - - public function testWidgetAttributes() - { - $form = $this->factory->createNamed('text', 'Symfony\Component\Form\Extension\Core\Type\TextType', 'value', [ - 'required' => true, - 'disabled' => true, - 'attr' => ['readonly' => true, 'maxlength' => 10, 'pattern' => '\d+', 'class' => 'foobar', 'data-foo' => 'bar'], - ]); - - $html = $this->renderWidget($form->createView()); - - // compare plain HTML to check the whitespace - $this->assertSame('', $html); - } - - public function testWidgetAttributeNameRepeatedIfTrue() - { - $form = $this->factory->createNamed('text', 'Symfony\Component\Form\Extension\Core\Type\TextType', 'value', [ - 'attr' => ['foo' => true], - ]); - - $html = $this->renderWidget($form->createView()); - - // foo="foo" - $this->assertSame('', $html); - } - - public function testWidgetAttributeHiddenIfFalse() - { - $form = $this->factory->createNamed('text', 'Symfony\Component\Form\Extension\Core\Type\TextType', 'value', [ - 'attr' => ['foo' => false], - ]); - - $html = $this->renderWidget($form->createView()); - - $this->assertStringNotContainsString('foo="', $html); - } - - public function testButtonAttributes() - { - $form = $this->factory->createNamed('button', 'Symfony\Component\Form\Extension\Core\Type\ButtonType', null, [ - 'disabled' => true, - 'attr' => ['class' => 'foobar', 'data-foo' => 'bar'], - ]); - - $html = $this->renderWidget($form->createView()); - - // compare plain HTML to check the whitespace - $this->assertSame('', $html); - } - - public function testButtonAttributeNameRepeatedIfTrue() - { - $form = $this->factory->createNamed('button', 'Symfony\Component\Form\Extension\Core\Type\ButtonType', null, [ - 'attr' => ['foo' => true], - ]); - - $html = $this->renderWidget($form->createView()); - - // foo="foo" - $this->assertSame('', $html); - } - - public function testButtonAttributeHiddenIfFalse() - { - $form = $this->factory->createNamed('button', 'Symfony\Component\Form\Extension\Core\Type\ButtonType', null, [ - 'attr' => ['foo' => false], - ]); - - $html = $this->renderWidget($form->createView()); - - $this->assertStringNotContainsString('foo="', $html); - } - - public function testTextareaWithWhitespaceOnlyContentRetainsValue() - { - $form = $this->factory->createNamed('textarea', 'Symfony\Component\Form\Extension\Core\Type\TextareaType', ' '); - - $html = $this->renderWidget($form->createView()); - - $this->assertStringContainsString('> ', $html); - } - - public function testTextareaWithWhitespaceOnlyContentRetainsValueWhenRenderingForm() - { - $form = $this->factory->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', ['textarea' => ' ']) - ->add('textarea', 'Symfony\Component\Form\Extension\Core\Type\TextareaType') - ->getForm(); - - $html = $this->renderForm($form->createView()); - - $this->assertStringContainsString('> ', $html); - } - - public function testWidgetContainerAttributeHiddenIfFalse() - { - $form = $this->factory->createNamed('form', 'Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'attr' => ['foo' => false], - ]); - - $html = $this->renderWidget($form->createView()); - - // no foo - $this->assertStringNotContainsString('foo="', $html); - } - - public function testTranslatedAttributes() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('firstName', 'Symfony\Component\Form\Extension\Core\Type\TextType', ['attr' => ['title' => 'Foo']]) - ->add('lastName', 'Symfony\Component\Form\Extension\Core\Type\TextType', ['attr' => ['placeholder' => 'Bar']]) - ->getForm() - ->createView(); - - $html = $this->renderForm($view); - - $this->assertMatchesXpath($html, '/form//input[@title="[trans]Foo[/trans]"]'); - $this->assertMatchesXpath($html, '/form//input[@placeholder="[trans]Bar[/trans]"]'); - } - - public function testAttributesNotTranslatedWhenTranslationDomainIsFalse() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'translation_domain' => false, - ]) - ->add('firstName', 'Symfony\Component\Form\Extension\Core\Type\TextType', ['attr' => ['title' => 'Foo']]) - ->add('lastName', 'Symfony\Component\Form\Extension\Core\Type\TextType', ['attr' => ['placeholder' => 'Bar']]) - ->getForm() - ->createView(); - - $html = $this->renderForm($view); - - $this->assertMatchesXpath($html, '/form//input[@title="Foo"]'); - $this->assertMatchesXpath($html, '/form//input[@placeholder="Bar"]'); - } - - public function testTel() - { - $tel = '0102030405'; - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TelType', $tel); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="tel"] - [@name="name"] - [@value="0102030405"] -' - ); - } - - public function testColor() - { - $color = '#0000ff'; - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ColorType', $color); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/input - [@type="color"] - [@name="name"] - [@value="#0000ff"] -' - ); - } - - public function testLabelWithTranslationParameters() - { - $this->requiresFeatureSet(403); - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $html = $this->renderLabel($form->createView(), 'Address is %address%', [ - 'label_translation_parameters' => [ - '%address%' => 'Paris, rue de la Paix', - ], - ]); - - $this->assertMatchesXpath($html, - '/label - [@for="name"] - [.="[trans]Address is Paris, rue de la Paix[/trans]"] -' - ); - } - - public function testHelpWithTranslationParameters() - { - $this->requiresFeatureSet(403); - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'help' => 'for company %company%', - 'help_translation_parameters' => [ - '%company%' => 'ACME Ltd.', - ], - ]); - $html = $this->renderHelp($form->createView()); - - $this->assertMatchesXpath($html, - '/* - [@id="name_help"] - [.="[trans]for company ACME Ltd.[/trans]"] -' - ); - } - - public function testLabelWithTranslatableMessage() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'label' => new TranslatableMessage('foo'), - ]); - $html = $this->renderLabel($form->createView()); - - $this->assertMatchesXpath($html, - '/label - [@for="name"] - [.="[trans]foo[/trans]"] -' - ); - } - - public function testHelpWithTranslatableMessage() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'help' => new TranslatableMessage('foo'), - ]); - $html = $this->renderHelp($form->createView()); - - $this->assertMatchesXpath($html, - '/* - [@id="name_help"] - [.="[trans]foo[/trans]"] -' - ); - } - - public function testHelpWithTranslatableInterface() - { - $message = new class() implements TranslatableInterface { - public function trans(TranslatorInterface $translator, string $locale = null): string - { - return $translator->trans('foo'); - } - }; - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'help' => $message, - ]); - $html = $this->renderHelp($form->createView()); - - $this->assertMatchesXpath($html, - '/* - [@id="name_help"] - [.="[trans]foo[/trans]"] -' - ); - } - - public function testAttributesWithTranslationParameters() - { - $this->requiresFeatureSet(403); - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'attr' => [ - 'title' => 'Message to %company%', - 'placeholder' => 'Enter a message to %company%', - ], - 'attr_translation_parameters' => [ - '%company%' => 'ACME Ltd.', - ], - ]); - $html = $this->renderWidget($form->createView()); - - $this->assertMatchesXpath($html, - '/input - [@title="[trans]Message to ACME Ltd.[/trans]"] - [@placeholder="[trans]Enter a message to ACME Ltd.[/trans]"] -' - ); - } - - public function testButtonWithTranslationParameters() - { - $this->requiresFeatureSet(403); - - $form = $this->factory->createNamedBuilder('myform') - ->add('mybutton', 'Symfony\Component\Form\Extension\Core\Type\ButtonType', [ - 'label' => 'Submit to %company%', - 'label_translation_parameters' => [ - '%company%' => 'ACME Ltd.', - ], - ]) - ->getForm(); - $view = $form->get('mybutton')->createView(); - $html = $this->renderWidget($view, ['label_format' => 'form.%name%']); - - $this->assertMatchesXpath($html, - '/button - [.="[trans]Submit to ACME Ltd.[/trans]"] -' - ); - } - - /** - * @dataProvider submitFormNoValidateProvider - */ - public function testSubmitFormNoValidate(bool $validate) - { - $this->requiresFeatureSet(404); - - $form = $this->factory->create(SubmitType::class, null, [ - 'validate' => $validate, - ]); - - $html = $this->renderWidget($form->createView()); - - $xpath = '/button - [@type="submit"] - '; - - if (!$validate) { - $xpath .= '[@formnovalidate="formnovalidate"]'; - } else { - $xpath .= '[not(@formnovalidate="formnovalidate")]'; - } - - $this->assertMatchesXpath($html, $xpath); - } - - public static function submitFormNoValidateProvider() - { - return [ - [false], - [true], - ]; - } - - public function testWeekSingleText() - { - $this->requiresFeatureSet(404); - - $form = $this->factory->createNamed('holidays', 'Symfony\Component\Form\Extension\Core\Type\WeekType', '1970-W01', [ - 'input' => 'string', - 'widget' => 'single_text', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), ['attr' => ['class' => 'my&class']], - '/input - [@type="week"] - [@name="holidays"] - [@class="my&class"] - [@value="1970-W01"] -' - ); - } - - public function testWeekSingleTextNoHtml5() - { - $this->requiresFeatureSet(404); - - $form = $this->factory->createNamed('holidays', 'Symfony\Component\Form\Extension\Core\Type\WeekType', '1970-W01', [ - 'input' => 'string', - 'widget' => 'single_text', - 'html5' => false, - ]); - - $this->assertWidgetMatchesXpath($form->createView(), ['attr' => ['class' => 'my&class']], - '/input - [@type="text"] - [@name="holidays"] - [@class="my&class"] - [@value="1970-W01"] -' - ); - } - - public function testWeekChoices() - { - $this->requiresFeatureSet(404); - - $data = ['year' => (int) date('Y'), 'week' => 1]; - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\WeekType', $data, [ - 'input' => 'array', - 'widget' => 'choice', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), ['attr' => ['class' => 'my&class']], - '/div - [@class="my&class"] - [ - ./select - [@id="name_year"] - [./option[@value="'.$data['year'].'"][@selected="selected"]] - /following-sibling::select - [@id="name_week"] - [./option[@value="'.$data['week'].'"][@selected="selected"]] - ] - [count(.//select)=2]' - ); - } - - public function testWeekText() - { - $this->requiresFeatureSet(404); - - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\WeekType', '2000-W01', [ - 'input' => 'string', - 'widget' => 'text', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), ['attr' => ['class' => 'my&class']], - '/div - [@class="my&class"] - [ - ./input - [@id="name_year"] - [@type="number"] - [@value="2000"] - /following-sibling::input - [@id="name_week"] - [@type="number"] - [@value="1"] - ] - [count(./input)=2]' - ); - } -} diff --git a/Tests/AbstractTableLayoutTestCase.php b/Tests/AbstractTableLayoutTestCase.php deleted file mode 100644 index 09d669129f..0000000000 --- a/Tests/AbstractTableLayoutTestCase.php +++ /dev/null @@ -1,536 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Form\Tests; - -use Symfony\Component\Form\FormError; -use Symfony\Component\Security\Csrf\CsrfToken; - -abstract class AbstractTableLayoutTestCase extends AbstractLayoutTestCase -{ - public function testRow() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - $form->addError(new FormError('[trans]Error![/trans]')); - $view = $form->createView(); - $html = $this->renderRow($view); - - $this->assertMatchesXpath($html, - '/tr - [ - ./td - [./label[@for="name"]] - /following-sibling::td - [ - ./ul - [./li[.="[trans]Error![/trans]"]] - [count(./li)=1] - /following-sibling::input[@id="name"] - ] - ] -' - ); - } - - public function testLabelIsNotRenderedWhenSetToFalse() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'label' => false, - ]); - $html = $this->renderRow($form->createView()); - - $this->assertMatchesXpath($html, - '/tr - [ - ./td - [count(//label)=0] - /following-sibling::td - [./input[@id="name"]] - ] -' - ); - } - - public function testRepeatedRow() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType'); - $html = $this->renderRow($form->createView()); - - $this->assertMatchesXpath($html, - '/tr - [ - ./td - [./label[@for="name_first"]] - /following-sibling::td - [./input[@id="name_first"]] - ] -/following-sibling::tr - [ - ./td - [./label[@for="name_second"]] - /following-sibling::td - [./input[@id="name_second"]] - ] -/following-sibling::tr[@style="display: none"] - [./td[@colspan="2"]/input - [@type="hidden"] - [@id="name__token"] - ] - [count(../tr)=3] -' - ); - } - - public function testRepeatedRowWithErrors() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType'); - $form->addError(new FormError('[trans]Error![/trans]')); - $view = $form->createView(); - $html = $this->renderRow($view); - - // The errors of the form are not rendered by intention! - // In practice, repeated fields cannot have errors as all errors - // on them are mapped to the first child. - // (see RepeatedTypeValidatorExtension) - - $this->assertMatchesXpath($html, - '/tr - [ - ./td - [./label[@for="name_first"]] - /following-sibling::td - [./input[@id="name_first"]] - ] -/following-sibling::tr - [ - ./td - [./label[@for="name_second"]] - /following-sibling::td - [./input[@id="name_second"]] - ] -/following-sibling::tr[@style="display: none"] - [./td[@colspan="2"]/input - [@type="hidden"] - [@id="name__token"] - ] - [count(../tr)=3] -' - ); - } - - public function testButtonRow() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ButtonType'); - $view = $form->createView(); - $html = $this->renderRow($view); - - $this->assertMatchesXpath($html, - '/tr - [ - ./td - [.=""] - /following-sibling::td - [./button[@type="button"][@name="name"]] - ] - [count(//label)=0] -' - ); - } - - public function testRest() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('field1', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('field2', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType') - ->add('field3', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('field4', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm() - ->createView(); - - // Render field2 row -> does not implicitly call renderWidget because - // it is a repeated field! - $this->renderRow($view['field2']); - - // Render field3 widget - $this->renderWidget($view['field3']); - - // Rest should only contain field1 and field4 - $html = $this->renderRest($view); - - $this->assertMatchesXpath($html, - '/tr - [ - ./td - [./label[@for="name_field1"]] - /following-sibling::td - [./input[@id="name_field1"]] - ] -/following-sibling::tr - [ - ./td - [./label[@for="name_field4"]] - /following-sibling::td - [./input[@id="name_field4"]] - ] - [count(../tr)=3] - [count(..//label)=2] - [count(..//input)=3] -/following-sibling::tr[@style="display: none"] - [./td[@colspan="2"]/input - [@type="hidden"] - [@id="name__token"] - ] -' - ); - } - - public function testCollection() - { - $form = $this->factory->createNamed('names', 'Symfony\Component\Form\Extension\Core\Type\CollectionType', ['a', 'b'], [ - 'entry_type' => 'Symfony\Component\Form\Extension\Core\Type\TextType', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/table - [ - ./tr[./td/input[@type="text"][@value="a"]] - /following-sibling::tr[./td/input[@type="text"][@value="b"]] - /following-sibling::tr[@style="display: none"][./td[@colspan="2"]/input[@type="hidden"][@id="names__token"]] - ] - [count(./tr[./td/input])=3] -' - ); - } - - public function testEmptyCollection() - { - $form = $this->factory->createNamed('names', 'Symfony\Component\Form\Extension\Core\Type\CollectionType', [], [ - 'entry_type' => 'Symfony\Component\Form\Extension\Core\Type\TextType', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/table - [./tr[@style="display: none"][./td[@colspan="2"]/input[@type="hidden"][@id="names__token"]]] - [count(./tr[./td/input])=1] -' - ); - } - - public function testForm() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->setMethod('PUT') - ->setAction('http://example.com') - ->add('firstName', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('lastName', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm() - ->createView(); - - $html = $this->renderForm($view, [ - 'id' => 'my&id', - 'attr' => ['class' => 'my&class'], - ]); - - $this->assertMatchesXpath($html, - '/form - [ - ./input[@type="hidden"][@name="_method"][@value="PUT"] - /following-sibling::table - [ - ./tr - [ - ./td - [./label[@for="name_firstName"]] - /following-sibling::td - [./input[@id="name_firstName"]] - ] - /following-sibling::tr - [ - ./td - [./label[@for="name_lastName"]] - /following-sibling::td - [./input[@id="name_lastName"]] - ] - /following-sibling::tr[@style="display: none"] - [./td[@colspan="2"]/input - [@type="hidden"] - [@id="name__token"] - ] - ] - [count(.//input)=3] - [@id="my&id"] - [@class="my&class"] - ] - [@method="post"] - [@action="http://example.com"] - [@class="my&class"] -' - ); - } - - public function testFormWidget() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('firstName', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('lastName', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm() - ->createView(); - - $this->assertWidgetMatchesXpath($view, [], - '/table - [ - ./tr - [ - ./td - [./label[@for="name_firstName"]] - /following-sibling::td - [./input[@id="name_firstName"]] - ] - /following-sibling::tr - [ - ./td - [./label[@for="name_lastName"]] - /following-sibling::td - [./input[@id="name_lastName"]] - ] - /following-sibling::tr[@style="display: none"] - [./td[@colspan="2"]/input - [@type="hidden"] - [@id="name__token"] - ] - ] - [count(.//input)=3] -' - ); - } - - // https://github.com/symfony/symfony/issues/2308 - public function testNestedFormError() - { - $form = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add($this->factory - ->createNamedBuilder('child', 'Symfony\Component\Form\Extension\Core\Type\FormType', null, ['error_bubbling' => false]) - ->add('grandChild', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ) - ->getForm(); - - $form->get('child')->addError(new FormError('[trans]Error![/trans]')); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/table - [ - ./tr/td/ul[./li[.="[trans]Error![/trans]"]] - /following-sibling::table[@id="name_child"] - ] - [count(.//li[.="[trans]Error![/trans]"])=1] -' - ); - } - - public function testCsrf() - { - $this->csrfTokenManager->expects($this->any()) - ->method('getToken') - ->willReturn(new CsrfToken('token_id', 'foo&bar')); - - $form = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add($this->factory - // No CSRF protection on nested forms - ->createNamedBuilder('child', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add($this->factory->createNamedBuilder('grandchild', 'Symfony\Component\Form\Extension\Core\Type\TextType')) - ) - ->getForm(); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/table - [ - ./tr[@style="display: none"] - [./td[@colspan="2"]/input - [@type="hidden"] - [@id="name__token"] - ] - ] - [count(.//input[@type="hidden"])=1] -' - ); - } - - public function testRepeated() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType', 'foobar', [ - 'type' => 'Symfony\Component\Form\Extension\Core\Type\TextType', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/table - [ - ./tr - [ - ./td - [./label[@for="name_first"]] - /following-sibling::td - [./input[@type="text"][@id="name_first"]] - ] - /following-sibling::tr - [ - ./td - [./label[@for="name_second"]] - /following-sibling::td - [./input[@type="text"][@id="name_second"]] - ] - /following-sibling::tr[@style="display: none"] - [./td[@colspan="2"]/input - [@type="hidden"] - [@id="name__token"] - ] - ] - [count(.//input)=3] -' - ); - } - - public function testRepeatedWithCustomOptions() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\RepeatedType', 'foobar', [ - 'type' => 'Symfony\Component\Form\Extension\Core\Type\PasswordType', - 'first_options' => ['label' => 'Test', 'required' => false], - 'second_options' => ['label' => 'Test2'], - ]); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/table - [ - ./tr - [ - ./td - [./label[@for="name_first"][.="[trans]Test[/trans]"]] - /following-sibling::td - [./input[@type="password"][@id="name_first"][@required="required"]] - ] - /following-sibling::tr - [ - ./td - [./label[@for="name_second"][.="[trans]Test2[/trans]"]] - /following-sibling::td - [./input[@type="password"][@id="name_second"][@required="required"]] - ] - /following-sibling::tr[@style="display: none"] - [./td[@colspan="2"]/input - [@type="hidden"] - [@id="name__token"] - ] - ] - [count(.//input)=3] -' - ); - } - - /** - * The block "_name_child_label" should be overridden in the theme of the - * implemented driver. - */ - public function testCollectionRowWithCustomBlock() - { - $collection = ['one', 'two', 'three']; - $form = $this->factory->createNamedBuilder('names', 'Symfony\Component\Form\Extension\Core\Type\CollectionType', $collection) - ->getForm(); - - $this->assertWidgetMatchesXpath($form->createView(), [], - '/table - [ - ./tr[./td/label[.="Custom label: [trans]0[/trans]"]] - /following-sibling::tr[./td/label[.="Custom label: [trans]1[/trans]"]] - /following-sibling::tr[./td/label[.="Custom label: [trans]2[/trans]"]] - ] -' - ); - } - - public function testFormEndWithRest() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('field1', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('field2', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm() - ->createView(); - - $this->renderWidget($view['field1']); - - // Rest should only contain field2 - $html = $this->renderEnd($view); - - // Insert the start tag, the end tag should be rendered by the helper - // Unfortunately this is not valid HTML, because the surrounding table - // tag is missing. If someone renders a form with table layout - // manually, they should call form_rest() explicitly within the - // tag. - $this->assertMatchesXpath(''.$html, - '/form - [ - ./tr - [ - ./td - [./label[@for="name_field2"]] - /following-sibling::td - [./input[@id="name_field2"]] - ] - /following-sibling::tr[@style="display: none"] - [./td[@colspan="2"]/input - [@type="hidden"] - [@id="name__token"] - ] - ] -' - ); - } - - public function testFormEndWithoutRest() - { - $view = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType') - ->add('field1', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->add('field2', 'Symfony\Component\Form\Extension\Core\Type\TextType') - ->getForm() - ->createView(); - - $this->renderWidget($view['field1']); - - // Rest should only contain field2, but isn't rendered - $html = $this->renderEnd($view, ['render_rest' => false]); - - $this->assertEquals('', $html); - } - - public function testWidgetContainerAttributes() - { - $form = $this->factory->createNamed('form', 'Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'attr' => ['class' => 'foobar', 'data-foo' => 'bar'], - ]); - - $form->add('text', 'Symfony\Component\Form\Extension\Core\Type\TextType'); - - $html = $this->renderWidget($form->createView()); - - // compare plain HTML to check the whitespace - $this->assertStringContainsString('
', $html); - } - - public function testWidgetContainerAttributeNameRepeatedIfTrue() - { - $form = $this->factory->createNamed('form', 'Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'attr' => ['foo' => true], - ]); - - $html = $this->renderWidget($form->createView()); - - // foo="foo" - $this->assertStringContainsString('
', $html); - } -} From cb76849c06d2181cdfffd059df9826c6f223e4b4 Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Sun, 23 Apr 2023 22:56:27 +0200 Subject: [PATCH 106/208] Add missing return types --- AbstractType.php | 6 ++ ButtonBuilder.php | 64 +++++++++++++++++++ .../DataAccessor/PropertyPathAccessor.php | 2 +- Extension/Core/Type/ChoiceType.php | 16 ++++- Extension/Core/Type/DateType.php | 9 +++ Extension/Core/Type/FileType.php | 12 ++++ Extension/Core/Type/MoneyType.php | 2 + .../ViolationMapper/ViolationPathIterator.php | 3 + 8 files changed, 111 insertions(+), 3 deletions(-) diff --git a/AbstractType.php b/AbstractType.php index b163506132..ad4b195696 100644 --- a/AbstractType.php +++ b/AbstractType.php @@ -48,11 +48,17 @@ public function configureOptions(OptionsResolver $resolver) { } + /** + * @return string + */ public function getBlockPrefix() { return StringUtil::fqcnToBlockPrefix(static::class) ?: ''; } + /** + * @return string|null + */ public function getParent() { return FormType::class; diff --git a/ButtonBuilder.php b/ButtonBuilder.php index 9cc32888e1..20a30968d4 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -52,6 +52,8 @@ public function __construct(?string $name, array $options = []) /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function add(string|FormBuilderInterface $child, string $type = null, array $options = []): static @@ -62,6 +64,8 @@ public function add(string|FormBuilderInterface $child, string $type = null, arr /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function create(string $name, string $type = null, array $options = []): FormBuilderInterface @@ -72,6 +76,8 @@ public function create(string $name, string $type = null, array $options = []): /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function get(string $name): FormBuilderInterface @@ -82,6 +88,8 @@ public function get(string $name): FormBuilderInterface /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function remove(string $name): static @@ -116,6 +124,8 @@ public function getForm(): Button /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function addEventListener(string $eventName, callable $listener, int $priority = 0): static @@ -126,6 +136,8 @@ public function addEventListener(string $eventName, callable $listener, int $pri /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function addEventSubscriber(EventSubscriberInterface $subscriber): static @@ -136,6 +148,8 @@ public function addEventSubscriber(EventSubscriberInterface $subscriber): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false): static @@ -146,6 +160,8 @@ public function addViewTransformer(DataTransformerInterface $viewTransformer, bo /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function resetViewTransformers(): static @@ -156,6 +172,8 @@ public function resetViewTransformers(): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function addModelTransformer(DataTransformerInterface $modelTransformer, bool $forceAppend = false): static @@ -166,6 +184,8 @@ public function addModelTransformer(DataTransformerInterface $modelTransformer, /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function resetModelTransformers(): static @@ -196,6 +216,8 @@ public function setAttributes(array $attributes): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setDataMapper(DataMapperInterface $dataMapper = null): static @@ -222,6 +244,8 @@ public function setDisabled(bool $disabled): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setEmptyData(mixed $emptyData): static @@ -232,6 +256,8 @@ public function setEmptyData(mixed $emptyData): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setErrorBubbling(bool $errorBubbling): static @@ -242,6 +268,8 @@ public function setErrorBubbling(bool $errorBubbling): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setRequired(bool $required): static @@ -252,6 +280,8 @@ public function setRequired(bool $required): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setPropertyPath(string|PropertyPathInterface|null $propertyPath): static @@ -262,6 +292,8 @@ public function setPropertyPath(string|PropertyPathInterface|null $propertyPath) /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setMapped(bool $mapped): static @@ -272,6 +304,8 @@ public function setMapped(bool $mapped): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setByReference(bool $byReference): static @@ -282,6 +316,8 @@ public function setByReference(bool $byReference): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setCompound(bool $compound): static @@ -304,6 +340,8 @@ public function setType(ResolvedFormTypeInterface $type): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setData(mixed $data): static @@ -314,6 +352,8 @@ public function setData(mixed $data): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setDataLocked(bool $locked): static @@ -324,6 +364,8 @@ public function setDataLocked(bool $locked): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setFormFactory(FormFactoryInterface $formFactory) @@ -334,6 +376,8 @@ public function setFormFactory(FormFactoryInterface $formFactory) /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setAction(string $action): static @@ -344,6 +388,8 @@ public function setAction(string $action): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setMethod(string $method): static @@ -354,6 +400,8 @@ public function setMethod(string $method): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setRequestHandler(RequestHandlerInterface $requestHandler): static @@ -380,6 +428,8 @@ public function setAutoInitialize(bool $initialize): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setInheritData(bool $inheritData): static @@ -402,6 +452,8 @@ public function getFormConfig(): FormConfigInterface /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function setIsEmptyCallback(?callable $isEmptyCallback): static @@ -412,6 +464,8 @@ public function setIsEmptyCallback(?callable $isEmptyCallback): static /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function getEventDispatcher(): EventDispatcherInterface @@ -570,6 +624,8 @@ public function getDataLocked(): bool /** * Unsupported method. + * + * @return never */ public function getFormFactory(): FormFactoryInterface { @@ -579,6 +635,8 @@ public function getFormFactory(): FormFactoryInterface /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function getAction(): string @@ -589,6 +647,8 @@ public function getAction(): string /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function getMethod(): string @@ -599,6 +659,8 @@ public function getMethod(): string /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function getRequestHandler(): RequestHandlerInterface @@ -649,6 +711,8 @@ public function getOption(string $name, mixed $default = null): mixed /** * Unsupported method. * + * @return never + * * @throws BadMethodCallException */ public function getIsEmptyCallback(): ?callable diff --git a/Extension/Core/DataAccessor/PropertyPathAccessor.php b/Extension/Core/DataAccessor/PropertyPathAccessor.php index 85efa150f4..e06f583cbd 100644 --- a/Extension/Core/DataAccessor/PropertyPathAccessor.php +++ b/Extension/Core/DataAccessor/PropertyPathAccessor.php @@ -74,7 +74,7 @@ public function isWritable(object|array $data, FormInterface $form): bool return null !== $form->getPropertyPath(); } - private function getPropertyValue(object|array $data, PropertyPathInterface $propertyPath) + private function getPropertyValue(object|array $data, PropertyPathInterface $propertyPath): mixed { try { return $this->propertyAccessor->getValue($data, $propertyPath); diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 5e5997ddf9..4dcd3b6877 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -62,6 +62,9 @@ public function __construct(ChoiceListFactoryInterface $choiceListFactory = null $this->translator = $translator; } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $unknownValues = []; @@ -215,6 +218,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) }, 256); } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { $choiceTranslationDomain = $options['choice_translation_domain']; @@ -269,6 +275,9 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function finishView(FormView $view, FormInterface $form, array $options) { if ($options['expanded']) { @@ -286,6 +295,9 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $emptyData = static function (Options $options) { @@ -383,7 +395,7 @@ public function getBlockPrefix(): string /** * Adds the sub fields for an expanded choice field. */ - private function addSubForms(FormBuilderInterface $builder, array $choiceViews, array $options) + private function addSubForms(FormBuilderInterface $builder, array $choiceViews, array $options): void { foreach ($choiceViews as $name => $choiceView) { // Flatten groups @@ -401,7 +413,7 @@ private function addSubForms(FormBuilderInterface $builder, array $choiceViews, } } - private function addSubForm(FormBuilderInterface $builder, string $name, ChoiceView $choiceView, array $options) + private function addSubForm(FormBuilderInterface $builder, string $name, ChoiceView $choiceView, array $options): void { $choiceOpts = [ 'value' => $choiceView->value, diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index 5c079f137d..3b68dc241a 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -43,6 +43,9 @@ class DateType extends AbstractType 'choice' => ChoiceType::class, ]; + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { $dateFormat = \is_int($options['format']) ? $options['format'] : self::DEFAULT_FORMAT; @@ -177,6 +180,9 @@ class_exists(\IntlTimeZone::class, false) ? \IntlTimeZone::createDefault() : nul } } + /** + * @return void + */ public function finishView(FormView $view, FormInterface $form, array $options) { $view->vars['widget'] = $options['widget']; @@ -214,6 +220,9 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $compound = static fn (Options $options) => 'single_text' !== $options['widget']; diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index 6e4b78251d..cf8e1a7439 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -41,6 +41,9 @@ public function __construct(TranslatorInterface $translator = null) $this->translator = $translator; } + /** + * @return void + */ public function buildForm(FormBuilderInterface $builder, array $options) { // Ensure that submitted data is always an uploaded file or an array of some @@ -82,6 +85,9 @@ public function buildForm(FormBuilderInterface $builder, array $options) }); } + /** + * @return void + */ public function buildView(FormView $view, FormInterface $form, array $options) { if ($options['multiple']) { @@ -95,11 +101,17 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } + /** + * @return void + */ public function finishView(FormView $view, FormInterface $form, array $options) { $view->vars['multipart'] = true; } + /** + * @return void + */ public function configureOptions(OptionsResolver $resolver) { $dataClass = null; diff --git a/Extension/Core/Type/MoneyType.php b/Extension/Core/Type/MoneyType.php index 27c1dbb49b..9c9e5b4d7c 100644 --- a/Extension/Core/Type/MoneyType.php +++ b/Extension/Core/Type/MoneyType.php @@ -103,6 +103,8 @@ public function getBlockPrefix(): string * * The pattern contains the placeholder "{{ widget }}" where the HTML tag should * be inserted + * + * @return string */ protected static function getPattern(?string $currency) { diff --git a/Extension/Validator/ViolationMapper/ViolationPathIterator.php b/Extension/Validator/ViolationMapper/ViolationPathIterator.php index 50baa4533e..ed363a7b15 100644 --- a/Extension/Validator/ViolationMapper/ViolationPathIterator.php +++ b/Extension/Validator/ViolationMapper/ViolationPathIterator.php @@ -23,6 +23,9 @@ public function __construct(ViolationPath $violationPath) parent::__construct($violationPath); } + /** + * @return bool + */ public function mapsForm() { return $this->path->mapsForm($this->key()); From e2be9c81a023abe12a8d7a9f8f734ca9e9601a4c Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 11 May 2023 10:20:44 +0200 Subject: [PATCH 107/208] Remove unnecessary usages of DateTime --- .../Core/DataTransformer/DateTimeToArrayTransformer.php | 5 +---- .../DateTimeToHtml5LocalDateTimeTransformer.php | 5 +---- .../Core/DataTransformer/DateTimeToRfc3339Transformer.php | 5 +---- .../Core/DataTransformer/DateTimeToStringTransformer.php | 5 +---- Extension/Core/Type/DateType.php | 2 +- Extension/Validator/ValidatorTypeGuesser.php | 6 ++++++ .../Core/DataTransformer/Traits/DateTimeEqualsTrait.php | 2 +- Tests/Extension/Validator/ValidatorTypeGuesserTest.php | 1 + 8 files changed, 13 insertions(+), 18 deletions(-) diff --git a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php index 1f48aed1ad..6675d1c24a 100644 --- a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php @@ -67,10 +67,7 @@ public function transform(mixed $dateTime): array } if ($this->inputTimezone !== $this->outputTimezone) { - if (!$dateTime instanceof \DateTimeImmutable) { - $dateTime = clone $dateTime; - } - + $dateTime = \DateTimeImmutable::createFromInterface($dateTime); $dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone)); } diff --git a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php index a59ad9cb72..2dc157cd83 100644 --- a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php @@ -53,10 +53,7 @@ public function transform(mixed $dateTime): string } if ($this->inputTimezone !== $this->outputTimezone) { - if (!$dateTime instanceof \DateTimeImmutable) { - $dateTime = clone $dateTime; - } - + $dateTime = \DateTimeImmutable::createFromInterface($dateTime); $dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone)); } diff --git a/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php b/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php index 63f12b1f17..41e63e57ca 100644 --- a/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php +++ b/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php @@ -38,10 +38,7 @@ public function transform(mixed $dateTime): string } if ($this->inputTimezone !== $this->outputTimezone) { - if (!$dateTime instanceof \DateTimeImmutable) { - $dateTime = clone $dateTime; - } - + $dateTime = \DateTimeImmutable::createFromInterface($dateTime); $dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone)); } diff --git a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php index 23392ddd1c..ca0d2e59db 100644 --- a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php @@ -85,10 +85,7 @@ public function transform(mixed $dateTime): string throw new TransformationFailedException('Expected a \DateTimeInterface.'); } - if (!$dateTime instanceof \DateTimeImmutable) { - $dateTime = clone $dateTime; - } - + $dateTime = \DateTimeImmutable::createFromInterface($dateTime); $dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone)); return $dateTime->format($this->generateFormat); diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index 3b68dc241a..80023affcb 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -362,7 +362,7 @@ private function listYears(array $years): array $result = []; foreach ($years as $year) { - $result[\PHP_INT_SIZE === 4 ? \DateTime::createFromFormat('Y e', $year.' UTC')->format('U') : gmmktime(0, 0, 0, 6, 15, $year)] = $year; + $result[\PHP_INT_SIZE === 4 ? \DateTimeImmutable::createFromFormat('Y e', $year.' UTC')->format('U') : gmmktime(0, 0, 0, 6, 15, $year)] = $year; } return $result; diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index 9a74a125ed..57bccaa39f 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -115,6 +115,12 @@ public function guessTypeForConstraint(Constraint $constraint): ?TypeGuess case '\DateTime': return new TypeGuess(DateType::class, [], Guess::MEDIUM_CONFIDENCE); + case \DateTimeImmutable::class: + case '\DateTimeImmutable': + case \DateTimeInterface::class: + case '\DateTimeInterface': + return new TypeGuess(DateType::class, ['input' => 'datetime_immutable'], Guess::MEDIUM_CONFIDENCE); + case 'string': return new TypeGuess(TextType::class, [], Guess::LOW_CONFIDENCE); } diff --git a/Tests/Extension/Core/DataTransformer/Traits/DateTimeEqualsTrait.php b/Tests/Extension/Core/DataTransformer/Traits/DateTimeEqualsTrait.php index 738c4d96b0..7b582df7ac 100644 --- a/Tests/Extension/Core/DataTransformer/Traits/DateTimeEqualsTrait.php +++ b/Tests/Extension/Core/DataTransformer/Traits/DateTimeEqualsTrait.php @@ -18,7 +18,7 @@ trait DateTimeEqualsTrait { public static function assertDateTimeEquals($expected, $actual) { - if ($expected instanceof \DateTime && $actual instanceof \DateTime) { + if ($expected instanceof \DateTimeInterface && $actual instanceof \DateTimeInterface) { $expected = $expected->format('c'); $actual = $actual->format('c'); } diff --git a/Tests/Extension/Validator/ValidatorTypeGuesserTest.php b/Tests/Extension/Validator/ValidatorTypeGuesserTest.php index 8648dc3d49..0c8ab23e83 100644 --- a/Tests/Extension/Validator/ValidatorTypeGuesserTest.php +++ b/Tests/Extension/Validator/ValidatorTypeGuesserTest.php @@ -93,6 +93,7 @@ public static function guessTypeProvider() [new Type('long'), new TypeGuess(IntegerType::class, [], Guess::MEDIUM_CONFIDENCE)], [new Type('string'), new TypeGuess(TextType::class, [], Guess::LOW_CONFIDENCE)], [new Type(\DateTime::class), new TypeGuess(DateType::class, [], Guess::MEDIUM_CONFIDENCE)], + [new Type(\DateTimeImmutable::class), new TypeGuess(DateType::class, ['input' => 'datetime_immutable'], Guess::MEDIUM_CONFIDENCE)], [new Type('\DateTime'), new TypeGuess(DateType::class, [], Guess::MEDIUM_CONFIDENCE)], ]; } From c7406c6a5f08478163d7bdf4b441ce21cf12f8b8 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 23 May 2023 17:38:00 +0200 Subject: [PATCH 108/208] [6.4] Allow 7.0 deps --- composer.json | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/composer.json b/composer.json index 1401929459..efb43f19e1 100644 --- a/composer.json +++ b/composer.json @@ -18,30 +18,30 @@ "require": { "php": ">=8.1", "symfony/deprecation-contracts": "^2.5|^3", - "symfony/event-dispatcher": "^5.4|^6.0", - "symfony/options-resolver": "^5.4|^6.0", + "symfony/event-dispatcher": "^5.4|^6.0|^7.0", + "symfony/options-resolver": "^5.4|^6.0|^7.0", "symfony/polyfill-ctype": "~1.8", "symfony/polyfill-intl-icu": "^1.21", "symfony/polyfill-mbstring": "~1.0", - "symfony/property-access": "^5.4|^6.0", + "symfony/property-access": "^5.4|^6.0|^7.0", "symfony/service-contracts": "^2.5|^3" }, "require-dev": { "doctrine/collections": "^1.0|^2.0", - "symfony/validator": "^5.4|^6.0", - "symfony/dependency-injection": "^5.4|^6.0", - "symfony/expression-language": "^5.4|^6.0", - "symfony/config": "^5.4|^6.0", - "symfony/console": "^5.4|^6.0", - "symfony/html-sanitizer": "^6.1", - "symfony/http-foundation": "^5.4|^6.0", - "symfony/http-kernel": "^5.4|^6.0", - "symfony/intl": "^5.4|^6.0", - "symfony/security-core": "^6.2", - "symfony/security-csrf": "^5.4|^6.0", - "symfony/translation": "^5.4|^6.0", - "symfony/var-dumper": "^5.4|^6.0", - "symfony/uid": "^5.4|^6.0" + "symfony/validator": "^5.4|^6.0|^7.0", + "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/expression-language": "^5.4|^6.0|^7.0", + "symfony/config": "^5.4|^6.0|^7.0", + "symfony/console": "^5.4|^6.0|^7.0", + "symfony/html-sanitizer": "^6.1|^7.0", + "symfony/http-foundation": "^5.4|^6.0|^7.0", + "symfony/http-kernel": "^5.4|^6.0|^7.0", + "symfony/intl": "^5.4|^6.0|^7.0", + "symfony/security-core": "^6.2|^7.0", + "symfony/security-csrf": "^5.4|^6.0|^7.0", + "symfony/translation": "^5.4|^6.0|^7.0", + "symfony/var-dumper": "^5.4|^6.0|^7.0", + "symfony/uid": "^5.4|^6.0|^7.0" }, "conflict": { "phpunit/phpunit": "<5.4.3", From 5c4b8de1854b5d0964c38fd138da1fd273c53841 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 23 May 2023 17:24:39 +0200 Subject: [PATCH 109/208] [7.0] Bump to PHP 8.2 minimum --- composer.json | 52 +++++++++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/composer.json b/composer.json index efb43f19e1..53519c294c 100644 --- a/composer.json +++ b/composer.json @@ -16,44 +16,44 @@ } ], "require": { - "php": ">=8.1", + "php": ">=8.2", "symfony/deprecation-contracts": "^2.5|^3", - "symfony/event-dispatcher": "^5.4|^6.0|^7.0", - "symfony/options-resolver": "^5.4|^6.0|^7.0", + "symfony/event-dispatcher": "^6.4|^7.0", + "symfony/options-resolver": "^6.4|^7.0", "symfony/polyfill-ctype": "~1.8", "symfony/polyfill-intl-icu": "^1.21", "symfony/polyfill-mbstring": "~1.0", - "symfony/property-access": "^5.4|^6.0|^7.0", + "symfony/property-access": "^6.4|^7.0", "symfony/service-contracts": "^2.5|^3" }, "require-dev": { "doctrine/collections": "^1.0|^2.0", - "symfony/validator": "^5.4|^6.0|^7.0", - "symfony/dependency-injection": "^5.4|^6.0|^7.0", - "symfony/expression-language": "^5.4|^6.0|^7.0", - "symfony/config": "^5.4|^6.0|^7.0", - "symfony/console": "^5.4|^6.0|^7.0", - "symfony/html-sanitizer": "^6.1|^7.0", - "symfony/http-foundation": "^5.4|^6.0|^7.0", - "symfony/http-kernel": "^5.4|^6.0|^7.0", - "symfony/intl": "^5.4|^6.0|^7.0", - "symfony/security-core": "^6.2|^7.0", - "symfony/security-csrf": "^5.4|^6.0|^7.0", - "symfony/translation": "^5.4|^6.0|^7.0", - "symfony/var-dumper": "^5.4|^6.0|^7.0", - "symfony/uid": "^5.4|^6.0|^7.0" + "symfony/validator": "^6.4|^7.0", + "symfony/dependency-injection": "^6.4|^7.0", + "symfony/expression-language": "^6.4|^7.0", + "symfony/config": "^6.4|^7.0", + "symfony/console": "^6.4|^7.0", + "symfony/html-sanitizer": "^6.4|^7.0", + "symfony/http-foundation": "^6.4|^7.0", + "symfony/http-kernel": "^6.4|^7.0", + "symfony/intl": "^6.4|^7.0", + "symfony/security-core": "^6.4|^7.0", + "symfony/security-csrf": "^6.4|^7.0", + "symfony/translation": "^6.4|^7.0", + "symfony/var-dumper": "^6.4|^7.0", + "symfony/uid": "^6.4|^7.0" }, "conflict": { "phpunit/phpunit": "<5.4.3", - "symfony/console": "<5.4", - "symfony/dependency-injection": "<5.4", - "symfony/doctrine-bridge": "<5.4.21|>=6,<6.2.7", - "symfony/error-handler": "<5.4", - "symfony/framework-bundle": "<5.4", - "symfony/http-kernel": "<5.4", - "symfony/translation": "<5.4", + "symfony/console": "<6.4", + "symfony/dependency-injection": "<6.4", + "symfony/doctrine-bridge": "<6.4", + "symfony/error-handler": "<6.4", + "symfony/framework-bundle": "<6.4", + "symfony/http-kernel": "<6.4", + "symfony/translation": "<6.4", "symfony/translation-contracts": "<2.5", - "symfony/twig-bridge": "<6.3" + "symfony/twig-bridge": "<6.4" }, "autoload": { "psr-4": { "Symfony\\Component\\Form\\": "" }, From d65726b8e9864c248a0e79e84c819aa788f7af3a Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Sat, 21 May 2022 16:45:39 +0200 Subject: [PATCH 110/208] deprecate using date and time types with date objects with not-matching timezones --- CHANGELOG.md | 6 ++++ Extension/Core/Type/DateTimeType.php | 17 +++++++++ Extension/Core/Type/DateType.php | 17 +++++++++ Extension/Core/Type/TimeType.php | 15 ++++++++ .../Extension/Core/Type/DateTimeTypeTest.php | 36 +++++++++++++++++-- Tests/Extension/Core/Type/DateTypeTest.php | 34 +++++++++++++++++- Tests/Extension/Core/Type/TimeTypeTest.php | 32 +++++++++++++++++ 7 files changed, 154 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ff39c9726..22597f3b47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ CHANGELOG ========= +6.4 +--- + + * Deprecate using `DateTime` or `DateTimeImmutable` model data with a different timezone than configured with the + `model_timezone` option in `DateType`, `DateTimeType`, and `TimeType` + 6.3 --- diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index 32c58447cd..9ec4c9cca4 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -22,6 +22,8 @@ use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToTimestampTransformer; use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\Form\FormEvent; +use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; use Symfony\Component\Form\ReversedTransformer; @@ -194,6 +196,21 @@ public function buildForm(FormBuilderInterface $builder, array $options) new DateTimeToArrayTransformer($options['model_timezone'], $options['model_timezone'], $parts) )); } + + if (\in_array($options['input'], ['datetime', 'datetime_immutable'], true) && null !== $options['model_timezone']) { + $builder->addEventListener(FormEvents::POST_SET_DATA, static function (FormEvent $event) use ($options): void { + $date = $event->getData(); + + if (!$date instanceof \DateTimeInterface) { + return; + } + + if ($date->getTimezone()->getName() !== $options['model_timezone']) { + trigger_deprecation('symfony/form', '6.4', sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); + // throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); + } + }); + } } /** diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index 80023affcb..480afc315f 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -19,6 +19,8 @@ use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToTimestampTransformer; use Symfony\Component\Form\FormBuilderInterface; +use Symfony\Component\Form\FormEvent; +use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; use Symfony\Component\Form\ReversedTransformer; @@ -178,6 +180,21 @@ class_exists(\IntlTimeZone::class, false) ? \IntlTimeZone::createDefault() : nul new DateTimeToArrayTransformer($options['model_timezone'], $options['model_timezone'], ['year', 'month', 'day']) )); } + + if (\in_array($options['input'], ['datetime', 'datetime_immutable'], true) && null !== $options['model_timezone']) { + $builder->addEventListener(FormEvents::POST_SET_DATA, static function (FormEvent $event) use ($options): void { + $date = $event->getData(); + + if (!$date instanceof \DateTimeInterface) { + return; + } + + if ($date->getTimezone()->getName() !== $options['model_timezone']) { + trigger_deprecation('symfony/form', '6.4', sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); + // throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); + } + }); + } } /** diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index c7d5276960..623259f17a 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -208,6 +208,21 @@ public function buildForm(FormBuilderInterface $builder, array $options) new DateTimeToArrayTransformer($options['model_timezone'], $options['model_timezone'], $parts, 'text' === $options['widget'], $options['reference_date']) )); } + + if (\in_array($options['input'], ['datetime', 'datetime_immutable'], true) && null !== $options['model_timezone']) { + $builder->addEventListener(FormEvents::POST_SET_DATA, static function (FormEvent $event) use ($options): void { + $date = $event->getData(); + + if (!$date instanceof \DateTimeInterface) { + return; + } + + if ($date->getTimezone()->getName() !== $options['model_timezone']) { + trigger_deprecation('symfony/form', '6.4', sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); + // throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); + } + }); + } } /** diff --git a/Tests/Extension/Core/Type/DateTimeTypeTest.php b/Tests/Extension/Core/Type/DateTimeTypeTest.php index a2058596ee..71020a06b9 100644 --- a/Tests/Extension/Core/Type/DateTimeTypeTest.php +++ b/Tests/Extension/Core/Type/DateTimeTypeTest.php @@ -11,11 +11,14 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; class DateTimeTypeTest extends BaseTypeTestCase { + use ExpectDeprecationTrait; + public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\DateTimeType'; private $defaultLocale; @@ -154,7 +157,7 @@ public function testSubmitWithoutMinutes() 'with_minutes' => false, ]); - $form->setData(new \DateTime()); + $form->setData(new \DateTime('now', new \DateTimeZone('UTC'))); $input = [ 'date' => [ @@ -184,7 +187,7 @@ public function testSubmitWithSeconds() 'with_seconds' => true, ]); - $form->setData(new \DateTime()); + $form->setData(new \DateTime('now', new \DateTimeZone('UTC'))); $input = [ 'date' => [ @@ -748,6 +751,35 @@ public function testSubmitStringWithCustomInputFormat() $this->assertSame('14/01/2018 21:29:00 +00:00', $form->getData()); } + /** + * @group legacy + */ + public function testDateTimeInputTimezoneNotMatchingModelTimezone() + { + $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); + // $this->expectException(LogicException::class); + // $this->expectExceptionMessage('Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + + $this->factory->create(static::TESTED_TYPE, new \DateTime('now', new \DateTimeZone('UTC')), [ + 'model_timezone' => 'Europe/Berlin', + ]); + } + + /** + * @group legacy + */ + public function testDateTimeImmutableInputTimezoneNotMatchingModelTimezone() + { + $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); + // $this->expectException(LogicException::class); + // $this->expectExceptionMessage('Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + + $this->factory->create(static::TESTED_TYPE, new \DateTimeImmutable('now', new \DateTimeZone('UTC')), [ + 'input' => 'datetime_immutable', + 'model_timezone' => 'Europe/Berlin', + ]); + } + protected function getTestOptions(): array { return ['widget' => 'choice']; diff --git a/Tests/Extension/Core/Type/DateTypeTest.php b/Tests/Extension/Core/Type/DateTypeTest.php index abda1a6c07..bb171ffe88 100644 --- a/Tests/Extension/Core/Type/DateTypeTest.php +++ b/Tests/Extension/Core/Type/DateTypeTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; @@ -19,6 +20,8 @@ class DateTypeTest extends BaseTypeTestCase { + use ExpectDeprecationTrait; + public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\DateType'; private $defaultTimezone; @@ -654,7 +657,7 @@ public function testIsSynchronizedReturnsTrueIfChoiceAndCompletelyEmpty() public function testIsSynchronizedReturnsTrueIfChoiceAndCompletelyFilled() { - $form = $this->factory->create(static::TESTED_TYPE, new \DateTime(), [ + $form = $this->factory->create(static::TESTED_TYPE, new \DateTime('now', new \DateTimeZone('UTC')), [ 'model_timezone' => 'UTC', 'view_timezone' => 'UTC', 'widget' => 'choice', @@ -1112,6 +1115,35 @@ public function testSubmitStringWithCustomInputFormat() $this->assertSame('14/01/2018', $form->getData()); } + /** + * @group legacy + */ + public function testDateTimeInputTimezoneNotMatchingModelTimezone() + { + $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); + // $this->expectException(LogicException::class); + // $this->expectExceptionMessage('Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + + $this->factory->create(static::TESTED_TYPE, new \DateTime('now', new \DateTimeZone('UTC')), [ + 'model_timezone' => 'Europe/Berlin', + ]); + } + + /** + * @group legacy + */ + public function testDateTimeImmutableInputTimezoneNotMatchingModelTimezone() + { + $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); + // $this->expectException(LogicException::class); + // $this->expectExceptionMessage('Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + + $this->factory->create(static::TESTED_TYPE, new \DateTimeImmutable('now', new \DateTimeZone('UTC')), [ + 'input' => 'datetime_immutable', + 'model_timezone' => 'Europe/Berlin', + ]); + } + protected function getTestOptions(): array { return ['widget' => 'choice']; diff --git a/Tests/Extension/Core/Type/TimeTypeTest.php b/Tests/Extension/Core/Type/TimeTypeTest.php index 4ed930bbd5..3e8e42f4a8 100644 --- a/Tests/Extension/Core/Type/TimeTypeTest.php +++ b/Tests/Extension/Core/Type/TimeTypeTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\Exception\InvalidConfigurationException; use Symfony\Component\Form\Exception\LogicException; @@ -20,6 +21,8 @@ class TimeTypeTest extends BaseTypeTestCase { + use ExpectDeprecationTrait; + public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\TimeType'; public function testSubmitDateTime() @@ -1161,6 +1164,35 @@ public static function provideEmptyData() ]; } + /** + * @group legacy + */ + public function testDateTimeInputTimezoneNotMatchingModelTimezone() + { + $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); + // $this->expectException(LogicException::class); + // $this->expectExceptionMessage('Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + + $this->factory->create(static::TESTED_TYPE, new \DateTime('now', new \DateTimeZone('UTC')), [ + 'model_timezone' => 'Europe/Berlin', + ]); + } + + /** + * @group legacy + */ + public function testDateTimeImmutableInputTimezoneNotMatchingModelTimezone() + { + $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); + // $this->expectException(LogicException::class); + // $this->expectExceptionMessage('Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + + $this->factory->create(static::TESTED_TYPE, new \DateTimeImmutable('now', new \DateTimeZone('UTC')), [ + 'input' => 'datetime_immutable', + 'model_timezone' => 'Europe/Berlin', + ]); + } + protected function getTestOptions(): array { return ['widget' => 'choice']; From f7783d2df1bb01e4bd643959e623ca54c404ec12 Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Thu, 29 Jun 2023 12:39:19 +0200 Subject: [PATCH 111/208] Add missing return types and enforce return types on all methods --- Extension/DataCollector/FormDataCollector.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index ffce3ac137..0ac99e3729 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -242,7 +242,7 @@ protected function getCasters(): array ]; } - private function &recursiveBuildPreliminaryFormTree(FormInterface $form, array &$outputByHash) + private function &recursiveBuildPreliminaryFormTree(FormInterface $form, array &$outputByHash): array { $hash = spl_object_hash($form); @@ -259,7 +259,7 @@ private function &recursiveBuildPreliminaryFormTree(FormInterface $form, array & return $output; } - private function &recursiveBuildFinalFormTree(FormInterface $form = null, FormView $view, array &$outputByHash) + private function &recursiveBuildFinalFormTree(FormInterface $form = null, FormView $view, array &$outputByHash): array { $viewHash = spl_object_hash($view); $formHash = null; From cad698992652ebb93bd09bf547d4184ea2d751a8 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 30 Jun 2023 10:51:15 +0200 Subject: [PATCH 112/208] [7.0] Fix various `@psalm-return` annotations --- DataTransformerInterface.php | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/DataTransformerInterface.php b/DataTransformerInterface.php index 85fb99d218..aeab6f2c34 100644 --- a/DataTransformerInterface.php +++ b/DataTransformerInterface.php @@ -58,13 +58,11 @@ interface DataTransformerInterface * * @param TValue|null $value The value in the original representation * - * @return mixed - * - * @psalm-return TTransformedValue|null + * @return TTransformedValue|null * * @throws TransformationFailedException when the transformation fails */ - public function transform(mixed $value); + public function transform(mixed $value): mixed; /** * Transforms a value from the transformed representation to its original @@ -89,11 +87,9 @@ public function transform(mixed $value); * * @param TTransformedValue|null $value The value in the transformed representation * - * @return mixed - * - * @psalm-return TValue|null + * @return TValue|null * * @throws TransformationFailedException when the transformation fails */ - public function reverseTransform(mixed $value); + public function reverseTransform(mixed $value): mixed; } From adc36f72ad0b936481fc8bf7ae00de279a9cb92c Mon Sep 17 00:00:00 2001 From: Frank Fiebig Date: Tue, 4 Jul 2023 11:21:50 +0200 Subject: [PATCH 113/208] [Lock] 7.0 remove deprecations in Lock Component --- Extension/Validator/Constraints/Form.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Extension/Validator/Constraints/Form.php b/Extension/Validator/Constraints/Form.php index 6dec01be22..8be25c0b8b 100644 --- a/Extension/Validator/Constraints/Form.php +++ b/Extension/Validator/Constraints/Form.php @@ -26,11 +26,6 @@ class Form extends Constraint self::NO_SUCH_FIELD_ERROR => 'NO_SUCH_FIELD_ERROR', ]; - /** - * @deprecated since Symfony 6.1, use const ERROR_NAMES instead - */ - protected static $errorNames = self::ERROR_NAMES; - public function getTargets(): string|array { return self::CLASS_CONSTRAINT; From 376bbc54dd6509128b603c0cfb656ae925273df6 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 4 Jul 2023 14:50:59 +0200 Subject: [PATCH 114/208] [7.0] Remove remaining deprecated code paths --- Button.php | 5 +---- ButtonBuilder.php | 6 +----- CHANGELOG.md | 8 ++++++++ Exception/TransformationFailedException.php | 5 +---- Extension/Core/Type/DateTimeType.php | 6 ++---- Extension/Core/Type/DateType.php | 9 ++------- Extension/Core/Type/TimeType.php | 9 ++------- Form.php | 6 +----- FormConfigBuilder.php | 5 +---- .../Extension/Core/Type/DateTimeTypeTest.php | 20 +++++-------------- Tests/Extension/Core/Type/DateTypeTest.php | 20 +++++-------------- Tests/Extension/Core/Type/TimeTypeTest.php | 19 ++++-------------- composer.json | 1 - 13 files changed, 33 insertions(+), 86 deletions(-) diff --git a/Button.php b/Button.php index 00373b3770..67772ccfe1 100644 --- a/Button.php +++ b/Button.php @@ -81,11 +81,8 @@ public function offsetUnset(mixed $offset): void throw new BadMethodCallException('Buttons cannot have children.'); } - public function setParent(FormInterface $parent = null): static + public function setParent(?FormInterface $parent): static { - if (1 > \func_num_args()) { - trigger_deprecation('symfony/form', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__); - } if ($this->submitted) { throw new AlreadySubmittedException('You cannot set the parent of a submitted button.'); } diff --git a/ButtonBuilder.php b/ButtonBuilder.php index 20a30968d4..2c8c12ce23 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -220,12 +220,8 @@ public function setAttributes(array $attributes): static * * @throws BadMethodCallException */ - public function setDataMapper(DataMapperInterface $dataMapper = null): static + public function setDataMapper(?DataMapperInterface $dataMapper): static { - if (1 > \func_num_args()) { - trigger_deprecation('symfony/form', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__); - } - throw new BadMethodCallException('Buttons do not support data mappers.'); } diff --git a/CHANGELOG.md b/CHANGELOG.md index 22597f3b47..73c85c2271 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,14 @@ CHANGELOG ========= +7.0 +--- + + * Throw when using `DateTime` or `DateTimeImmutable` model data with a different timezone than configured with the + `model_timezone` option in `DateType`, `DateTimeType`, and `TimeType` + * Make the "widget" option of date/time form types default to "single_text" + * Require explicit argument when calling `Button/Form::setParent()`, `ButtonBuilder/FormConfigBuilder::setDataMapper()`, `TransformationFailedException::setInvalidMessage()` + 6.4 --- diff --git a/Exception/TransformationFailedException.php b/Exception/TransformationFailedException.php index 409b51517a..ceb01f1a9a 100644 --- a/Exception/TransformationFailedException.php +++ b/Exception/TransformationFailedException.php @@ -34,11 +34,8 @@ public function __construct(string $message = '', int $code = 0, \Throwable $pre * @param string|null $invalidMessage The message or message key * @param array $invalidMessageParameters Data to be passed into the translator */ - public function setInvalidMessage(string $invalidMessage = null, array $invalidMessageParameters = []): void + public function setInvalidMessage(?string $invalidMessage, array $invalidMessageParameters = []): void { - if (1 > \func_num_args()) { - trigger_deprecation('symfony/form', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__); - } $this->invalidMessage = $invalidMessage; $this->invalidMessageParameters = $invalidMessageParameters; } diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index 9ec4c9cca4..73ae5708c9 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -206,8 +206,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) } if ($date->getTimezone()->getName() !== $options['model_timezone']) { - trigger_deprecation('symfony/form', '6.4', sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); - // throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); + throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', get_debug_type($date), $date->getTimezone()->getName(), $options['model_timezone'])); } }); } @@ -335,8 +334,7 @@ public function configureOptions(OptionsResolver $resolver) throw new LogicException(sprintf('Cannot use the "time_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class)); } } elseif (null === $widget && null === $options['date_widget'] && null === $options['time_widget']) { - trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option of form type "datetime" is deprecated. It will default to "single_text" in Symfony 7.0.'); - // return 'single_text'; + return 'single_text'; } return $widget; diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index 480afc315f..d204a914bd 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -190,8 +190,7 @@ class_exists(\IntlTimeZone::class, false) ? \IntlTimeZone::createDefault() : nul } if ($date->getTimezone()->getName() !== $options['model_timezone']) { - trigger_deprecation('symfony/form', '6.4', sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); - // throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); + throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', get_debug_type($date), $date->getTimezone()->getName(), $options['model_timezone'])); } }); } @@ -286,11 +285,7 @@ public function configureOptions(OptionsResolver $resolver) 'years' => range((int) date('Y') - 5, (int) date('Y') + 5), 'months' => range(1, 12), 'days' => range(1, 31), - 'widget' => static function (Options $options) { - trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option of form type "date" is deprecated. It will default to "single_text" in Symfony 7.0.'); - - return 'choice'; - }, + 'widget' => 'single_text', 'input' => 'datetime', 'format' => $format, 'model_timezone' => null, diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 623259f17a..7788290d7a 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -218,8 +218,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) } if ($date->getTimezone()->getName() !== $options['model_timezone']) { - trigger_deprecation('symfony/form', '6.4', sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); - // throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', $date::class, $date->getTimezone()->getName(), $options['model_timezone'])); + throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', get_debug_type($date), $date->getTimezone()->getName(), $options['model_timezone'])); } }); } @@ -327,11 +326,7 @@ public function configureOptions(OptionsResolver $resolver) 'hours' => range(0, 23), 'minutes' => range(0, 59), 'seconds' => range(0, 59), - 'widget' => static function (Options $options) { - trigger_deprecation('symfony/form', '6.3', 'Not configuring the "widget" option of form type "time" is deprecated. It will default to "single_text" in Symfony 7.0.'); - - return 'choice'; - }, + 'widget' => 'single_text', 'input' => 'datetime', 'input_format' => 'H:i:s', 'with_minutes' => true, diff --git a/Form.php b/Form.php index a4b76506a2..5c86d27b56 100644 --- a/Form.php +++ b/Form.php @@ -218,12 +218,8 @@ public function isDisabled(): bool return true; } - public function setParent(FormInterface $parent = null): static + public function setParent(?FormInterface $parent): static { - if (1 > \func_num_args()) { - trigger_deprecation('symfony/form', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__); - } - if ($this->submitted) { throw new AlreadySubmittedException('You cannot set the parent of a submitted form.'); } diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 9fed3d1a0a..29e643680e 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -347,11 +347,8 @@ public function setAttributes(array $attributes): static /** * @return $this */ - public function setDataMapper(DataMapperInterface $dataMapper = null): static + public function setDataMapper(?DataMapperInterface $dataMapper): static { - if (1 > \func_num_args()) { - trigger_deprecation('symfony/form', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__); - } if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); } diff --git a/Tests/Extension/Core/Type/DateTimeTypeTest.php b/Tests/Extension/Core/Type/DateTimeTypeTest.php index 71020a06b9..eb6538e6a6 100644 --- a/Tests/Extension/Core/Type/DateTimeTypeTest.php +++ b/Tests/Extension/Core/Type/DateTimeTypeTest.php @@ -11,14 +11,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; +use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; class DateTimeTypeTest extends BaseTypeTestCase { - use ExpectDeprecationTrait; - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\DateTimeType'; private $defaultLocale; @@ -751,28 +749,20 @@ public function testSubmitStringWithCustomInputFormat() $this->assertSame('14/01/2018 21:29:00 +00:00', $form->getData()); } - /** - * @group legacy - */ public function testDateTimeInputTimezoneNotMatchingModelTimezone() { - $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); - // $this->expectException(LogicException::class); - // $this->expectExceptionMessage('Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); $this->factory->create(static::TESTED_TYPE, new \DateTime('now', new \DateTimeZone('UTC')), [ 'model_timezone' => 'Europe/Berlin', ]); } - /** - * @group legacy - */ public function testDateTimeImmutableInputTimezoneNotMatchingModelTimezone() { - $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); - // $this->expectException(LogicException::class); - // $this->expectExceptionMessage('Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); $this->factory->create(static::TESTED_TYPE, new \DateTimeImmutable('now', new \DateTimeZone('UTC')), [ 'input' => 'datetime_immutable', diff --git a/Tests/Extension/Core/Type/DateTypeTest.php b/Tests/Extension/Core/Type/DateTypeTest.php index bb171ffe88..976836553e 100644 --- a/Tests/Extension/Core/Type/DateTypeTest.php +++ b/Tests/Extension/Core/Type/DateTypeTest.php @@ -11,8 +11,8 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\ChoiceList\View\ChoiceView; +use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; use Symfony\Component\Intl\Util\IntlTestHelper; @@ -20,8 +20,6 @@ class DateTypeTest extends BaseTypeTestCase { - use ExpectDeprecationTrait; - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\DateType'; private $defaultTimezone; @@ -1115,28 +1113,20 @@ public function testSubmitStringWithCustomInputFormat() $this->assertSame('14/01/2018', $form->getData()); } - /** - * @group legacy - */ public function testDateTimeInputTimezoneNotMatchingModelTimezone() { - $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); - // $this->expectException(LogicException::class); - // $this->expectExceptionMessage('Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); $this->factory->create(static::TESTED_TYPE, new \DateTime('now', new \DateTimeZone('UTC')), [ 'model_timezone' => 'Europe/Berlin', ]); } - /** - * @group legacy - */ public function testDateTimeImmutableInputTimezoneNotMatchingModelTimezone() { - $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); - // $this->expectException(LogicException::class); - // $this->expectExceptionMessage('Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); $this->factory->create(static::TESTED_TYPE, new \DateTimeImmutable('now', new \DateTimeZone('UTC')), [ 'input' => 'datetime_immutable', diff --git a/Tests/Extension/Core/Type/TimeTypeTest.php b/Tests/Extension/Core/Type/TimeTypeTest.php index 3e8e42f4a8..155657038f 100644 --- a/Tests/Extension/Core/Type/TimeTypeTest.php +++ b/Tests/Extension/Core/Type/TimeTypeTest.php @@ -11,7 +11,6 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\Exception\InvalidConfigurationException; use Symfony\Component\Form\Exception\LogicException; @@ -21,8 +20,6 @@ class TimeTypeTest extends BaseTypeTestCase { - use ExpectDeprecationTrait; - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\TimeType'; public function testSubmitDateTime() @@ -1164,28 +1161,20 @@ public static function provideEmptyData() ]; } - /** - * @group legacy - */ public function testDateTimeInputTimezoneNotMatchingModelTimezone() { - $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); - // $this->expectException(LogicException::class); - // $this->expectExceptionMessage('Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Using a "DateTime" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); $this->factory->create(static::TESTED_TYPE, new \DateTime('now', new \DateTimeZone('UTC')), [ 'model_timezone' => 'Europe/Berlin', ]); } - /** - * @group legacy - */ public function testDateTimeImmutableInputTimezoneNotMatchingModelTimezone() { - $this->expectDeprecation('Since symfony/form 6.4: Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is deprecated.'); - // $this->expectException(LogicException::class); - // $this->expectExceptionMessage('Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Using a "DateTimeImmutable" instance with a timezone ("UTC") not matching the configured model timezone "Europe/Berlin" is not supported.'); $this->factory->create(static::TESTED_TYPE, new \DateTimeImmutable('now', new \DateTimeZone('UTC')), [ 'input' => 'datetime_immutable', diff --git a/composer.json b/composer.json index 7ee167817f..914ddc6c52 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,6 @@ ], "require": { "php": ">=8.2", - "symfony/deprecation-contracts": "^2.5|^3", "symfony/event-dispatcher": "^6.4|^7.0", "symfony/options-resolver": "^6.4|^7.0", "symfony/polyfill-ctype": "~1.8", From 6e27fa46f87e13f4bbcc56344e1b8a78c53c6fa9 Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Sat, 1 Jul 2023 14:03:11 +0200 Subject: [PATCH 115/208] Add missing return types to magic methods --- Util/OrderedHashMapIterator.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Util/OrderedHashMapIterator.php b/Util/OrderedHashMapIterator.php index e1335fefa6..828218a452 100644 --- a/Util/OrderedHashMapIterator.php +++ b/Util/OrderedHashMapIterator.php @@ -62,6 +62,9 @@ public function __sleep(): array throw new \BadMethodCallException('Cannot serialize '.__CLASS__); } + /** + * @return void + */ public function __wakeup() { throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); From 8266c81fcef3584b6aa041c464b95ebfc9a20b32 Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Sun, 2 Jul 2023 23:52:21 +0200 Subject: [PATCH 116/208] [Components] Convert to native return types --- AbstractExtension.php | 6 +- AbstractRendererEngine.php | 9 +- AbstractType.php | 30 +--- AbstractTypeExtension.php | 20 +-- ButtonBuilder.php | 129 +++++------------- .../Factory/CachingFactoryDecorator.php | 5 +- Command/DebugCommand.php | 5 +- DataMapperInterface.php | 8 +- DependencyInjection/FormPass.php | 5 +- .../Core/DataMapper/CheckboxListMapper.php | 10 +- Extension/Core/DataMapper/RadioListMapper.php | 10 +- .../EventListener/FixUrlProtocolListener.php | 5 +- .../EventListener/MergeCollectionListener.php | 5 +- .../Core/EventListener/ResizeFormListener.php | 15 +- .../TransformationFailureListener.php | 5 +- Extension/Core/EventListener/TrimListener.php | 5 +- Extension/Core/Type/BaseType.php | 15 +- Extension/Core/Type/BirthdayType.php | 5 +- Extension/Core/Type/ButtonType.php | 5 +- Extension/Core/Type/CheckboxType.php | 15 +- Extension/Core/Type/ChoiceType.php | 20 +-- Extension/Core/Type/CollectionType.php | 20 +-- Extension/Core/Type/ColorType.php | 10 +- Extension/Core/Type/CountryType.php | 5 +- Extension/Core/Type/CurrencyType.php | 5 +- Extension/Core/Type/DateIntervalType.php | 15 +- Extension/Core/Type/DateTimeType.php | 15 +- Extension/Core/Type/DateType.php | 15 +- Extension/Core/Type/EmailType.php | 5 +- Extension/Core/Type/FileType.php | 20 +-- Extension/Core/Type/FormType.php | 20 +-- Extension/Core/Type/HiddenType.php | 5 +- Extension/Core/Type/IntegerType.php | 15 +- Extension/Core/Type/LanguageType.php | 5 +- Extension/Core/Type/LocaleType.php | 5 +- Extension/Core/Type/MoneyType.php | 19 +-- Extension/Core/Type/NumberType.php | 15 +- Extension/Core/Type/PasswordType.php | 10 +- Extension/Core/Type/PercentType.php | 15 +- Extension/Core/Type/RadioType.php | 5 +- Extension/Core/Type/RangeType.php | 5 +- Extension/Core/Type/RepeatedType.php | 10 +- Extension/Core/Type/SearchType.php | 5 +- Extension/Core/Type/SubmitType.php | 10 +- Extension/Core/Type/TelType.php | 5 +- Extension/Core/Type/TextType.php | 10 +- Extension/Core/Type/TextareaType.php | 5 +- Extension/Core/Type/TimeType.php | 15 +- Extension/Core/Type/TimezoneType.php | 10 +- .../Type/TransformationFailureExtension.php | 5 +- Extension/Core/Type/UlidType.php | 10 +- Extension/Core/Type/UrlType.php | 15 +- Extension/Core/Type/UuidType.php | 10 +- Extension/Core/Type/WeekType.php | 15 +- .../EventListener/CsrfValidationListener.php | 5 +- Extension/Csrf/Type/FormTypeCsrfExtension.php | 13 +- .../EventListener/DataCollectorListener.php | 8 +- .../FormDataCollectorInterface.php | 28 +--- .../Proxy/ResolvedTypeDataCollectorProxy.php | 15 +- .../Type/DataCollectorTypeExtension.php | 5 +- .../Type/TextTypeHtmlSanitizerExtension.php | 10 +- .../HttpFoundationRequestHandler.php | 5 +- .../Type/FormTypeHttpFoundationExtension.php | 5 +- .../EventListener/PasswordHasherListener.php | 10 +- .../Type/FormTypePasswordHasherExtension.php | 5 +- .../PasswordTypePasswordHasherExtension.php | 10 +- .../Validator/Constraints/FormValidator.php | 5 +- .../EventListener/ValidationListener.php | 5 +- .../Validator/Type/BaseValidatorExtension.php | 5 +- .../Type/FormTypeValidatorExtension.php | 10 +- .../Type/RepeatedTypeValidatorExtension.php | 5 +- .../Type/UploadValidatorExtension.php | 5 +- .../ViolationMapper/ViolationMapper.php | 5 +- .../ViolationMapperInterface.php | 4 +- .../ViolationMapper/ViolationPathIterator.php | 5 +- FormBuilderInterface.php | 2 +- FormConfigBuilder.php | 2 +- FormConfigBuilderInterface.php | 2 +- FormError.php | 4 +- FormEvent.php | 4 +- FormRenderer.php | 5 +- FormRendererEngineInterface.php | 8 +- FormRendererInterface.php | 4 +- FormTypeExtensionInterface.php | 17 +-- FormTypeGuesserInterface.php | 16 +-- FormTypeInterface.php | 24 +--- FormView.php | 5 +- NativeRequestHandler.php | 4 +- RequestHandlerInterface.php | 4 +- ResolvedFormType.php | 15 +- ResolvedFormTypeInterface.php | 12 +- Util/OrderedHashMapIterator.php | 5 +- 92 files changed, 214 insertions(+), 773 deletions(-) diff --git a/AbstractExtension.php b/AbstractExtension.php index cffca7d398..908f4f86ff 100644 --- a/AbstractExtension.php +++ b/AbstractExtension.php @@ -98,7 +98,7 @@ public function getTypeGuesser(): ?FormTypeGuesserInterface * * @return FormTypeInterface[] */ - protected function loadTypes() + protected function loadTypes(): array { return []; } @@ -115,10 +115,8 @@ protected function loadTypeExtensions(): array /** * Registers the type guesser. - * - * @return FormTypeGuesserInterface|null */ - protected function loadTypeGuesser() + protected function loadTypeGuesser(): ?FormTypeGuesserInterface { return null; } diff --git a/AbstractRendererEngine.php b/AbstractRendererEngine.php index 3f1ab79c26..cd7215025a 100644 --- a/AbstractRendererEngine.php +++ b/AbstractRendererEngine.php @@ -61,10 +61,7 @@ public function __construct(array $defaultThemes = []) $this->defaultThemes = $defaultThemes; } - /** - * @return void - */ - public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true) + public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true): void { $cacheKey = $view->vars[self::CACHE_KEY_VAR]; @@ -124,10 +121,8 @@ public function getResourceHierarchyLevel(FormView $view, array $blockNameHierar * Loads the cache with the resource for a given block name. * * @see getResourceForBlock() - * - * @return bool */ - abstract protected function loadResourceForBlockName(string $cacheKey, FormView $view, string $blockName); + abstract protected function loadResourceForBlockName(string $cacheKey, FormView $view, string $blockName): bool; /** * Loads the cache with the resource for a specific level of a block hierarchy. diff --git a/AbstractType.php b/AbstractType.php index ad4b195696..269d541a0f 100644 --- a/AbstractType.php +++ b/AbstractType.php @@ -20,46 +20,28 @@ */ abstract class AbstractType implements FormTypeInterface { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { } - /** - * @return void - */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function finishView(FormView $view, FormInterface $form, array $options): void { } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { } - /** - * @return string - */ - public function getBlockPrefix() + public function getBlockPrefix(): string { return StringUtil::fqcnToBlockPrefix(static::class) ?: ''; } - /** - * @return string|null - */ - public function getParent() + public function getParent(): ?string { return FormType::class; } diff --git a/AbstractTypeExtension.php b/AbstractTypeExtension.php index 422f28bf33..1c1c4fc7c6 100644 --- a/AbstractTypeExtension.php +++ b/AbstractTypeExtension.php @@ -18,31 +18,19 @@ */ abstract class AbstractTypeExtension implements FormTypeExtensionInterface { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { } - /** - * @return void - */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function finishView(FormView $view, FormInterface $form, array $options): void { } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { } } diff --git a/ButtonBuilder.php b/ButtonBuilder.php index 2c8c12ce23..f9a6142dbf 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -11,7 +11,6 @@ namespace Symfony\Component\Form; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Form\Exception\BadMethodCallException; use Symfony\Component\Form\Exception\InvalidArgumentException; @@ -52,11 +51,9 @@ public function __construct(?string $name, array $options = []) /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function add(string|FormBuilderInterface $child, string $type = null, array $options = []): static + public function add(string|FormBuilderInterface $child, string $type = null, array $options = []): never { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -64,11 +61,9 @@ public function add(string|FormBuilderInterface $child, string $type = null, arr /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function create(string $name, string $type = null, array $options = []): FormBuilderInterface + public function create(string $name, string $type = null, array $options = []): never { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -76,11 +71,9 @@ public function create(string $name, string $type = null, array $options = []): /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function get(string $name): FormBuilderInterface + public function get(string $name): never { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -88,11 +81,9 @@ public function get(string $name): FormBuilderInterface /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function remove(string $name): static + public function remove(string $name): never { throw new BadMethodCallException('Buttons cannot have children.'); } @@ -124,11 +115,9 @@ public function getForm(): Button /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function addEventListener(string $eventName, callable $listener, int $priority = 0): static + public function addEventListener(string $eventName, callable $listener, int $priority = 0): never { throw new BadMethodCallException('Buttons do not support event listeners.'); } @@ -136,11 +125,9 @@ public function addEventListener(string $eventName, callable $listener, int $pri /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function addEventSubscriber(EventSubscriberInterface $subscriber): static + public function addEventSubscriber(EventSubscriberInterface $subscriber): never { throw new BadMethodCallException('Buttons do not support event subscribers.'); } @@ -148,11 +135,9 @@ public function addEventSubscriber(EventSubscriberInterface $subscriber): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false): static + public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false): never { throw new BadMethodCallException('Buttons do not support data transformers.'); } @@ -160,11 +145,9 @@ public function addViewTransformer(DataTransformerInterface $viewTransformer, bo /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function resetViewTransformers(): static + public function resetViewTransformers(): never { throw new BadMethodCallException('Buttons do not support data transformers.'); } @@ -172,11 +155,9 @@ public function resetViewTransformers(): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function addModelTransformer(DataTransformerInterface $modelTransformer, bool $forceAppend = false): static + public function addModelTransformer(DataTransformerInterface $modelTransformer, bool $forceAppend = false): never { throw new BadMethodCallException('Buttons do not support data transformers.'); } @@ -184,11 +165,9 @@ public function addModelTransformer(DataTransformerInterface $modelTransformer, /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function resetModelTransformers(): static + public function resetModelTransformers(): never { throw new BadMethodCallException('Buttons do not support data transformers.'); } @@ -216,11 +195,9 @@ public function setAttributes(array $attributes): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setDataMapper(?DataMapperInterface $dataMapper): static + public function setDataMapper(?DataMapperInterface $dataMapper): never { throw new BadMethodCallException('Buttons do not support data mappers.'); } @@ -240,11 +217,9 @@ public function setDisabled(bool $disabled): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setEmptyData(mixed $emptyData): static + public function setEmptyData(mixed $emptyData): never { throw new BadMethodCallException('Buttons do not support empty data.'); } @@ -252,11 +227,9 @@ public function setEmptyData(mixed $emptyData): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setErrorBubbling(bool $errorBubbling): static + public function setErrorBubbling(bool $errorBubbling): never { throw new BadMethodCallException('Buttons do not support error bubbling.'); } @@ -264,11 +237,9 @@ public function setErrorBubbling(bool $errorBubbling): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setRequired(bool $required): static + public function setRequired(bool $required): never { throw new BadMethodCallException('Buttons cannot be required.'); } @@ -276,11 +247,9 @@ public function setRequired(bool $required): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setPropertyPath(string|PropertyPathInterface|null $propertyPath): static + public function setPropertyPath(string|PropertyPathInterface|null $propertyPath): never { throw new BadMethodCallException('Buttons do not support property paths.'); } @@ -288,11 +257,9 @@ public function setPropertyPath(string|PropertyPathInterface|null $propertyPath) /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setMapped(bool $mapped): static + public function setMapped(bool $mapped): never { throw new BadMethodCallException('Buttons do not support data mapping.'); } @@ -300,11 +267,9 @@ public function setMapped(bool $mapped): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setByReference(bool $byReference): static + public function setByReference(bool $byReference): never { throw new BadMethodCallException('Buttons do not support data mapping.'); } @@ -312,11 +277,9 @@ public function setByReference(bool $byReference): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setCompound(bool $compound): static + public function setCompound(bool $compound): never { throw new BadMethodCallException('Buttons cannot be compound.'); } @@ -336,11 +299,9 @@ public function setType(ResolvedFormTypeInterface $type): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setData(mixed $data): static + public function setData(mixed $data): never { throw new BadMethodCallException('Buttons do not support data.'); } @@ -348,11 +309,9 @@ public function setData(mixed $data): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setDataLocked(bool $locked): static + public function setDataLocked(bool $locked): never { throw new BadMethodCallException('Buttons do not support data locking.'); } @@ -360,11 +319,9 @@ public function setDataLocked(bool $locked): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setFormFactory(FormFactoryInterface $formFactory) + public function setFormFactory(FormFactoryInterface $formFactory): never { throw new BadMethodCallException('Buttons do not support form factories.'); } @@ -372,11 +329,9 @@ public function setFormFactory(FormFactoryInterface $formFactory) /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setAction(string $action): static + public function setAction(string $action): never { throw new BadMethodCallException('Buttons do not support actions.'); } @@ -384,11 +339,9 @@ public function setAction(string $action): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setMethod(string $method): static + public function setMethod(string $method): never { throw new BadMethodCallException('Buttons do not support methods.'); } @@ -396,11 +349,9 @@ public function setMethod(string $method): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setRequestHandler(RequestHandlerInterface $requestHandler): static + public function setRequestHandler(RequestHandlerInterface $requestHandler): never { throw new BadMethodCallException('Buttons do not support request handlers.'); } @@ -424,11 +375,9 @@ public function setAutoInitialize(bool $initialize): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setInheritData(bool $inheritData): static + public function setInheritData(bool $inheritData): never { throw new BadMethodCallException('Buttons do not support data inheritance.'); } @@ -448,11 +397,9 @@ public function getFormConfig(): FormConfigInterface /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function setIsEmptyCallback(?callable $isEmptyCallback): static + public function setIsEmptyCallback(?callable $isEmptyCallback): never { throw new BadMethodCallException('Buttons do not support "is empty" callback.'); } @@ -460,11 +407,9 @@ public function setIsEmptyCallback(?callable $isEmptyCallback): static /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function getEventDispatcher(): EventDispatcherInterface + public function getEventDispatcher(): never { throw new BadMethodCallException('Buttons do not support event dispatching.'); } @@ -620,10 +565,8 @@ public function getDataLocked(): bool /** * Unsupported method. - * - * @return never */ - public function getFormFactory(): FormFactoryInterface + public function getFormFactory(): never { throw new BadMethodCallException('Buttons do not support adding children.'); } @@ -631,11 +574,9 @@ public function getFormFactory(): FormFactoryInterface /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function getAction(): string + public function getAction(): never { throw new BadMethodCallException('Buttons do not support actions.'); } @@ -643,11 +584,9 @@ public function getAction(): string /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function getMethod(): string + public function getMethod(): never { throw new BadMethodCallException('Buttons do not support methods.'); } @@ -655,11 +594,9 @@ public function getMethod(): string /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function getRequestHandler(): RequestHandlerInterface + public function getRequestHandler(): never { throw new BadMethodCallException('Buttons do not support request handlers.'); } @@ -707,11 +644,9 @@ public function getOption(string $name, mixed $default = null): mixed /** * Unsupported method. * - * @return never - * * @throws BadMethodCallException */ - public function getIsEmptyCallback(): ?callable + public function getIsEmptyCallback(): never { throw new BadMethodCallException('Buttons do not support "is empty" callback.'); } diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index 40c0604ea4..1e943ab319 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -214,10 +214,7 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = return $this->views[$hash]; } - /** - * @return void - */ - public function reset() + public function reset(): void { $this->lists = []; $this->views = []; diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index 4a142e2965..884186b715 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -54,10 +54,7 @@ public function __construct(FormRegistryInterface $formRegistry, array $namespac $this->fileLinkFormatter = $fileLinkFormatter; } - /** - * @return void - */ - protected function configure() + protected function configure(): void { $this ->setDefinition([ diff --git a/DataMapperInterface.php b/DataMapperInterface.php index f04137aec6..b8ca86bfe0 100644 --- a/DataMapperInterface.php +++ b/DataMapperInterface.php @@ -25,11 +25,9 @@ interface DataMapperInterface * @param mixed $viewData View data of the compound form being initialized * @param \Traversable $forms A list of {@link FormInterface} instances * - * @return void - * * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported */ - public function mapDataToForms(mixed $viewData, \Traversable $forms); + public function mapDataToForms(mixed $viewData, \Traversable $forms): void; /** * Maps the model data of a list of children forms into the view data of their parent. @@ -58,9 +56,7 @@ public function mapDataToForms(mixed $viewData, \Traversable $forms); * @param mixed &$viewData The compound form's view data that get mapped * its children model data * - * @return void - * * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported */ - public function mapFormsToData(\Traversable $forms, mixed &$viewData); + public function mapFormsToData(\Traversable $forms, mixed &$viewData): void; } diff --git a/DependencyInjection/FormPass.php b/DependencyInjection/FormPass.php index efb6d5c8bb..4087311631 100644 --- a/DependencyInjection/FormPass.php +++ b/DependencyInjection/FormPass.php @@ -30,10 +30,7 @@ class FormPass implements CompilerPassInterface { use PriorityTaggedServiceTrait; - /** - * @return void - */ - public function process(ContainerBuilder $container) + public function process(ContainerBuilder $container): void { if (!$container->hasDefinition('form.extension')) { return; diff --git a/Extension/Core/DataMapper/CheckboxListMapper.php b/Extension/Core/DataMapper/CheckboxListMapper.php index 119c81107d..eff6d166b3 100644 --- a/Extension/Core/DataMapper/CheckboxListMapper.php +++ b/Extension/Core/DataMapper/CheckboxListMapper.php @@ -25,10 +25,7 @@ */ class CheckboxListMapper implements DataMapperInterface { - /** - * @return void - */ - public function mapDataToForms(mixed $choices, \Traversable $checkboxes) + public function mapDataToForms(mixed $choices, \Traversable $checkboxes): void { if (!\is_array($choices ??= [])) { throw new UnexpectedTypeException($choices, 'array'); @@ -40,10 +37,7 @@ public function mapDataToForms(mixed $choices, \Traversable $checkboxes) } } - /** - * @return void - */ - public function mapFormsToData(\Traversable $checkboxes, mixed &$choices) + public function mapFormsToData(\Traversable $checkboxes, mixed &$choices): void { if (!\is_array($choices)) { throw new UnexpectedTypeException($choices, 'array'); diff --git a/Extension/Core/DataMapper/RadioListMapper.php b/Extension/Core/DataMapper/RadioListMapper.php index 37fdba0c35..5313473cb9 100644 --- a/Extension/Core/DataMapper/RadioListMapper.php +++ b/Extension/Core/DataMapper/RadioListMapper.php @@ -25,10 +25,7 @@ */ class RadioListMapper implements DataMapperInterface { - /** - * @return void - */ - public function mapDataToForms(mixed $choice, \Traversable $radios) + public function mapDataToForms(mixed $choice, \Traversable $radios): void { if (!\is_string($choice)) { throw new UnexpectedTypeException($choice, 'string'); @@ -40,10 +37,7 @@ public function mapDataToForms(mixed $choice, \Traversable $radios) } } - /** - * @return void - */ - public function mapFormsToData(\Traversable $radios, mixed &$choice) + public function mapFormsToData(\Traversable $radios, mixed &$choice): void { if (null !== $choice && !\is_string($choice)) { throw new UnexpectedTypeException($choice, 'null or string'); diff --git a/Extension/Core/EventListener/FixUrlProtocolListener.php b/Extension/Core/EventListener/FixUrlProtocolListener.php index 7189977549..d648d6f508 100644 --- a/Extension/Core/EventListener/FixUrlProtocolListener.php +++ b/Extension/Core/EventListener/FixUrlProtocolListener.php @@ -32,10 +32,7 @@ public function __construct(?string $defaultProtocol = 'http') $this->defaultProtocol = $defaultProtocol; } - /** - * @return void - */ - public function onSubmit(FormEvent $event) + public function onSubmit(FormEvent $event): void { $data = $event->getData(); diff --git a/Extension/Core/EventListener/MergeCollectionListener.php b/Extension/Core/EventListener/MergeCollectionListener.php index 62cd0a42a7..23ee47bd2f 100644 --- a/Extension/Core/EventListener/MergeCollectionListener.php +++ b/Extension/Core/EventListener/MergeCollectionListener.php @@ -41,10 +41,7 @@ public static function getSubscribedEvents(): array ]; } - /** - * @return void - */ - public function onSubmit(FormEvent $event) + public function onSubmit(FormEvent $event): void { $dataToMergeInto = $event->getForm()->getNormData(); $data = $event->getData() ?? []; diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index cec439754e..f5901f1ed9 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -52,10 +52,7 @@ public static function getSubscribedEvents(): array ]; } - /** - * @return void - */ - public function preSetData(FormEvent $event) + public function preSetData(FormEvent $event): void { $form = $event->getForm(); $data = $event->getData() ?? []; @@ -77,10 +74,7 @@ public function preSetData(FormEvent $event) } } - /** - * @return void - */ - public function preSubmit(FormEvent $event) + public function preSubmit(FormEvent $event): void { $form = $event->getForm(); $data = $event->getData(); @@ -110,10 +104,7 @@ public function preSubmit(FormEvent $event) } } - /** - * @return void - */ - public function onSubmit(FormEvent $event) + public function onSubmit(FormEvent $event): void { $form = $event->getForm(); $data = $event->getData() ?? []; diff --git a/Extension/Core/EventListener/TransformationFailureListener.php b/Extension/Core/EventListener/TransformationFailureListener.php index c9c216b59f..570a285aae 100644 --- a/Extension/Core/EventListener/TransformationFailureListener.php +++ b/Extension/Core/EventListener/TransformationFailureListener.php @@ -36,10 +36,7 @@ public static function getSubscribedEvents(): array ]; } - /** - * @return void - */ - public function convertTransformationFailureToFormError(FormEvent $event) + public function convertTransformationFailureToFormError(FormEvent $event): void { $form = $event->getForm(); diff --git a/Extension/Core/EventListener/TrimListener.php b/Extension/Core/EventListener/TrimListener.php index 81a55f3cb0..11151d3999 100644 --- a/Extension/Core/EventListener/TrimListener.php +++ b/Extension/Core/EventListener/TrimListener.php @@ -23,10 +23,7 @@ */ class TrimListener implements EventSubscriberInterface { - /** - * @return void - */ - public function preSubmit(FormEvent $event) + public function preSubmit(FormEvent $event): void { $data = $event->getData(); diff --git a/Extension/Core/Type/BaseType.php b/Extension/Core/Type/BaseType.php index 5e2ae22481..68190c742f 100644 --- a/Extension/Core/Type/BaseType.php +++ b/Extension/Core/Type/BaseType.php @@ -29,19 +29,13 @@ */ abstract class BaseType extends AbstractType { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->setDisabled($options['disabled']); $builder->setAutoInitialize($options['auto_initialize']); } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $name = $form->getName(); $blockName = $options['block_name'] ?: $form->getName(); @@ -125,10 +119,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'block_name' => null, diff --git a/Extension/Core/Type/BirthdayType.php b/Extension/Core/Type/BirthdayType.php index fa60d016eb..651b880d86 100644 --- a/Extension/Core/Type/BirthdayType.php +++ b/Extension/Core/Type/BirthdayType.php @@ -16,10 +16,7 @@ class BirthdayType extends AbstractType { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'years' => range((int) date('Y') - 120, date('Y')), diff --git a/Extension/Core/Type/ButtonType.php b/Extension/Core/Type/ButtonType.php index d710546407..0ac0585797 100644 --- a/Extension/Core/Type/ButtonType.php +++ b/Extension/Core/Type/ButtonType.php @@ -31,10 +31,7 @@ public function getBlockPrefix(): string return 'button'; } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); diff --git a/Extension/Core/Type/CheckboxType.php b/Extension/Core/Type/CheckboxType.php index 291ede93ef..2f21279cad 100644 --- a/Extension/Core/Type/CheckboxType.php +++ b/Extension/Core/Type/CheckboxType.php @@ -20,10 +20,7 @@ class CheckboxType extends AbstractType { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { // Unlike in other types, where the data is NULL by default, it // needs to be a Boolean here. setData(null) is not acceptable @@ -35,10 +32,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) $builder->addViewTransformer(new BooleanToStringTransformer($options['value'], $options['false_values'])); } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $view->vars = array_replace($view->vars, [ 'value' => $options['value'], @@ -46,10 +40,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $emptyData = static fn (FormInterface $form, $viewData) => $viewData; diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 4dcd3b6877..00cb316cce 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -62,10 +62,7 @@ public function __construct(ChoiceListFactoryInterface $choiceListFactory = null $this->translator = $translator; } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $unknownValues = []; $choiceList = $this->createChoiceList($options); @@ -218,10 +215,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) }, 256); } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $choiceTranslationDomain = $options['choice_translation_domain']; if ($view->parent && null === $choiceTranslationDomain) { @@ -275,10 +269,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function finishView(FormView $view, FormInterface $form, array $options): void { if ($options['expanded']) { // Radio buttons should have the same name as the parent @@ -295,10 +286,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $emptyData = static function (Options $options) { if ($options['expanded'] && !$options['multiple']) { diff --git a/Extension/Core/Type/CollectionType.php b/Extension/Core/Type/CollectionType.php index 0216e61dd5..c9d3ec5b7c 100644 --- a/Extension/Core/Type/CollectionType.php +++ b/Extension/Core/Type/CollectionType.php @@ -21,10 +21,7 @@ class CollectionType extends AbstractType { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $resizePrototypeOptions = null; if ($options['allow_add'] && $options['prototype']) { @@ -54,10 +51,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) $builder->addEventSubscriber($resizeListener); } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $view->vars = array_replace($view->vars, [ 'allow_add' => $options['allow_add'], @@ -70,10 +64,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function finishView(FormView $view, FormInterface $form, array $options): void { $prefixOffset = -2; // check if the entry type also defines a block prefix @@ -104,10 +95,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $entryOptionsNormalizer = static function (Options $options, $value) { $value['block_name'] = 'entry'; diff --git a/Extension/Core/Type/ColorType.php b/Extension/Core/Type/ColorType.php index 31538fc3c7..476050fbee 100644 --- a/Extension/Core/Type/ColorType.php +++ b/Extension/Core/Type/ColorType.php @@ -33,10 +33,7 @@ public function __construct(TranslatorInterface $translator = null) $this->translator = $translator; } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if (!$options['html5']) { return; @@ -63,10 +60,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) }); } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'html5' => false, diff --git a/Extension/Core/Type/CountryType.php b/Extension/Core/Type/CountryType.php index 6f872660a0..adef745c54 100644 --- a/Extension/Core/Type/CountryType.php +++ b/Extension/Core/Type/CountryType.php @@ -22,10 +22,7 @@ class CountryType extends AbstractType { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'choice_loader' => function (Options $options) { diff --git a/Extension/Core/Type/CurrencyType.php b/Extension/Core/Type/CurrencyType.php index 89edc6f630..3581a77d9b 100644 --- a/Extension/Core/Type/CurrencyType.php +++ b/Extension/Core/Type/CurrencyType.php @@ -22,10 +22,7 @@ class CurrencyType extends AbstractType { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'choice_loader' => function (Options $options) { diff --git a/Extension/Core/Type/DateIntervalType.php b/Extension/Core/Type/DateIntervalType.php index 655ef6682f..e7ebb3d45a 100644 --- a/Extension/Core/Type/DateIntervalType.php +++ b/Extension/Core/Type/DateIntervalType.php @@ -43,10 +43,7 @@ class DateIntervalType extends AbstractType 'choice' => ChoiceType::class, ]; - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if (!$options['with_years'] && !$options['with_months'] && !$options['with_weeks'] && !$options['with_days'] && !$options['with_hours'] && !$options['with_minutes'] && !$options['with_seconds']) { throw new InvalidConfigurationException('You must enable at least one interval field.'); @@ -148,10 +145,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $vars = [ 'widget' => $options['widget'], @@ -163,10 +157,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) $view->vars = array_replace($view->vars, $vars); } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $compound = static fn (Options $options) => 'single_text' !== $options['widget']; $emptyData = static fn (Options $options) => 'single_text' === $options['widget'] ? '' : []; diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index 73ae5708c9..1c67eeb159 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -49,10 +49,7 @@ class DateTimeType extends AbstractType \IntlDateFormatter::SHORT, ]; - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $parts = ['year', 'month', 'day', 'hour']; $dateParts = ['year', 'month', 'day']; @@ -212,10 +209,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $view->vars['widget'] = $options['widget']; @@ -240,10 +234,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $compound = static fn (Options $options) => 'single_text' !== $options['widget']; diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index d204a914bd..cfbbaf4c0d 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -45,10 +45,7 @@ class DateType extends AbstractType 'choice' => ChoiceType::class, ]; - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $dateFormat = \is_int($options['format']) ? $options['format'] : self::DEFAULT_FORMAT; $timeFormat = \IntlDateFormatter::NONE; @@ -196,10 +193,7 @@ class_exists(\IntlTimeZone::class, false) ? \IntlTimeZone::createDefault() : nul } } - /** - * @return void - */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function finishView(FormView $view, FormInterface $form, array $options): void { $view->vars['widget'] = $options['widget']; @@ -236,10 +230,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $compound = static fn (Options $options) => 'single_text' !== $options['widget']; diff --git a/Extension/Core/Type/EmailType.php b/Extension/Core/Type/EmailType.php index 64d01ee67a..99a5689afc 100644 --- a/Extension/Core/Type/EmailType.php +++ b/Extension/Core/Type/EmailType.php @@ -16,10 +16,7 @@ class EmailType extends AbstractType { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'invalid_message' => 'Please enter a valid email address.', diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index cf8e1a7439..4e52e19cfc 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -41,10 +41,7 @@ public function __construct(TranslatorInterface $translator = null) $this->translator = $translator; } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { // Ensure that submitted data is always an uploaded file or an array of some $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($options) { @@ -85,10 +82,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) }); } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { if ($options['multiple']) { $view->vars['full_name'] .= '[]'; @@ -101,18 +95,12 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } - /** - * @return void - */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function finishView(FormView $view, FormInterface $form, array $options): void { $view->vars['multipart'] = true; } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $dataClass = null; if (class_exists(File::class)) { diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index 82aa77f0a3..042bcd19a7 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -38,10 +38,7 @@ public function __construct(PropertyAccessorInterface $propertyAccessor = null) ])); } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { parent::buildForm($builder, $options); @@ -69,10 +66,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) $builder->setIsEmptyCallback($options['is_empty_callback']); } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { parent::buildView($view, $form, $options); @@ -111,10 +105,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) ]); } - /** - * @return void - */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function finishView(FormView $view, FormInterface $form, array $options): void { $multipart = false; @@ -128,10 +119,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) $view->vars['multipart'] = $multipart; } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); diff --git a/Extension/Core/Type/HiddenType.php b/Extension/Core/Type/HiddenType.php index c4e5eb2ccf..73449a3635 100644 --- a/Extension/Core/Type/HiddenType.php +++ b/Extension/Core/Type/HiddenType.php @@ -16,10 +16,7 @@ class HiddenType extends AbstractType { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ // hidden fields cannot have a required attribute diff --git a/Extension/Core/Type/IntegerType.php b/Extension/Core/Type/IntegerType.php index a287b66b7c..365c8a84b0 100644 --- a/Extension/Core/Type/IntegerType.php +++ b/Extension/Core/Type/IntegerType.php @@ -20,28 +20,19 @@ class IntegerType extends AbstractType { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addViewTransformer(new IntegerToLocalizedStringTransformer($options['grouping'], $options['rounding_mode'], !$options['grouping'] ? 'en' : null)); } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { if ($options['grouping']) { $view->vars['type'] = 'text'; } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'grouping' => false, diff --git a/Extension/Core/Type/LanguageType.php b/Extension/Core/Type/LanguageType.php index eeb9e591a1..e81571f8c4 100644 --- a/Extension/Core/Type/LanguageType.php +++ b/Extension/Core/Type/LanguageType.php @@ -23,10 +23,7 @@ class LanguageType extends AbstractType { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'choice_loader' => function (Options $options) { diff --git a/Extension/Core/Type/LocaleType.php b/Extension/Core/Type/LocaleType.php index e98134febd..d0124e6000 100644 --- a/Extension/Core/Type/LocaleType.php +++ b/Extension/Core/Type/LocaleType.php @@ -22,10 +22,7 @@ class LocaleType extends AbstractType { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'choice_loader' => function (Options $options) { diff --git a/Extension/Core/Type/MoneyType.php b/Extension/Core/Type/MoneyType.php index 9c9e5b4d7c..837d9ade42 100644 --- a/Extension/Core/Type/MoneyType.php +++ b/Extension/Core/Type/MoneyType.php @@ -24,10 +24,7 @@ class MoneyType extends AbstractType { protected static $patterns = []; - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { // Values used in HTML5 number inputs should be formatted as in "1234.5", ie. 'en' format without grouping, // according to https://www.w3.org/TR/html51/sec-forms.html#date-time-and-number-formats @@ -42,10 +39,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $view->vars['money_pattern'] = self::getPattern($options['currency']); @@ -54,10 +48,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'scale' => 2, @@ -103,10 +94,8 @@ public function getBlockPrefix(): string * * The pattern contains the placeholder "{{ widget }}" where the HTML tag should * be inserted - * - * @return string */ - protected static function getPattern(?string $currency) + protected static function getPattern(?string $currency): string { if (!$currency) { return '{{ widget }}'; diff --git a/Extension/Core/Type/NumberType.php b/Extension/Core/Type/NumberType.php index 578991f9fd..ce516a352c 100644 --- a/Extension/Core/Type/NumberType.php +++ b/Extension/Core/Type/NumberType.php @@ -23,10 +23,7 @@ class NumberType extends AbstractType { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addViewTransformer(new NumberToLocalizedStringTransformer( $options['scale'], @@ -40,10 +37,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { if ($options['html5']) { $view->vars['type'] = 'number'; @@ -56,10 +50,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ // default scale is locale specific (usually around 3) diff --git a/Extension/Core/Type/PasswordType.php b/Extension/Core/Type/PasswordType.php index 0c247f0f30..72cc8ec712 100644 --- a/Extension/Core/Type/PasswordType.php +++ b/Extension/Core/Type/PasswordType.php @@ -18,20 +18,14 @@ class PasswordType extends AbstractType { - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { if ($options['always_empty'] || !$form->isSubmitted()) { $view->vars['value'] = ''; } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'always_empty' => true, diff --git a/Extension/Core/Type/PercentType.php b/Extension/Core/Type/PercentType.php index f71e288b3e..fae102c31a 100644 --- a/Extension/Core/Type/PercentType.php +++ b/Extension/Core/Type/PercentType.php @@ -20,10 +20,7 @@ class PercentType extends AbstractType { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addViewTransformer(new PercentToLocalizedStringTransformer( $options['scale'], @@ -33,10 +30,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) )); } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $view->vars['symbol'] = $options['symbol']; @@ -45,10 +39,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'scale' => 0, diff --git a/Extension/Core/Type/RadioType.php b/Extension/Core/Type/RadioType.php index 4b97b0ae21..ac72a20bae 100644 --- a/Extension/Core/Type/RadioType.php +++ b/Extension/Core/Type/RadioType.php @@ -16,10 +16,7 @@ class RadioType extends AbstractType { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'invalid_message' => 'Please select a valid option.', diff --git a/Extension/Core/Type/RangeType.php b/Extension/Core/Type/RangeType.php index 2e33a977d9..edb04b4ca3 100644 --- a/Extension/Core/Type/RangeType.php +++ b/Extension/Core/Type/RangeType.php @@ -16,10 +16,7 @@ class RangeType extends AbstractType { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'invalid_message' => 'Please choose a valid range.', diff --git a/Extension/Core/Type/RepeatedType.php b/Extension/Core/Type/RepeatedType.php index 4176f93e52..96d2c07d3e 100644 --- a/Extension/Core/Type/RepeatedType.php +++ b/Extension/Core/Type/RepeatedType.php @@ -18,10 +18,7 @@ class RepeatedType extends AbstractType { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { // Overwrite required option for child fields $options['first_options']['required'] = $options['required']; @@ -44,10 +41,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) ; } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'type' => TextType::class, diff --git a/Extension/Core/Type/SearchType.php b/Extension/Core/Type/SearchType.php index 0dca6e42a8..f69cf79ee4 100644 --- a/Extension/Core/Type/SearchType.php +++ b/Extension/Core/Type/SearchType.php @@ -16,10 +16,7 @@ class SearchType extends AbstractType { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'invalid_message' => 'Please enter a valid search term.', diff --git a/Extension/Core/Type/SubmitType.php b/Extension/Core/Type/SubmitType.php index 3f1b5f95c9..5681060d48 100644 --- a/Extension/Core/Type/SubmitType.php +++ b/Extension/Core/Type/SubmitType.php @@ -24,10 +24,7 @@ */ class SubmitType extends AbstractType implements SubmitButtonTypeInterface { - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $view->vars['clicked'] = $form->isClicked(); @@ -36,10 +33,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('validate', true); $resolver->setAllowedTypes('validate', 'bool'); diff --git a/Extension/Core/Type/TelType.php b/Extension/Core/Type/TelType.php index 05fdd41626..29a3b5db55 100644 --- a/Extension/Core/Type/TelType.php +++ b/Extension/Core/Type/TelType.php @@ -16,10 +16,7 @@ class TelType extends AbstractType { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'invalid_message' => 'Please provide a valid phone number.', diff --git a/Extension/Core/Type/TextType.php b/Extension/Core/Type/TextType.php index 479ce054d8..bff23eab48 100644 --- a/Extension/Core/Type/TextType.php +++ b/Extension/Core/Type/TextType.php @@ -18,10 +18,7 @@ class TextType extends AbstractType implements DataTransformerInterface { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { // When empty_data is explicitly set to an empty string, // a string should always be returned when NULL is submitted @@ -33,10 +30,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'compound' => false, diff --git a/Extension/Core/Type/TextareaType.php b/Extension/Core/Type/TextareaType.php index 40e7580d80..1615964c53 100644 --- a/Extension/Core/Type/TextareaType.php +++ b/Extension/Core/Type/TextareaType.php @@ -17,10 +17,7 @@ class TextareaType extends AbstractType { - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $view->vars['pattern'] = null; unset($view->vars['attr']['pattern']); diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 7788290d7a..b59a7586f1 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -34,10 +34,7 @@ class TimeType extends AbstractType 'choice' => ChoiceType::class, ]; - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $parts = ['hour']; $format = 'H'; @@ -224,10 +221,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $view->vars = array_replace($view->vars, [ 'widget' => $options['widget'], @@ -255,10 +249,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $compound = static fn (Options $options) => 'single_text' !== $options['widget']; diff --git a/Extension/Core/Type/TimezoneType.php b/Extension/Core/Type/TimezoneType.php index a5d4bc61c0..4b64fd881c 100644 --- a/Extension/Core/Type/TimezoneType.php +++ b/Extension/Core/Type/TimezoneType.php @@ -25,10 +25,7 @@ class TimezoneType extends AbstractType { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if ('datetimezone' === $options['input']) { $builder->addModelTransformer(new DateTimeZoneToStringTransformer($options['multiple'])); @@ -37,10 +34,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'intl' => false, diff --git a/Extension/Core/Type/TransformationFailureExtension.php b/Extension/Core/Type/TransformationFailureExtension.php index 029ad4d439..5539e57f9f 100644 --- a/Extension/Core/Type/TransformationFailureExtension.php +++ b/Extension/Core/Type/TransformationFailureExtension.php @@ -28,10 +28,7 @@ public function __construct(TranslatorInterface $translator = null) $this->translator = $translator; } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if (!isset($options['constraints'])) { $builder->addEventSubscriber(new TransformationFailureListener($this->translator)); diff --git a/Extension/Core/Type/UlidType.php b/Extension/Core/Type/UlidType.php index ea3da07c02..a17b9d9c1d 100644 --- a/Extension/Core/Type/UlidType.php +++ b/Extension/Core/Type/UlidType.php @@ -21,20 +21,14 @@ */ class UlidType extends AbstractType { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->addViewTransformer(new UlidToStringTransformer()) ; } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'compound' => false, diff --git a/Extension/Core/Type/UrlType.php b/Extension/Core/Type/UrlType.php index 385c7a25fa..d9cd3c6fb3 100644 --- a/Extension/Core/Type/UrlType.php +++ b/Extension/Core/Type/UrlType.php @@ -20,20 +20,14 @@ class UrlType extends AbstractType { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if (null !== $options['default_protocol']) { $builder->addEventSubscriber(new FixUrlProtocolListener($options['default_protocol'])); } } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { if ($options['default_protocol']) { $view->vars['attr']['inputmode'] = 'url'; @@ -41,10 +35,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'default_protocol' => 'http', diff --git a/Extension/Core/Type/UuidType.php b/Extension/Core/Type/UuidType.php index 7c0f65b9a0..1035939a12 100644 --- a/Extension/Core/Type/UuidType.php +++ b/Extension/Core/Type/UuidType.php @@ -21,20 +21,14 @@ */ class UuidType extends AbstractType { - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->addViewTransformer(new UuidToStringTransformer()) ; } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'compound' => false, diff --git a/Extension/Core/Type/WeekType.php b/Extension/Core/Type/WeekType.php index 8027a41a99..c3ffae0617 100644 --- a/Extension/Core/Type/WeekType.php +++ b/Extension/Core/Type/WeekType.php @@ -28,10 +28,7 @@ class WeekType extends AbstractType 'choice' => ChoiceType::class, ]; - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if ('string' === $options['input']) { $builder->addModelTransformer(new WeekToArrayTransformer()); @@ -83,10 +80,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $view->vars['widget'] = $options['widget']; @@ -95,10 +89,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $compound = static fn (Options $options) => 'single_text' !== $options['widget']; diff --git a/Extension/Csrf/EventListener/CsrfValidationListener.php b/Extension/Csrf/EventListener/CsrfValidationListener.php index eca450a165..dab31fb65f 100644 --- a/Extension/Csrf/EventListener/CsrfValidationListener.php +++ b/Extension/Csrf/EventListener/CsrfValidationListener.php @@ -51,10 +51,7 @@ public function __construct(string $fieldName, CsrfTokenManagerInterface $tokenM $this->serverParams = $serverParams ?? new ServerParams(); } - /** - * @return void - */ - public function preSubmit(FormEvent $event) + public function preSubmit(FormEvent $event): void { $form = $event->getForm(); $postRequestSizeExceeded = 'POST' === $form->getConfig()->getMethod() && $this->serverParams->hasPostMaxSizeBeenExceeded(); diff --git a/Extension/Csrf/Type/FormTypeCsrfExtension.php b/Extension/Csrf/Type/FormTypeCsrfExtension.php index 8c3d45dec0..7096b8957d 100644 --- a/Extension/Csrf/Type/FormTypeCsrfExtension.php +++ b/Extension/Csrf/Type/FormTypeCsrfExtension.php @@ -47,10 +47,8 @@ public function __construct(CsrfTokenManagerInterface $defaultTokenManager, bool /** * Adds a CSRF field to the form when the CSRF protection is enabled. - * - * @return void */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if (!$options['csrf_protection']) { return; @@ -71,10 +69,8 @@ public function buildForm(FormBuilderInterface $builder, array $options) /** * Adds a CSRF field to the root form view. - * - * @return void */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function finishView(FormView $view, FormInterface $form, array $options): void { if ($options['csrf_protection'] && !$view->parent && $options['compound']) { $factory = $form->getConfig()->getFormFactory(); @@ -90,10 +86,7 @@ public function finishView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'csrf_protection' => $this->defaultEnabled, diff --git a/Extension/DataCollector/EventListener/DataCollectorListener.php b/Extension/DataCollector/EventListener/DataCollectorListener.php index 41a52e091e..f32dc9bc7d 100644 --- a/Extension/DataCollector/EventListener/DataCollectorListener.php +++ b/Extension/DataCollector/EventListener/DataCollectorListener.php @@ -43,10 +43,8 @@ public static function getSubscribedEvents(): array /** * Listener for the {@link FormEvents::POST_SET_DATA} event. - * - * @return void */ - public function postSetData(FormEvent $event) + public function postSetData(FormEvent $event): void { if ($event->getForm()->isRoot()) { // Collect basic information about each form @@ -59,10 +57,8 @@ public function postSetData(FormEvent $event) /** * Listener for the {@link FormEvents::POST_SUBMIT} event. - * - * @return void */ - public function postSubmit(FormEvent $event) + public function postSubmit(FormEvent $event): void { if ($event->getForm()->isRoot()) { // Collect the submitted data of each form diff --git a/Extension/DataCollector/FormDataCollectorInterface.php b/Extension/DataCollector/FormDataCollectorInterface.php index 346c101fe3..7c7903980b 100644 --- a/Extension/DataCollector/FormDataCollectorInterface.php +++ b/Extension/DataCollector/FormDataCollectorInterface.php @@ -25,48 +25,36 @@ interface FormDataCollectorInterface extends DataCollectorInterface { /** * Stores configuration data of the given form and its children. - * - * @return void */ - public function collectConfiguration(FormInterface $form); + public function collectConfiguration(FormInterface $form): void; /** * Stores the default data of the given form and its children. - * - * @return void */ - public function collectDefaultData(FormInterface $form); + public function collectDefaultData(FormInterface $form): void; /** * Stores the submitted data of the given form and its children. - * - * @return void */ - public function collectSubmittedData(FormInterface $form); + public function collectSubmittedData(FormInterface $form): void; /** * Stores the view variables of the given form view and its children. - * - * @return void */ - public function collectViewVariables(FormView $view); + public function collectViewVariables(FormView $view): void; /** * Specifies that the given objects represent the same conceptual form. - * - * @return void */ - public function associateFormWithView(FormInterface $form, FormView $view); + public function associateFormWithView(FormInterface $form, FormView $view): void; /** * Assembles the data collected about the given form and its children as * a tree-like data structure. * * The result can be queried using {@link getData()}. - * - * @return void */ - public function buildPreliminaryFormTree(FormInterface $form); + public function buildPreliminaryFormTree(FormInterface $form): void; /** * Assembles the data collected about the given form and its children as @@ -85,10 +73,8 @@ public function buildPreliminaryFormTree(FormInterface $form); * tree, only the view data will be included in the result. If a * corresponding {@link FormInterface} exists otherwise, call * {@link associateFormWithView()} before calling this method. - * - * @return void */ - public function buildFinalFormTree(FormInterface $form, FormView $view); + public function buildFinalFormTree(FormInterface $form, FormView $view): void; /** * Returns all collected data. diff --git a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php index 6c8cf3ee24..1e922ff2ea 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php @@ -71,26 +71,17 @@ public function createView(FormInterface $form, FormView $parent = null): FormVi return $this->proxiedType->createView($form, $parent); } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $this->proxiedType->buildForm($builder, $options); } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $this->proxiedType->buildView($view, $form, $options); } - /** - * @return void - */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function finishView(FormView $view, FormInterface $form, array $options): void { $this->proxiedType->finishView($view, $form, $options); diff --git a/Extension/DataCollector/Type/DataCollectorTypeExtension.php b/Extension/DataCollector/Type/DataCollectorTypeExtension.php index f1e3c903ec..0f40968e44 100644 --- a/Extension/DataCollector/Type/DataCollectorTypeExtension.php +++ b/Extension/DataCollector/Type/DataCollectorTypeExtension.php @@ -32,10 +32,7 @@ public function __construct(FormDataCollectorInterface $dataCollector) $this->listener = new DataCollectorListener($dataCollector); } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addEventSubscriber($this->listener); } diff --git a/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php b/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php index 8e92ea74a5..8c339a0675 100644 --- a/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php +++ b/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtension.php @@ -35,10 +35,7 @@ public static function getExtendedTypes(): iterable return [TextType::class]; } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver ->setDefaults(['sanitize_html' => false, 'sanitizer' => null]) @@ -47,10 +44,7 @@ public function configureOptions(OptionsResolver $resolver) ; } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if (!$options['sanitize_html']) { return; diff --git a/Extension/HttpFoundation/HttpFoundationRequestHandler.php b/Extension/HttpFoundation/HttpFoundationRequestHandler.php index b4e835c95a..636761593f 100644 --- a/Extension/HttpFoundation/HttpFoundationRequestHandler.php +++ b/Extension/HttpFoundation/HttpFoundationRequestHandler.php @@ -35,10 +35,7 @@ public function __construct(ServerParams $serverParams = null) $this->serverParams = $serverParams ?? new ServerParams(); } - /** - * @return void - */ - public function handleRequest(FormInterface $form, mixed $request = null) + public function handleRequest(FormInterface $form, mixed $request = null): void { if (!$request instanceof Request) { throw new UnexpectedTypeException($request, Request::class); diff --git a/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php b/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php index cc3e5e1207..ce90c30528 100644 --- a/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php +++ b/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php @@ -29,10 +29,7 @@ public function __construct(RequestHandlerInterface $requestHandler = null) $this->requestHandler = $requestHandler ?? new HttpFoundationRequestHandler(); } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->setRequestHandler($this->requestHandler); } diff --git a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php index 4854dd3e73..3ddac5ff35 100644 --- a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php +++ b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php @@ -35,10 +35,7 @@ public function __construct( $this->propertyAccessor ??= PropertyAccess::createPropertyAccessor(); } - /** - * @return void - */ - public function registerPassword(FormEvent $event) + public function registerPassword(FormEvent $event): void { if (null === $event->getData() || '' === $event->getData()) { return; @@ -53,10 +50,7 @@ public function registerPassword(FormEvent $event) ]; } - /** - * @return void - */ - public function hashPasswords(FormEvent $event) + public function hashPasswords(FormEvent $event): void { $form = $event->getForm(); diff --git a/Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php b/Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php index 5308992863..8836f95d93 100644 --- a/Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php +++ b/Extension/PasswordHasher/Type/FormTypePasswordHasherExtension.php @@ -27,10 +27,7 @@ public function __construct( ) { } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addEventListener(FormEvents::POST_SUBMIT, [$this->passwordHasherListener, 'hashPasswords']); } diff --git a/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php b/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php index 6f022fb1bf..1d73e0788b 100644 --- a/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php +++ b/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtension.php @@ -29,20 +29,14 @@ public function __construct( ) { } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { if ($options['hash_property_path']) { $builder->addEventListener(FormEvents::POST_SUBMIT, [$this->passwordHasherListener, 'registerPassword']); } } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'hash_property_path' => null, diff --git a/Extension/Validator/Constraints/FormValidator.php b/Extension/Validator/Constraints/FormValidator.php index d664e9b500..4a05981a86 100644 --- a/Extension/Validator/Constraints/FormValidator.php +++ b/Extension/Validator/Constraints/FormValidator.php @@ -29,10 +29,7 @@ class FormValidator extends ConstraintValidator */ private \SplObjectStorage $resolvedGroups; - /** - * @return void - */ - public function validate(mixed $form, Constraint $formConstraint) + public function validate(mixed $form, Constraint $formConstraint): void { if (!$formConstraint instanceof Form) { throw new UnexpectedTypeException($formConstraint, Form::class); diff --git a/Extension/Validator/EventListener/ValidationListener.php b/Extension/Validator/EventListener/ValidationListener.php index e2d4357622..d24264f244 100644 --- a/Extension/Validator/EventListener/ValidationListener.php +++ b/Extension/Validator/EventListener/ValidationListener.php @@ -37,10 +37,7 @@ public function __construct(ValidatorInterface $validator, ViolationMapperInterf $this->violationMapper = $violationMapper; } - /** - * @return void - */ - public function validateForm(FormEvent $event) + public function validateForm(FormEvent $event): void { $form = $event->getForm(); diff --git a/Extension/Validator/Type/BaseValidatorExtension.php b/Extension/Validator/Type/BaseValidatorExtension.php index ea01d03699..4b3fb49624 100644 --- a/Extension/Validator/Type/BaseValidatorExtension.php +++ b/Extension/Validator/Type/BaseValidatorExtension.php @@ -24,10 +24,7 @@ */ abstract class BaseValidatorExtension extends AbstractTypeExtension { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // Make sure that validation groups end up as null, closure or array $validationGroupsNormalizer = static function (Options $options, $groups) { diff --git a/Extension/Validator/Type/FormTypeValidatorExtension.php b/Extension/Validator/Type/FormTypeValidatorExtension.php index 54eebaf63e..e904a4f16e 100644 --- a/Extension/Validator/Type/FormTypeValidatorExtension.php +++ b/Extension/Validator/Type/FormTypeValidatorExtension.php @@ -37,18 +37,12 @@ public function __construct(ValidatorInterface $validator, bool $legacyErrorMess $this->violationMapper = new ViolationMapper($formRenderer, $translator); } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->addEventSubscriber(new ValidationListener($this->validator, $this->violationMapper)); } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); diff --git a/Extension/Validator/Type/RepeatedTypeValidatorExtension.php b/Extension/Validator/Type/RepeatedTypeValidatorExtension.php index d41dc0168c..949dca46a6 100644 --- a/Extension/Validator/Type/RepeatedTypeValidatorExtension.php +++ b/Extension/Validator/Type/RepeatedTypeValidatorExtension.php @@ -21,10 +21,7 @@ */ class RepeatedTypeValidatorExtension extends AbstractTypeExtension { - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // Map errors to the first field $errorMapping = static fn (Options $options) => ['.' => $options['first_name']]; diff --git a/Extension/Validator/Type/UploadValidatorExtension.php b/Extension/Validator/Type/UploadValidatorExtension.php index b7a19ed26a..80e3315ae9 100644 --- a/Extension/Validator/Type/UploadValidatorExtension.php +++ b/Extension/Validator/Type/UploadValidatorExtension.php @@ -32,10 +32,7 @@ public function __construct(TranslatorInterface $translator, string $translation $this->translationDomain = $translationDomain; } - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $translator = $this->translator; $translationDomain = $this->translationDomain; diff --git a/Extension/Validator/ViolationMapper/ViolationMapper.php b/Extension/Validator/ViolationMapper/ViolationMapper.php index 2f2ccefd30..fca010d70e 100644 --- a/Extension/Validator/ViolationMapper/ViolationMapper.php +++ b/Extension/Validator/ViolationMapper/ViolationMapper.php @@ -38,10 +38,7 @@ public function __construct(FormRendererInterface $formRenderer = null, Translat $this->translator = $translator; } - /** - * @return void - */ - public function mapViolation(ConstraintViolation $violation, FormInterface $form, bool $allowNonSynchronized = false) + public function mapViolation(ConstraintViolation $violation, FormInterface $form, bool $allowNonSynchronized = false): void { $this->allowNonSynchronized = $allowNonSynchronized; diff --git a/Extension/Validator/ViolationMapper/ViolationMapperInterface.php b/Extension/Validator/ViolationMapper/ViolationMapperInterface.php index a72d41df9e..8d1f242f95 100644 --- a/Extension/Validator/ViolationMapper/ViolationMapperInterface.php +++ b/Extension/Validator/ViolationMapper/ViolationMapperInterface.php @@ -24,8 +24,6 @@ interface ViolationMapperInterface * the given form. * * @param bool $allowNonSynchronized Whether to allow mapping to non-synchronized forms - * - * @return void */ - public function mapViolation(ConstraintViolation $violation, FormInterface $form, bool $allowNonSynchronized = false); + public function mapViolation(ConstraintViolation $violation, FormInterface $form, bool $allowNonSynchronized = false): void; } diff --git a/Extension/Validator/ViolationMapper/ViolationPathIterator.php b/Extension/Validator/ViolationMapper/ViolationPathIterator.php index ed363a7b15..06c719dc80 100644 --- a/Extension/Validator/ViolationMapper/ViolationPathIterator.php +++ b/Extension/Validator/ViolationMapper/ViolationPathIterator.php @@ -23,10 +23,7 @@ public function __construct(ViolationPath $violationPath) parent::__construct($violationPath); } - /** - * @return bool - */ - public function mapsForm() + public function mapsForm(): bool { return $this->path->mapsForm($this->key()); } diff --git a/FormBuilderInterface.php b/FormBuilderInterface.php index d4e7b525d5..c00fae46a5 100644 --- a/FormBuilderInterface.php +++ b/FormBuilderInterface.php @@ -27,7 +27,7 @@ interface FormBuilderInterface extends \Traversable, \Countable, FormConfigBuild * * @param array $options */ - public function add(string|FormBuilderInterface $child, string $type = null, array $options = []): static; + public function add(string|self $child, string $type = null, array $options = []): static; /** * Creates a form builder. diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 29e643680e..ef10087b80 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -533,7 +533,7 @@ public function setDataLocked(bool $locked): static /** * @return $this */ - public function setFormFactory(FormFactoryInterface $formFactory) + public function setFormFactory(FormFactoryInterface $formFactory): static { if ($this->locked) { throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); diff --git a/FormConfigBuilderInterface.php b/FormConfigBuilderInterface.php index 09b9149801..6b22b9f9e8 100644 --- a/FormConfigBuilderInterface.php +++ b/FormConfigBuilderInterface.php @@ -208,7 +208,7 @@ public function setDataLocked(bool $locked): static; * * @return $this */ - public function setFormFactory(FormFactoryInterface $formFactory); + public function setFormFactory(FormFactoryInterface $formFactory): static; /** * Sets the target URL of the form. diff --git a/FormError.php b/FormError.php index 572783c7ac..632d839ea2 100644 --- a/FormError.php +++ b/FormError.php @@ -99,11 +99,9 @@ public function getCause(): mixed * * This method must only be called once. * - * @return void - * * @throws BadMethodCallException If the method is called more than once */ - public function setOrigin(FormInterface $origin) + public function setOrigin(FormInterface $origin): void { if (null !== $this->origin) { throw new BadMethodCallException('setOrigin() must only be called once.'); diff --git a/FormEvent.php b/FormEvent.php index 1e6aa34d63..cedf2ea2e7 100644 --- a/FormEvent.php +++ b/FormEvent.php @@ -45,10 +45,8 @@ public function getData(): mixed /** * Allows updating with some filtered data. - * - * @return void */ - public function setData(mixed $data) + public function setData(mixed $data): void { $this->data = $data; } diff --git a/FormRenderer.php b/FormRenderer.php index 18dec4946b..c2771d28c9 100644 --- a/FormRenderer.php +++ b/FormRenderer.php @@ -42,10 +42,7 @@ public function getEngine(): FormRendererEngineInterface return $this->engine; } - /** - * @return void - */ - public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true) + public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true): void { $this->engine->setTheme($view, $themes, $useDefaultThemes); } diff --git a/FormRendererEngineInterface.php b/FormRendererEngineInterface.php index e7de3544a1..e3c4ba899a 100644 --- a/FormRendererEngineInterface.php +++ b/FormRendererEngineInterface.php @@ -24,10 +24,8 @@ interface FormRendererEngineInterface * @param FormView $view The view to assign the theme(s) to * @param mixed $themes The theme(s). The type of these themes * is open to the implementation. - * - * @return void */ - public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true); + public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true): void; /** * Returns the resource for a block name. @@ -129,8 +127,6 @@ public function getResourceHierarchyLevel(FormView $view, array $blockNameHierar * @param FormView $view The view to render * @param mixed $resource The renderer resource * @param array $variables The variables to pass to the template - * - * @return string */ - public function renderBlock(FormView $view, mixed $resource, string $blockName, array $variables = []); + public function renderBlock(FormView $view, mixed $resource, string $blockName, array $variables = []): string; } diff --git a/FormRendererInterface.php b/FormRendererInterface.php index 8e805727ce..d57a904b3b 100644 --- a/FormRendererInterface.php +++ b/FormRendererInterface.php @@ -31,10 +31,8 @@ public function getEngine(): FormRendererEngineInterface; * is open to the implementation. * @param bool $useDefaultThemes If true, will use default themes specified * in the renderer - * - * @return void */ - public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true); + public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true): void; /** * Renders a named block of the form theme. diff --git a/FormTypeExtensionInterface.php b/FormTypeExtensionInterface.php index 1937834515..2ae07fcf20 100644 --- a/FormTypeExtensionInterface.php +++ b/FormTypeExtensionInterface.php @@ -26,11 +26,9 @@ interface FormTypeExtensionInterface * * @param array $options * - * @return void - * * @see FormTypeInterface::buildForm() */ - public function buildForm(FormBuilderInterface $builder, array $options); + public function buildForm(FormBuilderInterface $builder, array $options): void; /** * Builds the view. @@ -40,11 +38,9 @@ public function buildForm(FormBuilderInterface $builder, array $options); * * @param array $options * - * @return void - * * @see FormTypeInterface::buildView() */ - public function buildView(FormView $view, FormInterface $form, array $options); + public function buildView(FormView $view, FormInterface $form, array $options): void; /** * Finishes the view. @@ -54,16 +50,11 @@ public function buildView(FormView $view, FormInterface $form, array $options); * * @param array $options * - * @return void - * * @see FormTypeInterface::finishView() */ - public function finishView(FormView $view, FormInterface $form, array $options); + public function finishView(FormView $view, FormInterface $form, array $options): void; - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver); + public function configureOptions(OptionsResolver $resolver): void; /** * Gets the extended types. diff --git a/FormTypeGuesserInterface.php b/FormTypeGuesserInterface.php index 61e2c5f80d..e895c0f085 100644 --- a/FormTypeGuesserInterface.php +++ b/FormTypeGuesserInterface.php @@ -18,24 +18,18 @@ interface FormTypeGuesserInterface { /** * Returns a field guess for a property name of a class. - * - * @return Guess\TypeGuess|null */ - public function guessType(string $class, string $property); + public function guessType(string $class, string $property): ?Guess\TypeGuess; /** * Returns a guess whether a property of a class is required. - * - * @return Guess\ValueGuess|null */ - public function guessRequired(string $class, string $property); + public function guessRequired(string $class, string $property): ?Guess\ValueGuess; /** * Returns a guess about the field's maximum length. - * - * @return Guess\ValueGuess|null */ - public function guessMaxLength(string $class, string $property); + public function guessMaxLength(string $class, string $property): ?Guess\ValueGuess; /** * Returns a guess about the field's pattern. @@ -46,8 +40,6 @@ public function guessMaxLength(string $class, string $property); * You want a float greater than 5, 4.512313 is not valid but length(4.512314) > length(5) * * @see https://github.com/symfony/symfony/pull/3927 - * - * @return Guess\ValueGuess|null */ - public function guessPattern(string $class, string $property); + public function guessPattern(string $class, string $property): ?Guess\ValueGuess; } diff --git a/FormTypeInterface.php b/FormTypeInterface.php index 0c586d3f71..3d6c3a3527 100644 --- a/FormTypeInterface.php +++ b/FormTypeInterface.php @@ -26,11 +26,9 @@ interface FormTypeInterface * * @param array $options * - * @return void - * * @see FormTypeExtensionInterface::buildForm() */ - public function buildForm(FormBuilderInterface $builder, array $options); + public function buildForm(FormBuilderInterface $builder, array $options): void; /** * Builds the form view. @@ -44,11 +42,9 @@ public function buildForm(FormBuilderInterface $builder, array $options); * * @param array $options * - * @return void - * * @see FormTypeExtensionInterface::buildView() */ - public function buildView(FormView $view, FormInterface $form, array $options); + public function buildView(FormView $view, FormInterface $form, array $options): void; /** * Finishes the form view. @@ -63,33 +59,25 @@ public function buildView(FormView $view, FormInterface $form, array $options); * * @param array $options * - * @return void - * * @see FormTypeExtensionInterface::finishView() */ - public function finishView(FormView $view, FormInterface $form, array $options); + public function finishView(FormView $view, FormInterface $form, array $options): void; /** * Configures the options for this type. - * - * @return void */ - public function configureOptions(OptionsResolver $resolver); + public function configureOptions(OptionsResolver $resolver): void; /** * Returns the prefix of the template block name for this type. * * The block prefix defaults to the underscored short class name with * the "Type" suffix removed (e.g. "UserProfileType" => "user_profile"). - * - * @return string */ - public function getBlockPrefix(); + public function getBlockPrefix(): string; /** * Returns the name of the parent type. - * - * @return string|null */ - public function getParent(); + public function getParent(): ?string; } diff --git a/FormView.php b/FormView.php index e04fa13b09..746d1d2ee4 100644 --- a/FormView.php +++ b/FormView.php @@ -92,10 +92,7 @@ public function isMethodRendered(): bool return $this->methodRendered; } - /** - * @return void - */ - public function setMethodRendered() + public function setMethodRendered(): void { $this->methodRendered = true; } diff --git a/NativeRequestHandler.php b/NativeRequestHandler.php index 11c4d4d9c0..e91ee92e4c 100644 --- a/NativeRequestHandler.php +++ b/NativeRequestHandler.php @@ -40,11 +40,9 @@ public function __construct(ServerParams $params = null) } /** - * @return void - * * @throws Exception\UnexpectedTypeException If the $request is not null */ - public function handleRequest(FormInterface $form, mixed $request = null) + public function handleRequest(FormInterface $form, mixed $request = null): void { if (null !== $request) { throw new UnexpectedTypeException($request, 'null'); diff --git a/RequestHandlerInterface.php b/RequestHandlerInterface.php index 39fd458ee4..2a4bccf717 100644 --- a/RequestHandlerInterface.php +++ b/RequestHandlerInterface.php @@ -20,10 +20,8 @@ interface RequestHandlerInterface { /** * Submits a form if it was submitted. - * - * @return void */ - public function handleRequest(FormInterface $form, mixed $request = null); + public function handleRequest(FormInterface $form, mixed $request = null): void; /** * Returns true if the given data is a file upload. diff --git a/ResolvedFormType.php b/ResolvedFormType.php index f05db1533b..1acdce8375 100644 --- a/ResolvedFormType.php +++ b/ResolvedFormType.php @@ -92,10 +92,7 @@ public function createView(FormInterface $form, FormView $parent = null): FormVi return $this->newView($parent); } - /** - * @return void - */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $this->parent?->buildForm($builder, $options); @@ -106,10 +103,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) } } - /** - * @return void - */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options): void { $this->parent?->buildView($view, $form, $options); @@ -120,10 +114,7 @@ public function buildView(FormView $view, FormInterface $form, array $options) } } - /** - * @return void - */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function finishView(FormView $view, FormInterface $form, array $options): void { $this->parent?->finishView($view, $form, $options); diff --git a/ResolvedFormTypeInterface.php b/ResolvedFormTypeInterface.php index e0b96a5ac3..821d4d4b4e 100644 --- a/ResolvedFormTypeInterface.php +++ b/ResolvedFormTypeInterface.php @@ -56,28 +56,22 @@ public function createView(FormInterface $form, FormView $parent = null): FormVi /** * Configures a form builder for the type hierarchy. - * - * @return void */ - public function buildForm(FormBuilderInterface $builder, array $options); + public function buildForm(FormBuilderInterface $builder, array $options): void; /** * Configures a form view for the type hierarchy. * * It is called before the children of the view are built. - * - * @return void */ - public function buildView(FormView $view, FormInterface $form, array $options); + public function buildView(FormView $view, FormInterface $form, array $options): void; /** * Finishes a form view for the type hierarchy. * * It is called after the children of the view have been built. - * - * @return void */ - public function finishView(FormView $view, FormInterface $form, array $options); + public function finishView(FormView $view, FormInterface $form, array $options): void; /** * Returns the configured options resolver used for this type. diff --git a/Util/OrderedHashMapIterator.php b/Util/OrderedHashMapIterator.php index 828218a452..2a305f8e02 100644 --- a/Util/OrderedHashMapIterator.php +++ b/Util/OrderedHashMapIterator.php @@ -62,10 +62,7 @@ public function __sleep(): array throw new \BadMethodCallException('Cannot serialize '.__CLASS__); } - /** - * @return void - */ - public function __wakeup() + public function __wakeup(): void { throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); } From 530b5833bcfac1e57f97fc3d91d8c9ee74d1dd7e Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 5 Jul 2023 17:13:01 +0200 Subject: [PATCH 117/208] [Form] Revert native return types on AbstractType --- AbstractType.php | 30 ++++++++++++++++++++++++------ FormTypeInterface.php | 24 ++++++++++++++++++------ 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/AbstractType.php b/AbstractType.php index 269d541a0f..ad4b195696 100644 --- a/AbstractType.php +++ b/AbstractType.php @@ -20,28 +20,46 @@ */ abstract class AbstractType implements FormTypeInterface { - public function buildForm(FormBuilderInterface $builder, array $options): void + /** + * @return void + */ + public function buildForm(FormBuilderInterface $builder, array $options) { } - public function buildView(FormView $view, FormInterface $form, array $options): void + /** + * @return void + */ + public function buildView(FormView $view, FormInterface $form, array $options) { } - public function finishView(FormView $view, FormInterface $form, array $options): void + /** + * @return void + */ + public function finishView(FormView $view, FormInterface $form, array $options) { } - public function configureOptions(OptionsResolver $resolver): void + /** + * @return void + */ + public function configureOptions(OptionsResolver $resolver) { } - public function getBlockPrefix(): string + /** + * @return string + */ + public function getBlockPrefix() { return StringUtil::fqcnToBlockPrefix(static::class) ?: ''; } - public function getParent(): ?string + /** + * @return string|null + */ + public function getParent() { return FormType::class; } diff --git a/FormTypeInterface.php b/FormTypeInterface.php index 3d6c3a3527..0c586d3f71 100644 --- a/FormTypeInterface.php +++ b/FormTypeInterface.php @@ -26,9 +26,11 @@ interface FormTypeInterface * * @param array $options * + * @return void + * * @see FormTypeExtensionInterface::buildForm() */ - public function buildForm(FormBuilderInterface $builder, array $options): void; + public function buildForm(FormBuilderInterface $builder, array $options); /** * Builds the form view. @@ -42,9 +44,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void; * * @param array $options * + * @return void + * * @see FormTypeExtensionInterface::buildView() */ - public function buildView(FormView $view, FormInterface $form, array $options): void; + public function buildView(FormView $view, FormInterface $form, array $options); /** * Finishes the form view. @@ -59,25 +63,33 @@ public function buildView(FormView $view, FormInterface $form, array $options): * * @param array $options * + * @return void + * * @see FormTypeExtensionInterface::finishView() */ - public function finishView(FormView $view, FormInterface $form, array $options): void; + public function finishView(FormView $view, FormInterface $form, array $options); /** * Configures the options for this type. + * + * @return void */ - public function configureOptions(OptionsResolver $resolver): void; + public function configureOptions(OptionsResolver $resolver); /** * Returns the prefix of the template block name for this type. * * The block prefix defaults to the underscored short class name with * the "Type" suffix removed (e.g. "UserProfileType" => "user_profile"). + * + * @return string */ - public function getBlockPrefix(): string; + public function getBlockPrefix(); /** * Returns the name of the parent type. + * + * @return string|null */ - public function getParent(): ?string; + public function getParent(); } From ae00de251b3eba4024ccfe30f3bdbb5a6de8f6c9 Mon Sep 17 00:00:00 2001 From: Jules Pietri Date: Tue, 18 Jul 2023 16:55:59 +0200 Subject: [PATCH 118/208] [Form] Remove duplicated attr option in FormType --- Extension/Core/Type/FormType.php | 1 - 1 file changed, 1 deletion(-) diff --git a/Extension/Core/Type/FormType.php b/Extension/Core/Type/FormType.php index 82aa77f0a3..53fb713a64 100644 --- a/Extension/Core/Type/FormType.php +++ b/Extension/Core/Type/FormType.php @@ -178,7 +178,6 @@ public function configureOptions(OptionsResolver $resolver) // According to RFC 2396 (http://www.ietf.org/rfc/rfc2396.txt) // section 4.2., empty URIs are considered same-document references 'action' => '', - 'attr' => [], 'post_max_size_message' => 'The uploaded file was too large. Please try to upload a smaller file.', 'upload_max_size_message' => $uploadMaxSizeMessage, // internal 'allow_file_upload' => false, From 3673459fa1ea7cff33735a1a9e6b60d26be2f246 Mon Sep 17 00:00:00 2001 From: Jules Pietri Date: Thu, 20 Jul 2023 12:42:23 +0200 Subject: [PATCH 119/208] [Form] Deprecate `FormEvent::setData()` for events that do not allow it --- CHANGELOG.md | 2 ++ Event/PostSetDataEvent.php | 9 +++++++++ Event/PostSubmitEvent.php | 8 ++++++++ 3 files changed, 19 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22597f3b47..3918636e56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ CHANGELOG * Deprecate using `DateTime` or `DateTimeImmutable` model data with a different timezone than configured with the `model_timezone` option in `DateType`, `DateTimeType`, and `TimeType` + * Deprecate `PostSetDataEvent::setData()`, use `PreSetDataEvent::setData()` instead + * Deprecate `PostSubmitEvent::setData()`, use `PreSubmitDataEvent::setData()` or `SubmitDataEvent::setData()` instead 6.3 --- diff --git a/Event/PostSetDataEvent.php b/Event/PostSetDataEvent.php index eef537452a..58f2f25a82 100644 --- a/Event/PostSetDataEvent.php +++ b/Event/PostSetDataEvent.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Event; +use Symfony\Component\Form\Exception\BadMethodCallException; use Symfony\Component\Form\FormEvent; /** @@ -20,4 +21,12 @@ */ final class PostSetDataEvent extends FormEvent { + /** + * @deprecated since Symfony 6.4, it will throw an exception in 7.0. + */ + public function setData(mixed $data): void + { + trigger_deprecation('symfony/form', '6.4', 'Calling "%s()" will throw an exception as of 7.0, listen to "form.pre_set_data" instead.', __METHOD__); + // throw new BadMethodCallException('Form data cannot be changed during "form.post_set_data", you should use "form.pre_set_data" instead.'); + } } diff --git a/Event/PostSubmitEvent.php b/Event/PostSubmitEvent.php index aa3775f5c1..b7fb10176a 100644 --- a/Event/PostSubmitEvent.php +++ b/Event/PostSubmitEvent.php @@ -21,4 +21,12 @@ */ final class PostSubmitEvent extends FormEvent { + /** + * @deprecated since Symfony 6.4, it will throw an exception in 7.0. + */ + public function setData(mixed $data): void + { + trigger_deprecation('symfony/form', '6.4', 'Calling "%s()" will throw an exception as of 7.0, listen to "form.pre_submit" or "form.submit" instead.', __METHOD__); + // throw new BadMethodCallException('Form data cannot be changed during "form.post_submit", you should use "form.pre_submit" or "form.submit" instead.'); + } } From 2f1f30cd023f6212f6de53b9af8496a8abe001b2 Mon Sep 17 00:00:00 2001 From: Jules Pietri Date: Mon, 24 Jul 2023 09:08:33 +0200 Subject: [PATCH 120/208] [Form] Remove deprecations in form events --- Event/PostSetDataEvent.php | 6 +----- Event/PostSubmitEvent.php | 7 ++----- 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/Event/PostSetDataEvent.php b/Event/PostSetDataEvent.php index b42012d682..74aeb78d50 100644 --- a/Event/PostSetDataEvent.php +++ b/Event/PostSetDataEvent.php @@ -22,12 +22,8 @@ */ final class PostSetDataEvent extends FormEvent { - /** - * @deprecated since Symfony 6.4, it will throw an exception in 7.0. - */ public function setData(mixed $data): void { - trigger_deprecation('symfony/form', '6.4', 'Calling "%s()" will throw an exception as of 7.0, listen to "form.pre_set_data" instead.', __METHOD__); - // throw new BadMethodCallException('Form data cannot be changed during "form.post_set_data", you should use "form.pre_set_data" instead.'); + throw new BadMethodCallException('Form data cannot be changed during "form.post_set_data", you should use "form.pre_set_data" instead.'); } } diff --git a/Event/PostSubmitEvent.php b/Event/PostSubmitEvent.php index b7fb10176a..104ea2d0ec 100644 --- a/Event/PostSubmitEvent.php +++ b/Event/PostSubmitEvent.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Event; +use Symfony\Component\Form\Exception\BadMethodCallException; use Symfony\Component\Form\FormEvent; /** @@ -21,12 +22,8 @@ */ final class PostSubmitEvent extends FormEvent { - /** - * @deprecated since Symfony 6.4, it will throw an exception in 7.0. - */ public function setData(mixed $data): void { - trigger_deprecation('symfony/form', '6.4', 'Calling "%s()" will throw an exception as of 7.0, listen to "form.pre_submit" or "form.submit" instead.', __METHOD__); - // throw new BadMethodCallException('Form data cannot be changed during "form.post_submit", you should use "form.pre_submit" or "form.submit" instead.'); + throw new BadMethodCallException('Form data cannot be changed during "form.post_submit", you should use "form.pre_submit" or "form.submit" instead.'); } } From fdab838d4c76a7fb6e4785bc8132412fc321b961 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Alfaiate?= Date: Tue, 11 Jul 2023 11:21:41 +0700 Subject: [PATCH 121/208] [Form] Support Translatable Enum --- Extension/Core/Type/EnumType.php | 3 ++- Tests/Extension/Core/Type/EnumTypeTest.php | 17 ++++++++++++++ Tests/Fixtures/TranslatableTextAlign.php | 27 ++++++++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 Tests/Fixtures/TranslatableTextAlign.php diff --git a/Extension/Core/Type/EnumType.php b/Extension/Core/Type/EnumType.php index 003819e065..bfede9c04d 100644 --- a/Extension/Core/Type/EnumType.php +++ b/Extension/Core/Type/EnumType.php @@ -14,6 +14,7 @@ use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; +use Symfony\Contracts\Translation\TranslatableInterface; /** * A choice type for native PHP enums. @@ -29,7 +30,7 @@ public function configureOptions(OptionsResolver $resolver): void ->setAllowedTypes('class', 'string') ->setAllowedValues('class', enum_exists(...)) ->setDefault('choices', static fn (Options $options): array => $options['class']::cases()) - ->setDefault('choice_label', static fn (\UnitEnum $choice): string => $choice->name) + ->setDefault('choice_label', static fn (\UnitEnum $choice) => $choice instanceof TranslatableInterface ? $choice : $choice->name) ->setDefault('choice_value', static function (Options $options): ?\Closure { if (!is_a($options['class'], \BackedEnum::class, true)) { return null; diff --git a/Tests/Extension/Core/Type/EnumTypeTest.php b/Tests/Extension/Core/Type/EnumTypeTest.php index 7c43e945b1..0458720691 100644 --- a/Tests/Extension/Core/Type/EnumTypeTest.php +++ b/Tests/Extension/Core/Type/EnumTypeTest.php @@ -16,8 +16,11 @@ use Symfony\Component\Form\Tests\Fixtures\Answer; use Symfony\Component\Form\Tests\Fixtures\Number; use Symfony\Component\Form\Tests\Fixtures\Suit; +use Symfony\Component\Form\Tests\Fixtures\TranslatableTextAlign; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; +use Symfony\Component\Translation\IdentityTranslator; +use Symfony\Contracts\Translation\TranslatableInterface; class EnumTypeTest extends BaseTypeTestCase { @@ -257,6 +260,20 @@ public function testChoiceLabel() $this->assertSame('Yes', $view->children[0]->vars['label']); } + public function testChoiceLabelTranslatable() + { + $form = $this->factory->create($this->getTestedType(), null, [ + 'multiple' => false, + 'expanded' => true, + 'class' => TranslatableTextAlign::class, + ]); + + $view = $form->createView(); + + $this->assertInstanceOf(TranslatableInterface::class, $view->children[0]->vars['label']); + $this->assertEquals('Left', $view->children[0]->vars['label']->trans(new IdentityTranslator())); + } + protected function getTestOptions(): array { return ['class' => Suit::class]; diff --git a/Tests/Fixtures/TranslatableTextAlign.php b/Tests/Fixtures/TranslatableTextAlign.php new file mode 100644 index 0000000000..7a5d5cdff6 --- /dev/null +++ b/Tests/Fixtures/TranslatableTextAlign.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Tests\Fixtures; + +use Symfony\Contracts\Translation\TranslatableInterface; +use Symfony\Contracts\Translation\TranslatorInterface; + +enum TranslatableTextAlign implements TranslatableInterface +{ + case Left; + case Center; + case Right; + + public function trans(TranslatorInterface $translator, string $locale = null): string + { + return $translator->trans($this->name, locale: $locale); + } +} From d9fd1f267074854ef9793784b56fd1e29d70c8dc Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 21 Jul 2023 15:28:24 +0200 Subject: [PATCH 122/208] Use typed properties in tests as much as possible --- Test/FormIntegrationTestCase.php | 5 +- Tests/AbstractRequestHandlerTestCase.php | 19 +--- .../ChoiceList/AbstractChoiceListTestCase.php | 101 +++--------------- Tests/ChoiceList/ArrayChoiceListTest.php | 2 +- .../Factory/CachingFactoryDecoratorTest.php | 5 +- .../Factory/DefaultChoiceListFactoryTest.php | 38 +++---- .../Factory/PropertyAccessDecoratorTest.php | 5 +- .../Loader/CallbackChoiceLoaderTest.php | 39 +------ .../Loader/IntlCallbackChoiceLoaderTest.php | 39 +------ Tests/CompoundFormTest.php | 12 +-- .../Descriptor/AbstractDescriptorTestCase.php | 2 +- .../Core/DataMapper/DataMapperTest.php | 14 +-- .../ArrayToPartsTransformerTest.php | 7 +- .../BooleanToStringTransformerTest.php | 10 +- .../ChoiceToValueTransformerTest.php | 10 +- .../ChoicesToValuesTransformerTest.php | 10 +- ...teTimeToLocalizedStringTransformerTest.php | 8 +- .../DateTimeToRfc3339TransformerTest.php | 10 +- ...ntegerToLocalizedStringTransformerTest.php | 2 +- .../MoneyToLocalizedStringTransformerTest.php | 4 +- ...NumberToLocalizedStringTransformerTest.php | 2 +- ...ercentToLocalizedStringTransformerTest.php | 2 +- .../ValueToDuplicatesTransformerTest.php | 7 +- ...MergeCollectionListenerArrayObjectTest.php | 3 +- .../MergeCollectionListenerArrayTest.php | 3 +- ...ollectionListenerCustomArrayObjectTest.php | 3 +- .../MergeCollectionListenerTestCase.php | 11 +- .../EventListener/ResizeFormListenerTest.php | 12 +-- Tests/Extension/Core/Type/ChoiceTypeTest.php | 19 ++-- .../Core/Type/ChoiceTypeTranslationTest.php | 2 +- .../Extension/Core/Type/DateTimeTypeTest.php | 2 +- Tests/Extension/Core/Type/DateTypeTest.php | 4 +- Tests/Extension/Core/Type/IntegerTypeTest.php | 2 +- Tests/Extension/Core/Type/MoneyTypeTest.php | 2 +- Tests/Extension/Core/Type/NumberTypeTest.php | 2 +- Tests/Extension/Core/Type/PercentTypeTest.php | 2 +- .../Extension/Core/Type/RepeatedTypeTest.php | 5 +- .../CsrfValidationListenerTest.php | 18 ++-- .../Csrf/Type/FormTypeCsrfExtensionTest.php | 5 +- .../DataCollectorExtensionTest.php | 5 +- .../DataCollector/FormDataCollectorTest.php | 35 ++---- .../DataCollector/FormDataExtractorTest.php | 5 +- .../Type/DataCollectorTypeExtensionTest.php | 5 +- ...asswordTypePasswordHasherExtensionTest.php | 5 +- .../FormValidatorFunctionalTest.php | 6 +- .../Constraints/FormValidatorTest.php | 12 +-- .../EventListener/ValidationListenerTest.php | 36 ++----- .../Validator/ValidatorTypeGuesserTest.php | 14 +-- .../ViolationMapper/ViolationMapperTest.php | 29 +---- Tests/Fixtures/CustomArrayObject.php | 2 +- Tests/Fixtures/FixedDataTransformer.php | 2 +- Tests/Fixtures/FixedTranslator.php | 2 +- Tests/Fixtures/Map.php | 2 +- Tests/Fixtures/TestExtension.php | 8 +- Tests/Fixtures/User.php | 2 +- Tests/FormBuilderTest.php | 4 +- Tests/FormFactoryBuilderTest.php | 4 +- Tests/FormFactoryTest.php | 31 ++---- Tests/FormRegistryTest.php | 17 +-- Tests/NativeRequestHandlerTest.php | 2 +- Tests/ResolvedFormTypeTest.php | 51 ++------- Tests/SimpleFormTest.php | 6 +- Tests/Util/ServerParamsTest.php | 2 +- 63 files changed, 176 insertions(+), 559 deletions(-) diff --git a/Test/FormIntegrationTestCase.php b/Test/FormIntegrationTestCase.php index 4feb8df5a6..5bf37fd48a 100644 --- a/Test/FormIntegrationTestCase.php +++ b/Test/FormIntegrationTestCase.php @@ -20,10 +20,7 @@ */ abstract class FormIntegrationTestCase extends TestCase { - /** - * @var FormFactoryInterface - */ - protected $factory; + protected FormFactoryInterface $factory; protected function setUp(): void { diff --git a/Tests/AbstractRequestHandlerTestCase.php b/Tests/AbstractRequestHandlerTestCase.php index becf3504c3..3367d58047 100644 --- a/Tests/AbstractRequestHandlerTestCase.php +++ b/Tests/AbstractRequestHandlerTestCase.php @@ -29,25 +29,16 @@ */ abstract class AbstractRequestHandlerTestCase extends TestCase { - /** - * @var RequestHandlerInterface - */ - protected $requestHandler; - - /** - * @var FormFactory - */ - protected $factory; - + protected RequestHandlerInterface $requestHandler; + protected FormFactory $factory; protected $request; - - protected $serverParams; + protected ServerParams $serverParams; protected function setUp(): void { $this->serverParams = new class() extends ServerParams { - public $contentLength; - public $postMaxSize = ''; + public ?int $contentLength = null; + public string $postMaxSize = ''; public function getContentLength(): ?int { diff --git a/Tests/ChoiceList/AbstractChoiceListTestCase.php b/Tests/ChoiceList/AbstractChoiceListTestCase.php index dd55bfcff0..0b0cb8e79f 100644 --- a/Tests/ChoiceList/AbstractChoiceListTestCase.php +++ b/Tests/ChoiceList/AbstractChoiceListTestCase.php @@ -19,90 +19,23 @@ */ abstract class AbstractChoiceListTestCase extends TestCase { - /** - * @var ChoiceListInterface - */ - protected $list; - - /** - * @var array - */ - protected $choices; - - /** - * @var array - */ - protected $values; - - /** - * @var array - */ - protected $structuredValues; - - /** - * @var array - */ - protected $keys; - - /** - * @var mixed - */ - protected $choice1; - - /** - * @var mixed - */ - protected $choice2; - - /** - * @var mixed - */ - protected $choice3; - - /** - * @var mixed - */ - protected $choice4; - - /** - * @var string - */ - protected $value1; - - /** - * @var string - */ - protected $value2; - - /** - * @var string - */ - protected $value3; - - /** - * @var string - */ - protected $value4; - - /** - * @var string - */ - protected $key1; - - /** - * @var string - */ - protected $key2; - - /** - * @var string - */ - protected $key3; - - /** - * @var string - */ - protected $key4; + protected ChoiceListInterface $list; + protected array $choices; + protected array $values; + protected array $structuredValues; + protected array $keys; + protected mixed $choice1; + protected mixed $choice2; + protected mixed $choice3; + protected mixed $choice4; + protected string $value1; + protected string $value2; + protected string $value3; + protected string $value4; + protected string $key1; + protected string $key2; + protected string $key3; + protected string $key4; protected function setUp(): void { diff --git a/Tests/ChoiceList/ArrayChoiceListTest.php b/Tests/ChoiceList/ArrayChoiceListTest.php index 835085a7ac..f8a6b5b26e 100644 --- a/Tests/ChoiceList/ArrayChoiceListTest.php +++ b/Tests/ChoiceList/ArrayChoiceListTest.php @@ -19,7 +19,7 @@ */ class ArrayChoiceListTest extends AbstractChoiceListTestCase { - private $object; + private \stdClass $object; protected function setUp(): void { diff --git a/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php b/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php index d4231bf946..2668d72edc 100644 --- a/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php +++ b/Tests/ChoiceList/Factory/CachingFactoryDecoratorTest.php @@ -28,10 +28,7 @@ */ class CachingFactoryDecoratorTest extends TestCase { - /** - * @var CachingFactoryDecorator - */ - private $factory; + private CachingFactoryDecorator $factory; protected function setUp(): void { diff --git a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index dfbbd2b5b8..9973c62ae9 100644 --- a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -27,24 +27,12 @@ class DefaultChoiceListFactoryTest extends TestCase { - private $obj1; - - private $obj2; - - private $obj3; - - private $obj4; - - private $obj5; - - private $obj6; - - private $list; - - /** - * @var DefaultChoiceListFactory - */ - private $factory; + private \stdClass $obj1; + private \stdClass $obj2; + private \stdClass $obj3; + private \stdClass $obj4; + private ArrayChoiceList $list; + private DefaultChoiceListFactory $factory; public function getValue($object) { @@ -208,9 +196,9 @@ public function testCreateFromChoicesGroupedValuesAsClosure() public function testCreateFromFilteredChoices() { $list = $this->factory->createListFromChoices( - ['A' => $this->obj1, 'B' => $this->obj2, 'C' => $this->obj3, 'D' => $this->obj4, 'E' => $this->obj5, 'F' => $this->obj6], + ['A' => $this->obj1, 'B' => $this->obj2, 'C' => $this->obj3, 'D' => $this->obj4, 'E' => null, 'F' => null], null, - fn ($choice) => $choice !== $this->obj5 && $choice !== $this->obj6 + fn ($choice) => null !== $choice ); $this->assertObjectListWithGeneratedValues($list); @@ -222,11 +210,11 @@ public function testCreateFromChoicesGroupedAndFiltered() [ 'Group 1' => ['A' => $this->obj1, 'B' => $this->obj2], 'Group 2' => ['C' => $this->obj3, 'D' => $this->obj4], - 'Group 3' => ['E' => $this->obj5, 'F' => $this->obj6], + 'Group 3' => ['E' => null, 'F' => null], 'Group 4' => [/* empty group should be filtered */], ], null, - fn ($choice) => $choice !== $this->obj5 && $choice !== $this->obj6 + fn ($choice) => null !== $choice ); $this->assertObjectListWithGeneratedValues($list); @@ -238,11 +226,11 @@ public function testCreateFromChoicesGroupedAndFilteredTraversable() new \ArrayIterator([ 'Group 1' => ['A' => $this->obj1, 'B' => $this->obj2], 'Group 2' => ['C' => $this->obj3, 'D' => $this->obj4], - 'Group 3' => ['E' => $this->obj5, 'F' => $this->obj6], + 'Group 3' => ['E' => null, 'F' => null], 'Group 4' => [/* empty group should be filtered */], ]), null, - fn ($choice) => $choice !== $this->obj5 && $choice !== $this->obj6 + fn ($choice) => null !== $choice ); $this->assertObjectListWithGeneratedValues($list); @@ -1026,7 +1014,7 @@ private function assertGroupedViewWithChoiceDuplication($view) class DefaultChoiceListFactoryTest_Castable { - private $property; + private string $property; public function __construct($property) { diff --git a/Tests/ChoiceList/Factory/PropertyAccessDecoratorTest.php b/Tests/ChoiceList/Factory/PropertyAccessDecoratorTest.php index 09482fda89..afc83f707f 100644 --- a/Tests/ChoiceList/Factory/PropertyAccessDecoratorTest.php +++ b/Tests/ChoiceList/Factory/PropertyAccessDecoratorTest.php @@ -25,10 +25,7 @@ */ class PropertyAccessDecoratorTest extends TestCase { - /** - * @var PropertyAccessDecorator - */ - private $factory; + private PropertyAccessDecorator $factory; protected function setUp(): void { diff --git a/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php b/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php index e175c58103..d394196ee1 100644 --- a/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php +++ b/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php @@ -21,30 +21,11 @@ */ class CallbackChoiceLoaderTest extends TestCase { - /** - * @var \Symfony\Component\Form\ChoiceList\Loader\CallbackChoiceLoader - */ - private static $loader; - - /** - * @var callable - */ - private static $value; - - /** - * @var array - */ - private static $choices; - - /** - * @var string[] - */ - private static $choiceValues; - - /** - * @var \Symfony\Component\Form\ChoiceList\LazyChoiceList - */ - private static $lazyChoiceList; + private static CallbackChoiceLoader $loader; + private static \Closure $value; + private static array $choices; + private static array $choiceValues = ['choice_one', 'choice_two']; + private static LazyChoiceList $lazyChoiceList; public static function setUpBeforeClass(): void { @@ -54,7 +35,6 @@ public static function setUpBeforeClass(): void (object) ['value' => 'choice_one'], (object) ['value' => 'choice_two'], ]; - self::$choiceValues = ['choice_one', 'choice_two']; self::$lazyChoiceList = new LazyChoiceList(self::$loader, self::$value); } @@ -106,13 +86,4 @@ public function testLoadValuesForChoicesLoadsChoiceListOnFirstCall() 'Choice list should not be reloaded.' ); } - - public static function tearDownAfterClass(): void - { - self::$loader = null; - self::$value = null; - self::$choices = []; - self::$choiceValues = []; - self::$lazyChoiceList = null; - } } diff --git a/Tests/ChoiceList/Loader/IntlCallbackChoiceLoaderTest.php b/Tests/ChoiceList/Loader/IntlCallbackChoiceLoaderTest.php index 0aed92fb5e..2c61388d0e 100644 --- a/Tests/ChoiceList/Loader/IntlCallbackChoiceLoaderTest.php +++ b/Tests/ChoiceList/Loader/IntlCallbackChoiceLoaderTest.php @@ -22,30 +22,11 @@ */ class IntlCallbackChoiceLoaderTest extends TestCase { - /** - * @var \Symfony\Component\Form\ChoiceList\Loader\IntlCallbackChoiceLoader - */ - private static $loader; - - /** - * @var callable - */ - private static $value; - - /** - * @var array - */ - private static $choices; - - /** - * @var string[] - */ - private static $choiceValues; - - /** - * @var \Symfony\Component\Form\ChoiceList\LazyChoiceList - */ - private static $lazyChoiceList; + private static IntlCallbackChoiceLoader $loader; + private static \Closure $value; + private static array $choices; + private static array $choiceValues = ['choice_one', 'choice_two']; + private static LazyChoiceList $lazyChoiceList; public static function setUpBeforeClass(): void { @@ -55,7 +36,6 @@ public static function setUpBeforeClass(): void (object) ['value' => 'choice_one'], (object) ['value' => 'choice_two'], ]; - self::$choiceValues = ['choice_one', 'choice_two']; self::$lazyChoiceList = new LazyChoiceList(self::$loader, self::$value); } @@ -101,13 +81,4 @@ public function testLoadValuesForChoicesLoadsChoiceListOnFirstCall() 'Choice list should not be reloaded.' ); } - - public static function tearDownAfterClass(): void - { - self::$loader = null; - self::$value = null; - self::$choices = []; - self::$choiceValues = []; - self::$lazyChoiceList = null; - } } diff --git a/Tests/CompoundFormTest.php b/Tests/CompoundFormTest.php index 5247cdecdb..daa8cf7c68 100644 --- a/Tests/CompoundFormTest.php +++ b/Tests/CompoundFormTest.php @@ -26,7 +26,6 @@ use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\FormFactory; -use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormRegistry; use Symfony\Component\Form\Forms; @@ -42,15 +41,8 @@ class CompoundFormTest extends TestCase { - /** - * @var FormFactoryInterface - */ - private $factory; - - /** - * @var FormInterface - */ - private $form; + private FormFactory $factory; + private FormInterface $form; protected function setUp(): void { diff --git a/Tests/Console/Descriptor/AbstractDescriptorTestCase.php b/Tests/Console/Descriptor/AbstractDescriptorTestCase.php index 3201ab9f72..fa8745b584 100644 --- a/Tests/Console/Descriptor/AbstractDescriptorTestCase.php +++ b/Tests/Console/Descriptor/AbstractDescriptorTestCase.php @@ -28,7 +28,7 @@ abstract class AbstractDescriptorTestCase extends TestCase { - private $colSize; + private string|false $colSize; protected function setUp(): void { diff --git a/Tests/Extension/Core/DataMapper/DataMapperTest.php b/Tests/Extension/Core/DataMapper/DataMapperTest.php index 7dcf4169ba..fafd0e9d03 100644 --- a/Tests/Extension/Core/DataMapper/DataMapperTest.php +++ b/Tests/Extension/Core/DataMapper/DataMapperTest.php @@ -13,7 +13,6 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\Extension\Core\DataAccessor\PropertyPathAccessor; use Symfony\Component\Form\Extension\Core\DataMapper\DataMapper; use Symfony\Component\Form\Extension\Core\Type\DateType; @@ -26,15 +25,8 @@ class DataMapperTest extends TestCase { - /** - * @var DataMapper - */ - private $mapper; - - /** - * @var EventDispatcherInterface - */ - private $dispatcher; + private DataMapper $mapper; + private EventDispatcher $dispatcher; protected function setUp(): void { @@ -431,7 +423,7 @@ public function isSynchronized(): bool class DummyPerson { - private $name; + private string $name; public function __construct(string $name) { diff --git a/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php b/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php index b82a3a3802..6040792240 100644 --- a/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.php @@ -17,7 +17,7 @@ class ArrayToPartsTransformerTest extends TestCase { - private $transformer; + private ArrayToPartsTransformer $transformer; protected function setUp(): void { @@ -27,11 +27,6 @@ protected function setUp(): void ]); } - protected function tearDown(): void - { - $this->transformer = null; - } - public function testTransform() { $input = [ diff --git a/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php index 98d58c612a..a40a26e54b 100644 --- a/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.php @@ -20,21 +20,13 @@ class BooleanToStringTransformerTest extends TestCase { private const TRUE_VALUE = '1'; - /** - * @var BooleanToStringTransformer - */ - protected $transformer; + protected BooleanToStringTransformer $transformer; protected function setUp(): void { $this->transformer = new BooleanToStringTransformer(self::TRUE_VALUE); } - protected function tearDown(): void - { - $this->transformer = null; - } - public function testTransform() { $this->assertEquals(self::TRUE_VALUE, $this->transformer->transform(true)); diff --git a/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php b/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php index 5253058527..cb2db09462 100644 --- a/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php @@ -18,8 +18,8 @@ class ChoiceToValueTransformerTest extends TestCase { - protected $transformer; - protected $transformerWithNull; + protected ChoiceToValueTransformer $transformer; + protected ChoiceToValueTransformer $transformerWithNull; protected function setUp(): void { @@ -30,12 +30,6 @@ protected function setUp(): void $this->transformerWithNull = new ChoiceToValueTransformer($listWithNull); } - protected function tearDown(): void - { - $this->transformer = null; - $this->transformerWithNull = null; - } - public static function transformProvider() { return [ diff --git a/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php b/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php index d0911673dd..f7233463bd 100644 --- a/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.php @@ -18,8 +18,8 @@ class ChoicesToValuesTransformerTest extends TestCase { - protected $transformer; - protected $transformerWithNull; + protected ChoicesToValuesTransformer $transformer; + protected ChoicesToValuesTransformer $transformerWithNull; protected function setUp(): void { @@ -30,12 +30,6 @@ protected function setUp(): void $this->transformerWithNull = new ChoicesToValuesTransformer($listWithNull); } - protected function tearDown(): void - { - $this->transformer = null; - $this->transformerWithNull = null; - } - public function testTransform() { $in = ['', false, 'X']; diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php index e4e7071478..107d5513d6 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php @@ -21,9 +21,9 @@ class DateTimeToLocalizedStringTransformerTest extends BaseDateTimeTransformerTe { use DateTimeEqualsTrait; - protected $dateTime; - protected $dateTimeWithoutSeconds; - private $defaultLocale; + protected \DateTime $dateTime; + protected \DateTime $dateTimeWithoutSeconds; + private string $defaultLocale; protected function setUp(): void { @@ -47,8 +47,6 @@ protected function setUp(): void protected function tearDown(): void { - $this->dateTime = null; - $this->dateTimeWithoutSeconds = null; \Locale::setDefault($this->defaultLocale); } diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php index 18005e0ed5..f214be450d 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php @@ -20,8 +20,8 @@ class DateTimeToRfc3339TransformerTest extends BaseDateTimeTransformerTestCase { use DateTimeEqualsTrait; - protected $dateTime; - protected $dateTimeWithoutSeconds; + protected \DateTime $dateTime; + protected \DateTime $dateTimeWithoutSeconds; protected function setUp(): void { @@ -31,12 +31,6 @@ protected function setUp(): void $this->dateTimeWithoutSeconds = new \DateTime('2010-02-03 04:05:00 UTC'); } - protected function tearDown(): void - { - $this->dateTime = null; - $this->dateTimeWithoutSeconds = null; - } - public static function allProvider() { return [ diff --git a/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php index 837717670a..513224574a 100644 --- a/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.php @@ -18,7 +18,7 @@ class IntegerToLocalizedStringTransformerTest extends TestCase { - private $defaultLocale; + private string $defaultLocale; protected function setUp(): void { diff --git a/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php index 7f9d436679..2d43e95332 100644 --- a/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php @@ -18,8 +18,8 @@ class MoneyToLocalizedStringTransformerTest extends TestCase { - private $previousLocale; - private $defaultLocale; + private string|false $previousLocale; + private string $defaultLocale; protected function setUp(): void { diff --git a/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php index 9c2e3bcae3..a1dc724fd7 100644 --- a/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.php @@ -18,7 +18,7 @@ class NumberToLocalizedStringTransformerTest extends TestCase { - private $defaultLocale; + private string $defaultLocale; protected function setUp(): void { diff --git a/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php index 59e31101a0..957098ad86 100644 --- a/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.php @@ -18,7 +18,7 @@ class PercentToLocalizedStringTransformerTest extends TestCase { - private $defaultLocale; + private string $defaultLocale; protected function setUp(): void { diff --git a/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php b/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php index fdfd983576..5909a51ef4 100644 --- a/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php @@ -17,18 +17,13 @@ class ValueToDuplicatesTransformerTest extends TestCase { - private $transformer; + private ValueToDuplicatesTransformer $transformer; protected function setUp(): void { $this->transformer = new ValueToDuplicatesTransformer(['a', 'b', 'c']); } - protected function tearDown(): void - { - $this->transformer = null; - } - public function testTransform() { $output = [ diff --git a/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayObjectTest.php b/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayObjectTest.php index 47db5a0acd..80dfa22bd4 100644 --- a/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayObjectTest.php +++ b/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayObjectTest.php @@ -13,6 +13,7 @@ use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Form\FormBuilder; +use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormFactoryBuilder; class MergeCollectionListenerArrayObjectTest extends MergeCollectionListenerTestCase @@ -22,7 +23,7 @@ protected function getData(array $data) return new \ArrayObject($data); } - protected function getBuilder($name = 'name') + protected function getBuilder($name = 'name'): FormBuilderInterface { return new FormBuilder($name, \ArrayObject::class, new EventDispatcher(), (new FormFactoryBuilder())->getFormFactory()); } diff --git a/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayTest.php b/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayTest.php index df382a0b50..9095951748 100644 --- a/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayTest.php +++ b/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayTest.php @@ -13,6 +13,7 @@ use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Form\FormBuilder; +use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormFactoryBuilder; class MergeCollectionListenerArrayTest extends MergeCollectionListenerTestCase @@ -22,7 +23,7 @@ protected function getData(array $data) return $data; } - protected function getBuilder($name = 'name') + protected function getBuilder($name = 'name'): FormBuilderInterface { return new FormBuilder($name, null, new EventDispatcher(), (new FormFactoryBuilder())->getFormFactory()); } diff --git a/Tests/Extension/Core/EventListener/MergeCollectionListenerCustomArrayObjectTest.php b/Tests/Extension/Core/EventListener/MergeCollectionListenerCustomArrayObjectTest.php index a13a6c071a..b57eabc0bb 100644 --- a/Tests/Extension/Core/EventListener/MergeCollectionListenerCustomArrayObjectTest.php +++ b/Tests/Extension/Core/EventListener/MergeCollectionListenerCustomArrayObjectTest.php @@ -13,6 +13,7 @@ use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Form\FormBuilder; +use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormFactoryBuilder; use Symfony\Component\Form\Tests\Fixtures\CustomArrayObject; @@ -23,7 +24,7 @@ protected function getData(array $data) return new CustomArrayObject($data); } - protected function getBuilder($name = 'name') + protected function getBuilder($name = 'name'): FormBuilderInterface { return new FormBuilder($name, 'Symfony\Component\Form\Tests\Fixtures\CustomArrayObject', new EventDispatcher(), (new FormFactoryBuilder())->getFormFactory()); } diff --git a/Tests/Extension/Core/EventListener/MergeCollectionListenerTestCase.php b/Tests/Extension/Core/EventListener/MergeCollectionListenerTestCase.php index 4717ed2789..7070db995b 100644 --- a/Tests/Extension/Core/EventListener/MergeCollectionListenerTestCase.php +++ b/Tests/Extension/Core/EventListener/MergeCollectionListenerTestCase.php @@ -14,23 +14,20 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Extension\Core\EventListener\MergeCollectionListener; +use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormEvent; +use Symfony\Component\Form\FormInterface; abstract class MergeCollectionListenerTestCase extends TestCase { - protected $form; + protected FormInterface $form; protected function setUp(): void { $this->form = $this->getForm('axes'); } - protected function tearDown(): void - { - $this->form = null; - } - - abstract protected function getBuilder($name = 'name'); + abstract protected function getBuilder($name = 'name'): FormBuilderInterface; protected function getForm($name = 'name', $propertyPath = null) { diff --git a/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php b/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php index d42d4d8899..f63a5c1548 100644 --- a/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php +++ b/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php @@ -21,11 +21,13 @@ use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormFactoryBuilder; +use Symfony\Component\Form\FormFactoryInterface; +use Symfony\Component\Form\FormInterface; class ResizeFormListenerTest extends TestCase { - private $factory; - private $form; + private FormFactoryInterface $factory; + private FormInterface $form; protected function setUp(): void { @@ -36,12 +38,6 @@ protected function setUp(): void ->getForm(); } - protected function tearDown(): void - { - $this->factory = null; - $this->form = null; - } - protected function getBuilder($name = 'name') { return new FormBuilder($name, null, new EventDispatcher(), $this->factory); diff --git a/Tests/Extension/Core/Type/ChoiceTypeTest.php b/Tests/Extension/Core/Type/ChoiceTypeTest.php index 11c389551b..8e2372d7e1 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -22,7 +22,7 @@ class ChoiceTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\ChoiceType'; - private $choices = [ + private array $choices = [ 'Bernhard' => 'a', 'Fabien' => 'b', 'Kris' => 'c', @@ -30,19 +30,19 @@ class ChoiceTypeTest extends BaseTypeTestCase 'Roman' => 'e', ]; - private $scalarChoices = [ + private array $scalarChoices = [ 'Yes' => true, 'No' => false, 'n/a' => '', ]; - private $booleanChoicesWithNull = [ + private array $booleanChoicesWithNull = [ 'Yes' => true, 'No' => false, 'n/a' => null, ]; - private $numericChoicesFlipped = [ + private array $numericChoicesFlipped = [ 0 => 'Bernhard', 1 => 'Fabien', 2 => 'Kris', @@ -50,9 +50,9 @@ class ChoiceTypeTest extends BaseTypeTestCase 4 => 'Roman', ]; - private $objectChoices; + private array $objectChoices; - protected $groupedChoices = [ + protected array $groupedChoices = [ 'Symfony' => [ 'Bernhard' => 'a', 'Fabien' => 'b', @@ -77,13 +77,6 @@ protected function setUp(): void ]; } - protected function tearDown(): void - { - parent::tearDown(); - - $this->objectChoices = null; - } - public function testChoicesOptionExpectsArrayOrTraversable() { $this->expectException(InvalidOptionsException::class); diff --git a/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php b/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php index 490e84604a..26055c203c 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php @@ -19,7 +19,7 @@ class ChoiceTypeTranslationTest extends TypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\ChoiceType'; - private $choices = [ + private array $choices = [ 'Bernhard' => 'a', 'Fabien' => 'b', 'Kris' => 'c', diff --git a/Tests/Extension/Core/Type/DateTimeTypeTest.php b/Tests/Extension/Core/Type/DateTimeTypeTest.php index a94f2dff34..95e7901faf 100644 --- a/Tests/Extension/Core/Type/DateTimeTypeTest.php +++ b/Tests/Extension/Core/Type/DateTimeTypeTest.php @@ -21,7 +21,7 @@ class DateTimeTypeTest extends BaseTypeTestCase public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\DateTimeType'; - private $defaultLocale; + private string $defaultLocale; protected function setUp(): void { diff --git a/Tests/Extension/Core/Type/DateTypeTest.php b/Tests/Extension/Core/Type/DateTypeTest.php index bb171ffe88..29cacc2422 100644 --- a/Tests/Extension/Core/Type/DateTypeTest.php +++ b/Tests/Extension/Core/Type/DateTypeTest.php @@ -24,8 +24,8 @@ class DateTypeTest extends BaseTypeTestCase public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\DateType'; - private $defaultTimezone; - private $defaultLocale; + private string $defaultTimezone; + private string $defaultLocale; protected function setUp(): void { diff --git a/Tests/Extension/Core/Type/IntegerTypeTest.php b/Tests/Extension/Core/Type/IntegerTypeTest.php index 6d03ebf6cf..1e143b342f 100644 --- a/Tests/Extension/Core/Type/IntegerTypeTest.php +++ b/Tests/Extension/Core/Type/IntegerTypeTest.php @@ -17,7 +17,7 @@ class IntegerTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\IntegerType'; - private $previousLocale; + private string $previousLocale; protected function setUp(): void { diff --git a/Tests/Extension/Core/Type/MoneyTypeTest.php b/Tests/Extension/Core/Type/MoneyTypeTest.php index c65629d946..b00439b574 100644 --- a/Tests/Extension/Core/Type/MoneyTypeTest.php +++ b/Tests/Extension/Core/Type/MoneyTypeTest.php @@ -17,7 +17,7 @@ class MoneyTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\MoneyType'; - private $defaultLocale; + private string $defaultLocale; protected function setUp(): void { diff --git a/Tests/Extension/Core/Type/NumberTypeTest.php b/Tests/Extension/Core/Type/NumberTypeTest.php index f289fa6978..9efe052219 100644 --- a/Tests/Extension/Core/Type/NumberTypeTest.php +++ b/Tests/Extension/Core/Type/NumberTypeTest.php @@ -19,7 +19,7 @@ class NumberTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\NumberType'; - private $defaultLocale; + private string $defaultLocale; protected function setUp(): void { diff --git a/Tests/Extension/Core/Type/PercentTypeTest.php b/Tests/Extension/Core/Type/PercentTypeTest.php index be92926e0b..76595d79be 100644 --- a/Tests/Extension/Core/Type/PercentTypeTest.php +++ b/Tests/Extension/Core/Type/PercentTypeTest.php @@ -19,7 +19,7 @@ class PercentTypeTest extends TypeTestCase { public const TESTED_TYPE = PercentType::class; - private $defaultLocale; + private string $defaultLocale; protected function setUp(): void { diff --git a/Tests/Extension/Core/Type/RepeatedTypeTest.php b/Tests/Extension/Core/Type/RepeatedTypeTest.php index b2a295b276..06b9151fbe 100644 --- a/Tests/Extension/Core/Type/RepeatedTypeTest.php +++ b/Tests/Extension/Core/Type/RepeatedTypeTest.php @@ -19,10 +19,7 @@ class RepeatedTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\RepeatedType'; - /** - * @var Form - */ - protected $form; + protected Form $form; protected function setUp(): void { diff --git a/Tests/Extension/Csrf/EventListener/CsrfValidationListenerTest.php b/Tests/Extension/Csrf/EventListener/CsrfValidationListenerTest.php index 3d028ac801..6a6a8be9cd 100644 --- a/Tests/Extension/Csrf/EventListener/CsrfValidationListenerTest.php +++ b/Tests/Extension/Csrf/EventListener/CsrfValidationListenerTest.php @@ -18,15 +18,17 @@ use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormFactoryBuilder; +use Symfony\Component\Form\FormFactoryInterface; +use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\Util\ServerParams; use Symfony\Component\Security\Csrf\CsrfTokenManager; class CsrfValidationListenerTest extends TestCase { - protected $dispatcher; - protected $factory; - protected $tokenManager; - protected $form; + protected EventDispatcher $dispatcher; + protected FormFactoryInterface $factory; + protected CsrfTokenManager $tokenManager; + protected FormInterface $form; protected function setUp(): void { @@ -38,14 +40,6 @@ protected function setUp(): void ->getForm(); } - protected function tearDown(): void - { - $this->dispatcher = null; - $this->factory = null; - $this->tokenManager = null; - $this->form = null; - } - protected function getBuilder() { return new FormBuilder('post', null, $this->dispatcher, $this->factory, ['compound' => true]); diff --git a/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php b/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php index 81418527ee..bfa3025554 100644 --- a/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php +++ b/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php @@ -33,10 +33,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void class FormTypeCsrfExtensionTest extends TypeTestCase { - /** - * @var MockObject&CsrfTokenManagerInterface - */ - protected $tokenManager; + protected MockObject&CsrfTokenManagerInterface $tokenManager; protected function setUp(): void { diff --git a/Tests/Extension/DataCollector/DataCollectorExtensionTest.php b/Tests/Extension/DataCollector/DataCollectorExtensionTest.php index 0ae127d077..99e6215cbb 100644 --- a/Tests/Extension/DataCollector/DataCollectorExtensionTest.php +++ b/Tests/Extension/DataCollector/DataCollectorExtensionTest.php @@ -19,10 +19,7 @@ class DataCollectorExtensionTest extends TestCase { - /** - * @var DataCollectorExtension - */ - private $extension; + private DataCollectorExtension $extension; protected function setUp(): void { diff --git a/Tests/Extension/DataCollector/FormDataCollectorTest.php b/Tests/Extension/DataCollector/FormDataCollectorTest.php index fd9870fa6d..798faa0c5e 100644 --- a/Tests/Extension/DataCollector/FormDataCollectorTest.php +++ b/Tests/Extension/DataCollector/FormDataCollectorTest.php @@ -28,35 +28,12 @@ class FormDataCollectorTest extends TestCase { - /** - * @var FormDataCollector - */ - private $dataCollector; - - /** - * @var FormFactory - */ - private $factory; - - /** - * @var Form - */ - private $form; - - /** - * @var Form - */ - private $childForm; - - /** - * @var FormView - */ - private $view; - - /** - * @var FormView - */ - private $childView; + private FormDataCollector $dataCollector; + private FormFactory $factory; + private FormInterface $form; + private FormInterface $childForm; + private FormView $view; + private FormView $childView; protected function setUp(): void { diff --git a/Tests/Extension/DataCollector/FormDataExtractorTest.php b/Tests/Extension/DataCollector/FormDataExtractorTest.php index b496b71fd5..ec01721c70 100644 --- a/Tests/Extension/DataCollector/FormDataExtractorTest.php +++ b/Tests/Extension/DataCollector/FormDataExtractorTest.php @@ -36,10 +36,7 @@ class FormDataExtractorTest extends TestCase { use VarDumperTestTrait; - /** - * @var FormDataExtractor - */ - private $dataExtractor; + private FormDataExtractor $dataExtractor; protected function setUp(): void { diff --git a/Tests/Extension/DataCollector/Type/DataCollectorTypeExtensionTest.php b/Tests/Extension/DataCollector/Type/DataCollectorTypeExtensionTest.php index 1f7d6a817d..7442d181b8 100644 --- a/Tests/Extension/DataCollector/Type/DataCollectorTypeExtensionTest.php +++ b/Tests/Extension/DataCollector/Type/DataCollectorTypeExtensionTest.php @@ -24,10 +24,7 @@ class DataCollectorTypeExtensionTest extends TestCase { - /** - * @var DataCollectorTypeExtension - */ - private $extension; + private DataCollectorTypeExtension $extension; protected function setUp(): void { diff --git a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php index 0b745c172f..4ec91c8274 100644 --- a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php +++ b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php @@ -27,10 +27,7 @@ class PasswordTypePasswordHasherExtensionTest extends TypeTestCase { - /** - * @var MockObject&UserPasswordHasherInterface - */ - protected $passwordHasher; + protected MockObject&UserPasswordHasherInterface $passwordHasher; protected function setUp(): void { diff --git a/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php b/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php index e1698e6b9b..aa6056c137 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php @@ -23,6 +23,7 @@ use Symfony\Component\Form\Extension\Validator\ValidatorExtension; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormFactoryBuilder; +use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Validator\Constraints\Collection; use Symfony\Component\Validator\Constraints\Expression; @@ -34,11 +35,12 @@ use Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory; use Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader; use Symfony\Component\Validator\Validation; +use Symfony\Component\Validator\Validator\ValidatorInterface; class FormValidatorFunctionalTest extends TestCase { - private $validator; - private $formFactory; + private ValidatorInterface $validator; + private FormFactoryInterface $formFactory; protected function setUp(): void { diff --git a/Tests/Extension/Validator/Constraints/FormValidatorTest.php b/Tests/Extension/Validator/Constraints/FormValidatorTest.php index 7d9061c882..180a9578fe 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Constraints; use Symfony\Component\EventDispatcher\EventDispatcher; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataMapper\DataMapper; @@ -39,15 +38,8 @@ */ class FormValidatorTest extends ConstraintValidatorTestCase { - /** - * @var EventDispatcherInterface - */ - private $dispatcher; - - /** - * @var FormFactoryInterface - */ - private $factory; + private EventDispatcher $dispatcher; + private FormFactoryInterface $factory; protected function setUp(): void { diff --git a/Tests/Extension/Validator/EventListener/ValidationListenerTest.php b/Tests/Extension/Validator/EventListener/ValidationListenerTest.php index ba01183915..b3f900e87e 100644 --- a/Tests/Extension/Validator/EventListener/ValidationListenerTest.php +++ b/Tests/Extension/Validator/EventListener/ValidationListenerTest.php @@ -13,7 +13,6 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\Extension\Core\DataMapper\DataMapper; use Symfony\Component\Form\Extension\Validator\Constraints\Form as FormConstraint; use Symfony\Component\Form\Extension\Validator\EventListener\ValidationListener; @@ -23,7 +22,6 @@ use Symfony\Component\Form\FormConfigBuilder; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormFactoryBuilder; -use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Validator\ConstraintViolation; use Symfony\Component\Validator\ConstraintViolationInterface; use Symfony\Component\Validator\ConstraintViolationList; @@ -36,36 +34,14 @@ class ValidationListenerTest extends TestCase { - /** - * @var EventDispatcherInterface - */ - private $dispatcher; - - /** - * @var FormFactoryInterface - */ - private $factory; - - /** - * @var ValidatorInterface - */ - private $validator; - - /** - * @var ValidationListener - */ - private $listener; - - private $message; - - private $messageTemplate; - - private $params; + private ValidatorInterface $validator; + private ValidationListener $listener; + private string $message; + private string $messageTemplate; + private array $params; protected function setUp(): void { - $this->dispatcher = new EventDispatcher(); - $this->factory = (new FormFactoryBuilder())->getFormFactory(); $this->validator = Validation::createValidator(); $this->listener = new ValidationListener($this->validator, new ViolationMapper()); $this->message = 'Message'; @@ -153,7 +129,7 @@ public function isSynchronized(): bool class DummyValidator implements ValidatorInterface { - private $violation; + private ConstraintViolationInterface $violation; public function __construct(ConstraintViolationInterface $violation) { diff --git a/Tests/Extension/Validator/ValidatorTypeGuesserTest.php b/Tests/Extension/Validator/ValidatorTypeGuesserTest.php index 0c8ab23e83..0ac6b39148 100644 --- a/Tests/Extension/Validator/ValidatorTypeGuesserTest.php +++ b/Tests/Extension/Validator/ValidatorTypeGuesserTest.php @@ -42,23 +42,15 @@ class ValidatorTypeGuesserTest extends TestCase { public const TEST_CLASS = 'Symfony\Component\Form\Tests\Extension\Validator\ValidatorTypeGuesserTest_TestClass'; - public const TEST_PROPERTY = 'property'; - /** - * @var ValidatorTypeGuesser - */ - private $guesser; - - /** - * @var ClassMetadata - */ - private $metadata; + private ValidatorTypeGuesser $guesser; + private ClassMetadata $metadata; /** * @var MetadataFactoryInterface */ - private $metadataFactory; + private \Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory $metadataFactory; protected function setUp(): void { diff --git a/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php b/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php index b2c4830555..6cb270ac2e 100644 --- a/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php +++ b/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php @@ -43,30 +43,11 @@ class ViolationMapperTest extends TestCase private const LEVEL_1B = 2; private const LEVEL_2 = 3; - /** - * @var EventDispatcherInterface - */ - private $dispatcher; - - /** - * @var ViolationMapper - */ - private $mapper; - - /** - * @var string - */ - private $message; - - /** - * @var string - */ - private $messageTemplate; - - /** - * @var array - */ - private $params; + private EventDispatcher $dispatcher; + private ViolationMapper $mapper; + private string $message; + private string $messageTemplate; + private array $params; protected function setUp(): void { diff --git a/Tests/Fixtures/CustomArrayObject.php b/Tests/Fixtures/CustomArrayObject.php index 009b79568a..b37bfe5ed2 100644 --- a/Tests/Fixtures/CustomArrayObject.php +++ b/Tests/Fixtures/CustomArrayObject.php @@ -17,7 +17,7 @@ */ class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable { - private $array; + private array $array; public function __construct(array $array = null) { diff --git a/Tests/Fixtures/FixedDataTransformer.php b/Tests/Fixtures/FixedDataTransformer.php index fc99419f55..f3121fc103 100644 --- a/Tests/Fixtures/FixedDataTransformer.php +++ b/Tests/Fixtures/FixedDataTransformer.php @@ -16,7 +16,7 @@ class FixedDataTransformer implements DataTransformerInterface { - private $mapping; + private array $mapping; public function __construct(array $mapping) { diff --git a/Tests/Fixtures/FixedTranslator.php b/Tests/Fixtures/FixedTranslator.php index ba17b5dd3d..1fc0fa9016 100644 --- a/Tests/Fixtures/FixedTranslator.php +++ b/Tests/Fixtures/FixedTranslator.php @@ -15,7 +15,7 @@ class FixedTranslator implements TranslatorInterface { - private $translations; + private array $translations; public function __construct(array $translations) { diff --git a/Tests/Fixtures/Map.php b/Tests/Fixtures/Map.php index d3a9de6f92..ffe89e0875 100644 --- a/Tests/Fixtures/Map.php +++ b/Tests/Fixtures/Map.php @@ -13,7 +13,7 @@ class Map implements \ArrayAccess { - private $data = []; + private array $data = []; public function offsetExists($offset): bool { diff --git a/Tests/Fixtures/TestExtension.php b/Tests/Fixtures/TestExtension.php index 5f6556ca6e..44725a69c7 100644 --- a/Tests/Fixtures/TestExtension.php +++ b/Tests/Fixtures/TestExtension.php @@ -18,11 +18,9 @@ class TestExtension implements FormExtensionInterface { - private $types = []; - - private $extensions = []; - - private $guesser; + private array $types = []; + private array $extensions = []; + private FormTypeGuesserInterface $guesser; public function __construct(FormTypeGuesserInterface $guesser) { diff --git a/Tests/Fixtures/User.php b/Tests/Fixtures/User.php index 486311ee6c..a637a4e1fe 100644 --- a/Tests/Fixtures/User.php +++ b/Tests/Fixtures/User.php @@ -15,7 +15,7 @@ class User implements PasswordAuthenticatedUserInterface { - private $password; + private ?string $password = null; public function getPassword(): ?string { diff --git a/Tests/FormBuilderTest.php b/Tests/FormBuilderTest.php index c08c64867a..023cf77d60 100644 --- a/Tests/FormBuilderTest.php +++ b/Tests/FormBuilderTest.php @@ -27,8 +27,8 @@ class FormBuilderTest extends TestCase { - private $factory; - private $builder; + private FormFactory $factory; + private FormBuilder $builder; protected function setUp(): void { diff --git a/Tests/FormFactoryBuilderTest.php b/Tests/FormFactoryBuilderTest.php index 818ab1b2b1..13e6e30a16 100644 --- a/Tests/FormFactoryBuilderTest.php +++ b/Tests/FormFactoryBuilderTest.php @@ -19,8 +19,8 @@ class FormFactoryBuilderTest extends TestCase { - private $registry; - private $type; + private \ReflectionProperty $registry; + private FooType $type; protected function setUp(): void { diff --git a/Tests/FormFactoryTest.php b/Tests/FormFactoryTest.php index ab13c67775..678e343759 100644 --- a/Tests/FormFactoryTest.php +++ b/Tests/FormFactoryTest.php @@ -31,25 +31,10 @@ */ class FormFactoryTest extends TestCase { - /** - * @var ConfigurableFormTypeGuesser - */ - private $guesser1; - - /** - * @var ConfigurableFormTypeGuesser - */ - private $guesser2; - - /** - * @var FormRegistryInterface - */ - private $registry; - - /** - * @var FormFactory - */ - private $factory; + private ConfigurableFormTypeGuesser $guesser1; + private ConfigurableFormTypeGuesser $guesser2; + private FormRegistry $registry; + private FormFactory $factory; protected function setUp(): void { @@ -189,10 +174,10 @@ public function testCreateBuilderUsesPatternIfFound() class ConfigurableFormTypeGuesser implements FormTypeGuesserInterface { - private $typeGuess; - private $requiredGuess; - private $maxLengthGuess; - private $patternGuess; + private ?\Symfony\Component\Form\Guess\TypeGuess $typeGuess = null; + private ?\Symfony\Component\Form\Guess\ValueGuess $requiredGuess = null; + private ?\Symfony\Component\Form\Guess\ValueGuess $maxLengthGuess = null; + private ?\Symfony\Component\Form\Guess\ValueGuess $patternGuess = null; public function guessType($class, $property): ?TypeGuess { diff --git a/Tests/FormRegistryTest.php b/Tests/FormRegistryTest.php index 8cee7282a4..e2f226924c 100644 --- a/Tests/FormRegistryTest.php +++ b/Tests/FormRegistryTest.php @@ -35,20 +35,9 @@ */ class FormRegistryTest extends TestCase { - /** - * @var FormRegistry - */ - private $registry; - - /** - * @var TestExtension - */ - private $extension1; - - /** - * @var TestExtension - */ - private $extension2; + private FormRegistry $registry; + private TestExtension $extension1; + private TestExtension $extension2; protected function setUp(): void { diff --git a/Tests/NativeRequestHandlerTest.php b/Tests/NativeRequestHandlerTest.php index e698138376..bdb0763f9d 100644 --- a/Tests/NativeRequestHandlerTest.php +++ b/Tests/NativeRequestHandlerTest.php @@ -19,7 +19,7 @@ */ class NativeRequestHandlerTest extends AbstractRequestHandlerTestCase { - private static $serverBackup; + private static array $serverBackup; public static function setUpBeforeClass(): void { diff --git a/Tests/ResolvedFormTypeTest.php b/Tests/ResolvedFormTypeTest.php index ca943fed53..03adb3e0b4 100644 --- a/Tests/ResolvedFormTypeTest.php +++ b/Tests/ResolvedFormTypeTest.php @@ -19,11 +19,8 @@ use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormFactory; -use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormRegistry; -use Symfony\Component\Form\FormTypeExtensionInterface; -use Symfony\Component\Form\FormTypeInterface; use Symfony\Component\Form\FormView; use Symfony\Component\Form\ResolvedFormType; use Symfony\Component\Form\ResolvedFormTypeFactory; @@ -36,42 +33,14 @@ */ class ResolvedFormTypeTest extends TestCase { - private $calls; - - /** - * @var FormTypeInterface - */ - private $parentType; - - /** - * @var FormTypeInterface - */ - private $type; - - /** - * @var FormTypeExtensionInterface - */ - private $extension1; - - /** - * @var FormTypeExtensionInterface - */ - private $extension2; - - /** - * @var ResolvedFormType - */ - private $parentResolvedType; - - /** - * @var ResolvedFormType - */ - private $resolvedType; - - /** - * @var FormFactoryInterface - */ - private $formFactory; + private array $calls; + private UsageTrackingParentFormType $parentType; + private UsageTrackingFormType $type; + private UsageTrackingFormTypeExtension $extension1; + private UsageTrackingFormTypeExtension $extension2; + private ResolvedFormType $parentResolvedType; + private ResolvedFormType $resolvedType; + private FormFactory $formFactory; protected function setUp(): void { @@ -246,7 +215,7 @@ class UsageTrackingFormTypeExtension extends AbstractTypeExtension { use UsageTrackingTrait; - private $defaultOptions; + private array $defaultOptions; public function __construct(array &$calls, array $defaultOptions) { @@ -267,7 +236,7 @@ public static function getExtendedTypes(): iterable trait UsageTrackingTrait { - private $calls; + private array $calls; public function buildForm(FormBuilderInterface $builder, array $options): void { diff --git a/Tests/SimpleFormTest.php b/Tests/SimpleFormTest.php index 1b7af764ad..da01c89cbc 100644 --- a/Tests/SimpleFormTest.php +++ b/Tests/SimpleFormTest.php @@ -38,7 +38,7 @@ class SimpleFormTest_Countable implements \Countable { - private $count; + private int $count; public function __construct($count) { @@ -53,7 +53,7 @@ public function count(): int class SimpleFormTest_Traversable implements \IteratorAggregate { - private $iterator; + private \ArrayIterator $iterator; public function __construct($count) { @@ -68,7 +68,7 @@ public function getIterator(): \Traversable class SimpleFormTest extends TestCase { - private $form; + private Form $form; protected function setUp(): void { diff --git a/Tests/Util/ServerParamsTest.php b/Tests/Util/ServerParamsTest.php index ebe680e710..1904812d81 100644 --- a/Tests/Util/ServerParamsTest.php +++ b/Tests/Util/ServerParamsTest.php @@ -70,7 +70,7 @@ public static function getGetPostMaxSizeTestData() class DummyServerParams extends ServerParams { - private $size; + private string $size; public function __construct($size) { From 76f2f1fc090e5f76cc92690be817d97394bf65cd Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 21 Jul 2023 18:41:43 +0200 Subject: [PATCH 123/208] Add types to private and internal properties --- ChoiceList/View/ChoiceListView.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ChoiceList/View/ChoiceListView.php b/ChoiceList/View/ChoiceListView.php index 8f7a245916..949174e3a7 100644 --- a/ChoiceList/View/ChoiceListView.php +++ b/ChoiceList/View/ChoiceListView.php @@ -28,8 +28,8 @@ class ChoiceListView /** * Creates a new choice list view. * - * @param ChoiceGroupView[]|ChoiceView[] $choices The choice views - * @param ChoiceGroupView[]|ChoiceView[] $preferredChoices the preferred choice views + * @param array $choices The choice views + * @param array $preferredChoices the preferred choice views */ public function __construct(array $choices = [], array $preferredChoices = []) { From 0e73963b2772a2912b3620f7819afd4159042195 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Wed, 26 Jul 2023 17:12:55 +0200 Subject: [PATCH 124/208] More short closures + isset instead of null checks + etc. --- ChoiceList/ArrayChoiceList.php | 2 +- Test/TypeTestCase.php | 7 ------- .../Validator/Constraints/FormValidatorTest.php | 16 ++++++++-------- .../ViolationMapper/ViolationMapperTest.php | 4 ++-- 4 files changed, 11 insertions(+), 18 deletions(-) diff --git a/ChoiceList/ArrayChoiceList.php b/ChoiceList/ArrayChoiceList.php index 2af19b0bf8..4ac7e55fba 100644 --- a/ChoiceList/ArrayChoiceList.php +++ b/ChoiceList/ArrayChoiceList.php @@ -69,7 +69,7 @@ public function __construct(iterable $choices, callable $value = null) if (null !== $value) { // If a deterministic value generator was passed, use it later - $this->valueCallback = $value; + $this->valueCallback = $value(...); } else { // Otherwise generate incrementing integers as values $value = static function () { diff --git a/Test/TypeTestCase.php b/Test/TypeTestCase.php index a925c555ec..ac8eb9baa4 100644 --- a/Test/TypeTestCase.php +++ b/Test/TypeTestCase.php @@ -35,13 +35,6 @@ protected function setUp(): void $this->builder = new FormBuilder('', null, $this->dispatcher, $this->factory); } - protected function tearDown(): void - { - if (\in_array(ValidatorExtensionTrait::class, class_uses($this))) { - $this->validator = null; - } - } - protected function getExtensions() { $extensions = []; diff --git a/Tests/Extension/Validator/Constraints/FormValidatorTest.php b/Tests/Extension/Validator/Constraints/FormValidatorTest.php index 180a9578fe..e26d31299c 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorTest.php @@ -264,8 +264,8 @@ public function testDontValidateIfNotSynchronized() ]) ->setData($object) ->addViewTransformer(new CallbackTransformer( - fn ($data) => $data, - function () { throw new TransformationFailedException(); } + static fn ($data) => $data, + static fn () => throw new TransformationFailedException() )) ->getForm(); @@ -301,8 +301,8 @@ public function testAddInvalidErrorEvenIfNoValidationGroups() ]) ->setData($object) ->addViewTransformer(new CallbackTransformer( - fn ($data) => $data, - function () { throw new TransformationFailedException(); } + static fn ($data) => $data, + static fn () => throw new TransformationFailedException() )) ->getForm(); @@ -336,8 +336,8 @@ public function testDontValidateConstraintsIfNotSynchronized() $form = $this->getBuilder('name', '\stdClass', $options) ->setData($object) ->addViewTransformer(new CallbackTransformer( - fn ($data) => $data, - function () { throw new TransformationFailedException(); } + static fn ($data) => $data, + static fn () => throw new TransformationFailedException() )) ->getForm(); @@ -367,8 +367,8 @@ public function testTransformationFailedExceptionInvalidMessageIsUsed() ]) ->setData($object) ->addViewTransformer(new CallbackTransformer( - fn ($data) => $data, - function () { + static fn ($data) => $data, + static function () { $failure = new TransformationFailedException(); $failure->setInvalidMessage('safe message to be used', ['{{ bar }}' => 'bar']); diff --git a/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php b/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php index 6cb270ac2e..93ad47b196 100644 --- a/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php +++ b/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php @@ -72,8 +72,8 @@ protected function getForm($name = 'name', $propertyPath = null, $dataClass = nu if (!$synchronized) { $config->addViewTransformer(new CallbackTransformer( - fn ($normData) => $normData, - function () { throw new TransformationFailedException(); } + static fn ($normData) => $normData, + static fn () => throw new TransformationFailedException() )); } From f707676df8620cb1d3285f09bfdcff5957106321 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 27 Jul 2023 11:02:28 +0200 Subject: [PATCH 125/208] Ensure all properties have a type --- Console/Descriptor/Descriptor.php | 18 ++++++++---------- Tests/AbstractRequestHandlerTestCase.php | 2 +- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/Console/Descriptor/Descriptor.php b/Console/Descriptor/Descriptor.php index 3c54545cf1..b8d0399ee1 100644 --- a/Console/Descriptor/Descriptor.php +++ b/Console/Descriptor/Descriptor.php @@ -29,16 +29,14 @@ */ abstract class Descriptor implements DescriptorInterface { - /** @var OutputStyle */ - protected $output; - protected $type; - protected $ownOptions = []; - protected $overriddenOptions = []; - protected $parentOptions = []; - protected $extensionOptions = []; - protected $requiredOptions = []; - protected $parents = []; - protected $extensions = []; + protected OutputStyle $output; + protected array $ownOptions = []; + protected array $overriddenOptions = []; + protected array $parentOptions = []; + protected array $extensionOptions = []; + protected array $requiredOptions = []; + protected array $parents = []; + protected array $extensions = []; public function describe(OutputInterface $output, ?object $object, array $options = []): void { diff --git a/Tests/AbstractRequestHandlerTestCase.php b/Tests/AbstractRequestHandlerTestCase.php index 3367d58047..c21dcd6a2f 100644 --- a/Tests/AbstractRequestHandlerTestCase.php +++ b/Tests/AbstractRequestHandlerTestCase.php @@ -31,7 +31,7 @@ abstract class AbstractRequestHandlerTestCase extends TestCase { protected RequestHandlerInterface $requestHandler; protected FormFactory $factory; - protected $request; + protected mixed $request = null; protected ServerParams $serverParams; protected function setUp(): void From e1d7b9d9abf255dd908cd5d9b9de1a6a90c686d7 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 21 Jul 2023 15:36:26 +0200 Subject: [PATCH 126/208] Add types to public and protected properties --- AbstractRendererEngine.php | 11 ++++------- ButtonBuilder.php | 2 +- ChoiceList/ArrayChoiceList.php | 17 ++++------------- ChoiceList/View/ChoiceGroupView.php | 4 ++-- ChoiceList/View/ChoiceListView.php | 4 ++-- ChoiceList/View/ChoiceView.php | 10 +++++----- .../DataTransformer/BaseDateTimeTransformer.php | 7 +++---- .../DataTransformer/DataTransformerChain.php | 2 +- .../NumberToLocalizedStringTransformer.php | 5 ++--- .../PercentToLocalizedStringTransformer.php | 2 +- .../Core/EventListener/ResizeFormListener.php | 10 +++++----- Extension/Core/Type/MoneyType.php | 2 +- FormConfigBuilder.php | 5 ++--- FormError.php | 6 +++--- FormEvent.php | 3 ++- FormView.php | 6 +++--- ReversedTransformer.php | 2 +- Test/FormPerformanceTestCase.php | 5 +---- Test/Traits/ValidatorExtensionTrait.php | 5 +---- Test/TypeTestCase.php | 11 ++--------- 20 files changed, 46 insertions(+), 73 deletions(-) diff --git a/AbstractRendererEngine.php b/AbstractRendererEngine.php index cd7215025a..bccdf69cc5 100644 --- a/AbstractRendererEngine.php +++ b/AbstractRendererEngine.php @@ -25,25 +25,22 @@ abstract class AbstractRendererEngine implements FormRendererEngineInterface, Re */ public const CACHE_KEY_VAR = 'cache_key'; - /** - * @var array - */ - protected $defaultThemes; + protected array $defaultThemes; /** * @var array[] */ - protected $themes = []; + protected array $themes = []; /** * @var bool[] */ - protected $useDefaultThemes = []; + protected array $useDefaultThemes = []; /** * @var array[] */ - protected $resources = []; + protected array $resources = []; /** * @var array> diff --git a/ButtonBuilder.php b/ButtonBuilder.php index f9a6142dbf..e640149bb8 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -25,7 +25,7 @@ */ class ButtonBuilder implements \IteratorAggregate, FormBuilderInterface { - protected $locked = false; + protected bool $locked = false; private bool $disabled = false; private ResolvedFormTypeInterface $type; diff --git a/ChoiceList/ArrayChoiceList.php b/ChoiceList/ArrayChoiceList.php index 4ac7e55fba..5f0d7dc36e 100644 --- a/ChoiceList/ArrayChoiceList.php +++ b/ChoiceList/ArrayChoiceList.php @@ -24,27 +24,18 @@ */ class ArrayChoiceList implements ChoiceListInterface { - /** - * The choices in the list. - * - * @var array - */ - protected $choices; + protected array $choices; /** * The values indexed by the original keys. - * - * @var array */ - protected $structuredValues; + protected array $structuredValues; /** * The original keys of the choices array. - * - * @var int[]|string[] */ - protected $originalKeys; - protected $valueCallback; + protected array $originalKeys; + protected ?\Closure $valueCallback = null; /** * Creates a list with the given choices and values. diff --git a/ChoiceList/View/ChoiceGroupView.php b/ChoiceList/View/ChoiceGroupView.php index 64fe3baec3..562515012c 100644 --- a/ChoiceList/View/ChoiceGroupView.php +++ b/ChoiceList/View/ChoiceGroupView.php @@ -20,8 +20,8 @@ */ class ChoiceGroupView implements \IteratorAggregate { - public $label; - public $choices; + public string $label; + public array $choices; /** * Creates a new choice group view. diff --git a/ChoiceList/View/ChoiceListView.php b/ChoiceList/View/ChoiceListView.php index 949174e3a7..15afc4a8a5 100644 --- a/ChoiceList/View/ChoiceListView.php +++ b/ChoiceList/View/ChoiceListView.php @@ -22,8 +22,8 @@ */ class ChoiceListView { - public $choices; - public $preferredChoices; + public array $choices; + public array $preferredChoices; /** * Creates a new choice list view. diff --git a/ChoiceList/View/ChoiceView.php b/ChoiceList/View/ChoiceView.php index 050d8ed243..52587fd363 100644 --- a/ChoiceList/View/ChoiceView.php +++ b/ChoiceList/View/ChoiceView.php @@ -20,19 +20,19 @@ */ class ChoiceView { - public $label; - public $value; - public $data; + public string|TranslatableInterface|false $label; + public string $value; + public mixed $data; /** * Additional attributes for the HTML tag. */ - public $attr; + public array $attr; /** * Additional parameters used to translate the label. */ - public $labelTranslationParameters; + public array $labelTranslationParameters; /** * Creates a new choice view. diff --git a/Extension/Core/DataTransformer/BaseDateTimeTransformer.php b/Extension/Core/DataTransformer/BaseDateTimeTransformer.php index c12a6de216..d2a8974714 100644 --- a/Extension/Core/DataTransformer/BaseDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/BaseDateTimeTransformer.php @@ -21,7 +21,7 @@ */ abstract class BaseDateTimeTransformer implements DataTransformerInterface { - protected static $formats = [ + protected static array $formats = [ \IntlDateFormatter::NONE, \IntlDateFormatter::FULL, \IntlDateFormatter::LONG, @@ -29,9 +29,8 @@ abstract class BaseDateTimeTransformer implements DataTransformerInterface \IntlDateFormatter::SHORT, ]; - protected $inputTimezone; - - protected $outputTimezone; + protected string $inputTimezone; + protected string $outputTimezone; /** * @param string|null $inputTimezone The name of the input timezone diff --git a/Extension/Core/DataTransformer/DataTransformerChain.php b/Extension/Core/DataTransformer/DataTransformerChain.php index 41b93e56a7..ec5def4695 100644 --- a/Extension/Core/DataTransformer/DataTransformerChain.php +++ b/Extension/Core/DataTransformer/DataTransformerChain.php @@ -21,7 +21,7 @@ */ class DataTransformerChain implements DataTransformerInterface { - protected $transformers; + protected array $transformers; /** * Uses the given value transformers to transform values. diff --git a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index 5ab33b4c94..911246782d 100644 --- a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -25,9 +25,8 @@ */ class NumberToLocalizedStringTransformer implements DataTransformerInterface { - protected $grouping; - - protected $roundingMode; + protected bool $grouping; + protected int $roundingMode; private ?int $scale; private ?string $locale; diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index 7bea4d227c..0915021d3b 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -28,7 +28,7 @@ class PercentToLocalizedStringTransformer implements DataTransformerInterface public const FRACTIONAL = 'fractional'; public const INTEGER = 'integer'; - protected static $types = [ + protected static array $types = [ self::FRACTIONAL, self::INTEGER, ]; diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index f5901f1ed9..482007d53b 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -24,11 +24,11 @@ */ class ResizeFormListener implements EventSubscriberInterface { - protected $type; - protected $options; - protected $prototypeOptions; - protected $allowAdd; - protected $allowDelete; + protected string $type; + protected array $options; + protected array $prototypeOptions; + protected bool $allowAdd; + protected bool $allowDelete; private \Closure|bool $deleteEmpty; diff --git a/Extension/Core/Type/MoneyType.php b/Extension/Core/Type/MoneyType.php index 837d9ade42..c82911a216 100644 --- a/Extension/Core/Type/MoneyType.php +++ b/Extension/Core/Type/MoneyType.php @@ -22,7 +22,7 @@ class MoneyType extends AbstractType { - protected static $patterns = []; + protected static array $patterns = []; public function buildForm(FormBuilderInterface $builder, array $options): void { diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index ef10087b80..49aa89ab04 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -26,14 +26,13 @@ */ class FormConfigBuilder implements FormConfigBuilderInterface { + protected bool $locked = false; + /** * Caches a globally unique {@link NativeRequestHandler} instance. */ private static NativeRequestHandler $nativeRequestHandler; - /** @var bool */ - protected $locked = false; - private EventDispatcherInterface $dispatcher; private string $name; private ?PropertyPathInterface $propertyPath = null; diff --git a/FormError.php b/FormError.php index 632d839ea2..face43bcef 100644 --- a/FormError.php +++ b/FormError.php @@ -20,9 +20,9 @@ */ class FormError { - protected $messageTemplate; - protected $messageParameters; - protected $messagePluralization; + protected string $messageTemplate; + protected array $messageParameters; + protected ?int $messagePluralization; private string $message; private mixed $cause; diff --git a/FormEvent.php b/FormEvent.php index cedf2ea2e7..e46fbb6a6a 100644 --- a/FormEvent.php +++ b/FormEvent.php @@ -18,8 +18,9 @@ */ class FormEvent extends Event { + protected mixed $data; + private FormInterface $form; - protected $data; public function __construct(FormInterface $form, mixed $data) { diff --git a/FormView.php b/FormView.php index 746d1d2ee4..e9e9e9957b 100644 --- a/FormView.php +++ b/FormView.php @@ -24,7 +24,7 @@ class FormView implements \ArrayAccess, \IteratorAggregate, \Countable /** * The variables assigned to this view. */ - public $vars = [ + public array $vars = [ 'value' => null, 'attr' => [], ]; @@ -32,14 +32,14 @@ class FormView implements \ArrayAccess, \IteratorAggregate, \Countable /** * The parent view. */ - public $parent; + public ?self $parent = null; /** * The child views. * * @var array */ - public $children = []; + public array $children = []; /** * Is the form attached to this renderer rendered? diff --git a/ReversedTransformer.php b/ReversedTransformer.php index 8572672369..b683879080 100644 --- a/ReversedTransformer.php +++ b/ReversedTransformer.php @@ -21,7 +21,7 @@ */ class ReversedTransformer implements DataTransformerInterface { - protected $reversedTransformer; + protected DataTransformerInterface $reversedTransformer; public function __construct(DataTransformerInterface $reversedTransformer) { diff --git a/Test/FormPerformanceTestCase.php b/Test/FormPerformanceTestCase.php index 16894bea0c..f398d3e72c 100644 --- a/Test/FormPerformanceTestCase.php +++ b/Test/FormPerformanceTestCase.php @@ -25,10 +25,7 @@ abstract class FormPerformanceTestCase extends FormIntegrationTestCase { use VersionAwareTest; - /** - * @var int - */ - protected $maxRunningTime = 0; + protected int $maxRunningTime = 0; protected function runTest() { diff --git a/Test/Traits/ValidatorExtensionTrait.php b/Test/Traits/ValidatorExtensionTrait.php index 7213719969..0b2c1e90da 100644 --- a/Test/Traits/ValidatorExtensionTrait.php +++ b/Test/Traits/ValidatorExtensionTrait.php @@ -19,10 +19,7 @@ trait ValidatorExtensionTrait { - /** - * @var ValidatorInterface|null - */ - protected $validator; + protected ValidatorInterface $validator; protected function getValidatorExtension(): ValidatorExtension { diff --git a/Test/TypeTestCase.php b/Test/TypeTestCase.php index ac8eb9baa4..5d4c2ba9c6 100644 --- a/Test/TypeTestCase.php +++ b/Test/TypeTestCase.php @@ -17,15 +17,8 @@ abstract class TypeTestCase extends FormIntegrationTestCase { - /** - * @var FormBuilder - */ - protected $builder; - - /** - * @var EventDispatcherInterface - */ - protected $dispatcher; + protected FormBuilder $builder; + protected EventDispatcherInterface $dispatcher; protected function setUp(): void { From 81bc4abaaed8c172778a977e9733df4520eb7544 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Fri, 28 Jul 2023 16:03:16 +0200 Subject: [PATCH 127/208] Use Stringable interface as much as possible --- FormErrorIterator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FormErrorIterator.php b/FormErrorIterator.php index ae265cf598..42de0c8358 100644 --- a/FormErrorIterator.php +++ b/FormErrorIterator.php @@ -35,7 +35,7 @@ * @implements \RecursiveIterator * @implements \SeekableIterator */ -class FormErrorIterator implements \RecursiveIterator, \SeekableIterator, \ArrayAccess, \Countable +class FormErrorIterator implements \RecursiveIterator, \SeekableIterator, \ArrayAccess, \Countable, \Stringable { /** * The prefix used for indenting nested error messages. From 45b1b17a78d46c1a2a3b7c02cbf3cc353e9ebaa1 Mon Sep 17 00:00:00 2001 From: HypeMC Date: Mon, 31 Jul 2023 06:20:09 +0200 Subject: [PATCH 128/208] Add some PHPDoc --- Extension/DependencyInjection/DependencyInjectionExtension.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Extension/DependencyInjection/DependencyInjectionExtension.php b/Extension/DependencyInjection/DependencyInjectionExtension.php index d7c9346889..6564bd5657 100644 --- a/Extension/DependencyInjection/DependencyInjectionExtension.php +++ b/Extension/DependencyInjection/DependencyInjectionExtension.php @@ -14,6 +14,7 @@ use Psr\Container\ContainerInterface; use Symfony\Component\Form\Exception\InvalidArgumentException; use Symfony\Component\Form\FormExtensionInterface; +use Symfony\Component\Form\FormTypeExtensionInterface; use Symfony\Component\Form\FormTypeGuesserChain; use Symfony\Component\Form\FormTypeGuesserInterface; use Symfony\Component\Form\FormTypeInterface; @@ -27,7 +28,7 @@ class DependencyInjectionExtension implements FormExtensionInterface private iterable $guesserServices; /** - * @param iterable[] $typeExtensionServices + * @param array> $typeExtensionServices */ public function __construct(ContainerInterface $typeContainer, array $typeExtensionServices, iterable $guesserServices) { From e3042b6844a7a29ec2d6afeccc87d8230b6da5cd Mon Sep 17 00:00:00 2001 From: Jules Pietri Date: Thu, 20 Jul 2023 13:12:56 +0200 Subject: [PATCH 129/208] [Form][DX] Use logical ordering for type and extension methods --- AbstractType.php | 22 +++++++++++----------- AbstractTypeExtension.php | 8 ++++---- FormTypeExtensionInterface.php | 24 ++++++++++++------------ FormTypeInterface.php | 31 +++++++++++++++++-------------- 4 files changed, 44 insertions(+), 41 deletions(-) diff --git a/AbstractType.php b/AbstractType.php index ad4b195696..8fffa379d8 100644 --- a/AbstractType.php +++ b/AbstractType.php @@ -21,46 +21,46 @@ abstract class AbstractType implements FormTypeInterface { /** - * @return void + * @return string|null */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function getParent() { + return FormType::class; } /** * @return void */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function configureOptions(OptionsResolver $resolver) { } /** * @return void */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function buildForm(FormBuilderInterface $builder, array $options) { } /** * @return void */ - public function configureOptions(OptionsResolver $resolver) + public function buildView(FormView $view, FormInterface $form, array $options) { } /** - * @return string + * @return void */ - public function getBlockPrefix() + public function finishView(FormView $view, FormInterface $form, array $options) { - return StringUtil::fqcnToBlockPrefix(static::class) ?: ''; } /** - * @return string|null + * @return string */ - public function getParent() + public function getBlockPrefix() { - return FormType::class; + return StringUtil::fqcnToBlockPrefix(static::class) ?: ''; } } diff --git a/AbstractTypeExtension.php b/AbstractTypeExtension.php index 422f28bf33..1956bd00a7 100644 --- a/AbstractTypeExtension.php +++ b/AbstractTypeExtension.php @@ -21,28 +21,28 @@ abstract class AbstractTypeExtension implements FormTypeExtensionInterface /** * @return void */ - public function buildForm(FormBuilderInterface $builder, array $options) + public function configureOptions(OptionsResolver $resolver) { } /** * @return void */ - public function buildView(FormView $view, FormInterface $form, array $options) + public function buildForm(FormBuilderInterface $builder, array $options) { } /** * @return void */ - public function finishView(FormView $view, FormInterface $form, array $options) + public function buildView(FormView $view, FormInterface $form, array $options) { } /** * @return void */ - public function configureOptions(OptionsResolver $resolver) + public function finishView(FormView $view, FormInterface $form, array $options) { } } diff --git a/FormTypeExtensionInterface.php b/FormTypeExtensionInterface.php index 1937834515..ae76457cd6 100644 --- a/FormTypeExtensionInterface.php +++ b/FormTypeExtensionInterface.php @@ -18,6 +18,18 @@ */ interface FormTypeExtensionInterface { + /** + * Gets the extended types. + * + * @return string[] + */ + public static function getExtendedTypes(): iterable; + + /** + * @return void + */ + public function configureOptions(OptionsResolver $resolver); + /** * Builds the form. * @@ -59,16 +71,4 @@ public function buildView(FormView $view, FormInterface $form, array $options); * @see FormTypeInterface::finishView() */ public function finishView(FormView $view, FormInterface $form, array $options); - - /** - * @return void - */ - public function configureOptions(OptionsResolver $resolver); - - /** - * Gets the extended types. - * - * @return string[] - */ - public static function getExtendedTypes(): iterable; } diff --git a/FormTypeInterface.php b/FormTypeInterface.php index 0c586d3f71..2bc9f7711e 100644 --- a/FormTypeInterface.php +++ b/FormTypeInterface.php @@ -18,6 +18,23 @@ */ interface FormTypeInterface { + /** + * Returns the name of the parent type. + * + * The parent type and its extensions will configure the form with the + * following methods before the current implementation. + * + * @return string|null + */ + public function getParent(); + + /** + * Configures the options for this type. + * + * @return void + */ + public function configureOptions(OptionsResolver $resolver); + /** * Builds the form. * @@ -69,13 +86,6 @@ public function buildView(FormView $view, FormInterface $form, array $options); */ public function finishView(FormView $view, FormInterface $form, array $options); - /** - * Configures the options for this type. - * - * @return void - */ - public function configureOptions(OptionsResolver $resolver); - /** * Returns the prefix of the template block name for this type. * @@ -85,11 +95,4 @@ public function configureOptions(OptionsResolver $resolver); * @return string */ public function getBlockPrefix(); - - /** - * Returns the name of the parent type. - * - * @return string|null - */ - public function getParent(); } From f8f1127fec670d592e6b47b7c01ffc5ecf691ca7 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 8 Aug 2023 11:09:50 +0200 Subject: [PATCH 130/208] Remove unneeded calls to setPublic(false) --- Tests/DependencyInjection/FormPassTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/DependencyInjection/FormPassTest.php b/Tests/DependencyInjection/FormPassTest.php index c2beee8747..e9a7b50346 100644 --- a/Tests/DependencyInjection/FormPassTest.php +++ b/Tests/DependencyInjection/FormPassTest.php @@ -64,8 +64,8 @@ public function testAddTaggedTypes() (new Definition(ServiceLocator::class, [[ __CLASS__.'_Type1' => new ServiceClosureArgument(new Reference('my.type1')), __CLASS__.'_Type2' => new ServiceClosureArgument(new Reference('my.type2')), - ]]))->addTag('container.service_locator')->setPublic(false), - $locator->setPublic(false) + ]]))->addTag('container.service_locator'), + $locator ); } From f389e4a7cc2e807b53ff8498d8abe61cdc32447a Mon Sep 17 00:00:00 2001 From: Jules Pietri Date: Sun, 20 Aug 2023 12:33:56 +0200 Subject: [PATCH 131/208] [Form] use `never` return type in form events --- Event/PostSetDataEvent.php | 2 +- Event/PostSubmitEvent.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Event/PostSetDataEvent.php b/Event/PostSetDataEvent.php index 74aeb78d50..5b6430a81d 100644 --- a/Event/PostSetDataEvent.php +++ b/Event/PostSetDataEvent.php @@ -22,7 +22,7 @@ */ final class PostSetDataEvent extends FormEvent { - public function setData(mixed $data): void + public function setData(mixed $data): never { throw new BadMethodCallException('Form data cannot be changed during "form.post_set_data", you should use "form.pre_set_data" instead.'); } diff --git a/Event/PostSubmitEvent.php b/Event/PostSubmitEvent.php index 104ea2d0ec..88cd5c4eb1 100644 --- a/Event/PostSubmitEvent.php +++ b/Event/PostSubmitEvent.php @@ -22,7 +22,7 @@ */ final class PostSubmitEvent extends FormEvent { - public function setData(mixed $data): void + public function setData(mixed $data): never { throw new BadMethodCallException('Form data cannot be changed during "form.post_submit", you should use "form.pre_submit" or "form.submit" instead.'); } From a6abf16cdeb22c43c9bbe9df2e7756763a3e5180 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 25 Sep 2023 14:52:38 +0200 Subject: [PATCH 132/208] Minor CS fixes --- .../Extension/Validator/ViolationMapper/ViolationMapperTest.php | 1 - Tests/FormFactoryTest.php | 1 - 2 files changed, 2 deletions(-) diff --git a/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php b/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php index 93ad47b196..0aeb35adcc 100644 --- a/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php +++ b/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php @@ -13,7 +13,6 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataMapper\DataMapper; diff --git a/Tests/FormFactoryTest.php b/Tests/FormFactoryTest.php index 678e343759..bb18464c78 100644 --- a/Tests/FormFactoryTest.php +++ b/Tests/FormFactoryTest.php @@ -16,7 +16,6 @@ use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormFactory; use Symfony\Component\Form\FormRegistry; -use Symfony\Component\Form\FormRegistryInterface; use Symfony\Component\Form\FormTypeGuesserChain; use Symfony\Component\Form\FormTypeGuesserInterface; use Symfony\Component\Form\Guess\Guess; From 9a7d14fa98728fbef0773bbe6ca58eebbb1038f7 Mon Sep 17 00:00:00 2001 From: HypeMC Date: Fri, 29 Sep 2023 05:03:43 +0200 Subject: [PATCH 133/208] [FrameworkBundle][WebProfilerBundle][Console][Form][HttpKernel][PropertyInfo][Validator] Remove optional before required param --- Extension/DataCollector/FormDataCollector.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index 0ac99e3729..dab72bb309 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -259,7 +259,7 @@ private function &recursiveBuildPreliminaryFormTree(FormInterface $form, array & return $output; } - private function &recursiveBuildFinalFormTree(FormInterface $form = null, FormView $view, array &$outputByHash): array + private function &recursiveBuildFinalFormTree(?FormInterface $form, FormView $view, array &$outputByHash): array { $viewHash = spl_object_hash($view); $formHash = null; From ceb820cde9a68c89781042b12829c2febba07ed1 Mon Sep 17 00:00:00 2001 From: Arnaud De Abreu Date: Tue, 11 Jul 2023 11:43:37 +0200 Subject: [PATCH 134/208] [Form] Add `duplicate_preferred_choices` option to `ChoiceType` --- CHANGELOG.md | 2 + .../Factory/CachingFactoryDecorator.php | 14 +++++-- .../Factory/ChoiceListFactoryInterface.php | 5 ++- .../Factory/DefaultChoiceListFactory.php | 38 +++++++++++++------ .../Factory/PropertyAccessDecorator.php | 9 ++++- Extension/Core/Type/ChoiceType.php | 5 ++- .../Descriptor/resolved_form_type_1.json | 1 + .../Descriptor/resolved_form_type_1.txt | 14 +++---- 8 files changed, 61 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3918636e56..9fba1a3f5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ CHANGELOG `model_timezone` option in `DateType`, `DateTimeType`, and `TimeType` * Deprecate `PostSetDataEvent::setData()`, use `PreSetDataEvent::setData()` instead * Deprecate `PostSubmitEvent::setData()`, use `PreSubmitDataEvent::setData()` or `SubmitDataEvent::setData()` instead + * Add `duplicate_preferred_choices` option in `ChoiceType` + * Add `$duplicatePreferredChoices` parameter to `ChoiceListFactoryInterface::createView()` 6.3 --- diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index 40c0604ea4..03bdff5dc9 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -145,8 +145,12 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value return $this->lists[$hash]; } - public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []): ChoiceListView + /** + * @param bool $duplicatePreferredChoices + */ + public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []/* , bool $duplicatePreferredChoices = true */): ChoiceListView { + $duplicatePreferredChoices = \func_num_args() > 7 ? func_get_arg(7) : true; $cache = true; if ($preferredChoices instanceof Cache\PreferredChoice) { @@ -193,11 +197,12 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = $index, $groupBy, $attr, - $labelTranslationParameters + $labelTranslationParameters, + $duplicatePreferredChoices, ); } - $hash = self::generateHash([$list, $preferredChoices, $label, $index, $groupBy, $attr, $labelTranslationParameters]); + $hash = self::generateHash([$list, $preferredChoices, $label, $index, $groupBy, $attr, $labelTranslationParameters, $duplicatePreferredChoices]); if (!isset($this->views[$hash])) { $this->views[$hash] = $this->decoratedFactory->createView( @@ -207,7 +212,8 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = $index, $groupBy, $attr, - $labelTranslationParameters + $labelTranslationParameters, + $duplicatePreferredChoices, ); } diff --git a/ChoiceList/Factory/ChoiceListFactoryInterface.php b/ChoiceList/Factory/ChoiceListFactoryInterface.php index 62c3e8d2ea..89633710b6 100644 --- a/ChoiceList/Factory/ChoiceListFactoryInterface.php +++ b/ChoiceList/Factory/ChoiceListFactoryInterface.php @@ -77,6 +77,9 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $va * pass false to discard the label * @param array|callable|null $attr The callable generating the HTML attributes * @param array|callable $labelTranslationParameters The parameters used to translate the choice labels + * @param bool $duplicatePreferredChoices Whether the preferred choices should be duplicated + * on top of the list and in their original position + * or only in the top of the list */ - public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []): ChoiceListView; + public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []/* , bool $duplicatePreferredChoices = true */): ChoiceListView; } diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index fb30fc6ded..aa371362c8 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -52,8 +52,12 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $va return new LazyChoiceList($loader, $value); } - public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []): ChoiceListView + /** + * @param bool $duplicatePreferredChoices + */ + public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []/* , bool $duplicatePreferredChoices = true */): ChoiceListView { + $duplicatePreferredChoices = \func_num_args() > 7 ? func_get_arg(7) : true; $preferredViews = []; $preferredViewsOrder = []; $otherViews = []; @@ -92,7 +96,8 @@ public function createView(ChoiceListInterface $list, array|callable $preferredC $preferredChoices, $preferredViews, $preferredViewsOrder, - $otherViews + $otherViews, + $duplicatePreferredChoices, ); } @@ -130,7 +135,8 @@ public function createView(ChoiceListInterface $list, array|callable $preferredC $preferredChoices, $preferredViews, $preferredViewsOrder, - $otherViews + $otherViews, + $duplicatePreferredChoices, ); } @@ -139,7 +145,7 @@ public function createView(ChoiceListInterface $list, array|callable $preferredC return new ChoiceListView($otherViews, $preferredViews); } - private static function addChoiceView($choice, string $value, $label, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews): void + private static function addChoiceView($choice, string $value, $label, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews, bool $duplicatePreferredChoices): void { // $value may be an integer or a string, since it's stored in the array // keys. We want to guarantee it's a string though. @@ -180,12 +186,16 @@ private static function addChoiceView($choice, string $value, $label, array $key if (null !== $isPreferred && false !== $preferredKey = $isPreferred($choice, $key, $value)) { $preferredViews[$nextIndex] = $view; $preferredViewsOrder[$nextIndex] = $preferredKey; - } - $otherViews[$nextIndex] = $view; + if ($duplicatePreferredChoices) { + $otherViews[$nextIndex] = $view; + } + } else { + $otherViews[$nextIndex] = $view; + } } - private static function addChoiceViewsFromStructuredValues(array $values, $label, array $choices, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews): void + private static function addChoiceViewsFromStructuredValues(array $values, $label, array $choices, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews, bool $duplicatePreferredChoices): void { foreach ($values as $key => $value) { if (null === $value) { @@ -208,7 +218,8 @@ private static function addChoiceViewsFromStructuredValues(array $values, $label $isPreferred, $preferredViewsForGroup, $preferredViewsOrder, - $otherViewsForGroup + $otherViewsForGroup, + $duplicatePreferredChoices, ); if (\count($preferredViewsForGroup) > 0) { @@ -234,12 +245,13 @@ private static function addChoiceViewsFromStructuredValues(array $values, $label $isPreferred, $preferredViews, $preferredViewsOrder, - $otherViews + $otherViews, + $duplicatePreferredChoices, ); } } - private static function addChoiceViewsGroupedByCallable(callable $groupBy, $choice, string $value, $label, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews): void + private static function addChoiceViewsGroupedByCallable(callable $groupBy, $choice, string $value, $label, array $keys, &$index, $attr, $labelTranslationParameters, ?callable $isPreferred, array &$preferredViews, array &$preferredViewsOrder, array &$otherViews, bool $duplicatePreferredChoices): void { $groupLabels = $groupBy($choice, $keys[$value], $value); @@ -256,7 +268,8 @@ private static function addChoiceViewsGroupedByCallable(callable $groupBy, $choi $isPreferred, $preferredViews, $preferredViewsOrder, - $otherViews + $otherViews, + $duplicatePreferredChoices, ); return; @@ -286,7 +299,8 @@ private static function addChoiceViewsGroupedByCallable(callable $groupBy, $choi $isPreferred, $preferredViews[$groupLabel]->choices, $preferredViewsOrder[$groupLabel], - $otherViews[$groupLabel]->choices + $otherViews[$groupLabel]->choices, + $duplicatePreferredChoices, ); } } diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index fa66290e34..dab8a5d77a 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -109,8 +109,12 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value return $this->decoratedFactory->createListFromLoader($loader, $value, $filter); } - public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []): ChoiceListView + /** + * @param bool $duplicatePreferredChoices + */ + public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []/* , bool $duplicatePreferredChoices = true */): ChoiceListView { + $duplicatePreferredChoices = \func_num_args() > 7 ? func_get_arg(7) : true; $accessor = $this->propertyAccessor; if (\is_string($label)) { @@ -182,7 +186,8 @@ public function createView(ChoiceListInterface $list, mixed $preferredChoices = $index, $groupBy, $attr, - $labelTranslationParameters + $labelTranslationParameters, + $duplicatePreferredChoices, ); } } diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index e31d810df1..1cc25c3b6e 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -354,6 +354,7 @@ public function configureOptions(OptionsResolver $resolver) 'choice_attr' => null, 'choice_translation_parameters' => [], 'preferred_choices' => [], + 'duplicate_preferred_choices' => true, 'group_by' => null, 'empty_data' => $emptyData, 'placeholder' => $placeholderDefault, @@ -383,6 +384,7 @@ public function configureOptions(OptionsResolver $resolver) $resolver->setAllowedTypes('choice_translation_parameters', ['null', 'array', 'callable', ChoiceTranslationParameters::class]); $resolver->setAllowedTypes('placeholder_attr', ['array']); $resolver->setAllowedTypes('preferred_choices', ['array', \Traversable::class, 'callable', 'string', PropertyPath::class, PreferredChoice::class]); + $resolver->setAllowedTypes('duplicate_preferred_choices', 'bool'); $resolver->setAllowedTypes('group_by', ['null', 'callable', 'string', PropertyPath::class, GroupBy::class]); } @@ -465,7 +467,8 @@ private function createChoiceListView(ChoiceListInterface $choiceList, array $op $options['choice_name'], $options['group_by'], $options['choice_attr'], - $options['choice_translation_parameters'] + $options['choice_translation_parameters'], + $options['duplicate_preferred_choices'], ); } } diff --git a/Tests/Fixtures/Descriptor/resolved_form_type_1.json b/Tests/Fixtures/Descriptor/resolved_form_type_1.json index 3a9b7a7ecc..27371fd6f6 100644 --- a/Tests/Fixtures/Descriptor/resolved_form_type_1.json +++ b/Tests/Fixtures/Descriptor/resolved_form_type_1.json @@ -12,6 +12,7 @@ "choice_translation_parameters", "choice_value", "choices", + "duplicate_preferred_choices", "expanded", "group_by", "multiple", diff --git a/Tests/Fixtures/Descriptor/resolved_form_type_1.txt b/Tests/Fixtures/Descriptor/resolved_form_type_1.txt index a15ac42dae..c8aee5e783 100644 --- a/Tests/Fixtures/Descriptor/resolved_form_type_1.txt +++ b/Tests/Fixtures/Descriptor/resolved_form_type_1.txt @@ -14,13 +14,13 @@ Symfony\Component\Form\Extension\Core\Type\ChoiceType (Block prefix: "choice") choice_translation_parameters invalid_message auto_initialize csrf_token_manager choice_value trim block_name choices block_prefix - expanded by_reference - group_by data - multiple disabled - placeholder form_attr - placeholder_attr getter - preferred_choices help - help_attr + duplicate_preferred_choices by_reference + expanded data + group_by disabled + multiple form_attr + placeholder getter + placeholder_attr help + preferred_choices help_attr help_html help_translation_parameters inherit_data From 222a0e4e5e76bae5e5d8658e7594718b592c5fc6 Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Sat, 7 Oct 2023 18:04:31 +0200 Subject: [PATCH 135/208] Remove RunTestTrait --- Test/FormPerformanceTestCase.php | 6 ++---- Test/Traits/RunTestTrait.php | 36 -------------------------------- 2 files changed, 2 insertions(+), 40 deletions(-) delete mode 100644 Test/Traits/RunTestTrait.php diff --git a/Test/FormPerformanceTestCase.php b/Test/FormPerformanceTestCase.php index 4494ffced4..54ccc67cfd 100644 --- a/Test/FormPerformanceTestCase.php +++ b/Test/FormPerformanceTestCase.php @@ -11,7 +11,6 @@ namespace Symfony\Component\Form\Test; -use Symfony\Component\Form\Test\Traits\RunTestTrait; use Symfony\Component\Form\Tests\VersionAwareTest; /** @@ -24,12 +23,11 @@ */ abstract class FormPerformanceTestCase extends FormIntegrationTestCase { - use RunTestTrait; use VersionAwareTest; protected int $maxRunningTime = 0; - private function doRunTest(): mixed + protected function runTest(): mixed { $s = microtime(true); $result = parent::runTest(); @@ -45,7 +43,7 @@ private function doRunTest(): mixed /** * @throws \InvalidArgumentException */ - public function setMaxRunningTime(int $maxRunningTime) + public function setMaxRunningTime(int $maxRunningTime): void { if ($maxRunningTime < 0) { throw new \InvalidArgumentException(); diff --git a/Test/Traits/RunTestTrait.php b/Test/Traits/RunTestTrait.php deleted file mode 100644 index 17204b9670..0000000000 --- a/Test/Traits/RunTestTrait.php +++ /dev/null @@ -1,36 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Form\Test\Traits; - -use PHPUnit\Framework\TestCase; - -if ((new \ReflectionMethod(TestCase::class, 'runTest'))->hasReturnType()) { - // PHPUnit 10 - /** @internal */ - trait RunTestTrait - { - protected function runTest(): mixed - { - return $this->doRunTest(); - } - } -} else { - // PHPUnit 9 - /** @internal */ - trait RunTestTrait - { - protected function runTest() - { - return $this->doRunTest(); - } - } -} From 55035e25259afabecc3878dbb1bffff0469fe4f5 Mon Sep 17 00:00:00 2001 From: Jules Pietri Date: Sat, 14 Oct 2023 14:37:23 +0200 Subject: [PATCH 136/208] [Form] Remove deprecation layer for duplicated preferred choices --- ChoiceList/Factory/CachingFactoryDecorator.php | 6 +----- ChoiceList/Factory/ChoiceListFactoryInterface.php | 2 +- ChoiceList/Factory/DefaultChoiceListFactory.php | 6 +----- ChoiceList/Factory/PropertyAccessDecorator.php | 6 +----- 4 files changed, 4 insertions(+), 16 deletions(-) diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index f77870c3e4..687fcec1ee 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -145,12 +145,8 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value return $this->lists[$hash]; } - /** - * @param bool $duplicatePreferredChoices - */ - public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []/* , bool $duplicatePreferredChoices = true */): ChoiceListView + public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = [], bool $duplicatePreferredChoices = true): ChoiceListView { - $duplicatePreferredChoices = \func_num_args() > 7 ? func_get_arg(7) : true; $cache = true; if ($preferredChoices instanceof Cache\PreferredChoice) { diff --git a/ChoiceList/Factory/ChoiceListFactoryInterface.php b/ChoiceList/Factory/ChoiceListFactoryInterface.php index 89633710b6..7c94ad809e 100644 --- a/ChoiceList/Factory/ChoiceListFactoryInterface.php +++ b/ChoiceList/Factory/ChoiceListFactoryInterface.php @@ -81,5 +81,5 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $va * on top of the list and in their original position * or only in the top of the list */ - public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []/* , bool $duplicatePreferredChoices = true */): ChoiceListView; + public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = [], bool $duplicatePreferredChoices = true): ChoiceListView; } diff --git a/ChoiceList/Factory/DefaultChoiceListFactory.php b/ChoiceList/Factory/DefaultChoiceListFactory.php index aa371362c8..abac8eae31 100644 --- a/ChoiceList/Factory/DefaultChoiceListFactory.php +++ b/ChoiceList/Factory/DefaultChoiceListFactory.php @@ -52,12 +52,8 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, callable $va return new LazyChoiceList($loader, $value); } - /** - * @param bool $duplicatePreferredChoices - */ - public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = []/* , bool $duplicatePreferredChoices = true */): ChoiceListView + public function createView(ChoiceListInterface $list, array|callable $preferredChoices = null, callable|false $label = null, callable $index = null, callable $groupBy = null, array|callable $attr = null, array|callable $labelTranslationParameters = [], bool $duplicatePreferredChoices = true): ChoiceListView { - $duplicatePreferredChoices = \func_num_args() > 7 ? func_get_arg(7) : true; $preferredViews = []; $preferredViewsOrder = []; $otherViews = []; diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index dab8a5d77a..91460774f3 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -109,12 +109,8 @@ public function createListFromLoader(ChoiceLoaderInterface $loader, mixed $value return $this->decoratedFactory->createListFromLoader($loader, $value, $filter); } - /** - * @param bool $duplicatePreferredChoices - */ - public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = []/* , bool $duplicatePreferredChoices = true */): ChoiceListView + public function createView(ChoiceListInterface $list, mixed $preferredChoices = null, mixed $label = null, mixed $index = null, mixed $groupBy = null, mixed $attr = null, mixed $labelTranslationParameters = [], bool $duplicatePreferredChoices = true): ChoiceListView { - $duplicatePreferredChoices = \func_num_args() > 7 ? func_get_arg(7) : true; $accessor = $this->propertyAccessor; if (\is_string($label)) { From caebc8874cad6fcf8eac29f7a1c4e530f6179df1 Mon Sep 17 00:00:00 2001 From: Nicolas Lemoine Date: Wed, 21 Jun 2023 21:09:57 +0200 Subject: [PATCH 137/208] [ErrorHandler] Improve fileLinkFormat handling - Avoid repeating file link format guessing (logic is already in FileLinkFormatter class) - Always set a fileLinkFormat to a FileLinkFormatter object to handle path mappings properly --- Command/DebugCommand.php | 7 ++++--- Console/Descriptor/TextDescriptor.php | 7 ++++--- Console/Helper/DescriptorHelper.php | 5 +++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index 4a142e2965..a256511261 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -21,11 +21,12 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\ErrorHandler\ErrorRenderer\FileLinkFormatter; use Symfony\Component\Form\Console\Helper\DescriptorHelper; use Symfony\Component\Form\Extension\Core\CoreExtension; use Symfony\Component\Form\FormRegistryInterface; use Symfony\Component\Form\FormTypeInterface; -use Symfony\Component\HttpKernel\Debug\FileLinkFormatter; +use Symfony\Component\HttpKernel\Debug\FileLinkFormatter as LegacyFileLinkFormatter; /** * A console command for retrieving information about form types. @@ -40,9 +41,9 @@ class DebugCommand extends Command private array $types; private array $extensions; private array $guessers; - private ?FileLinkFormatter $fileLinkFormatter; + private FileLinkFormatter|LegacyFileLinkFormatter|null $fileLinkFormatter; - public function __construct(FormRegistryInterface $formRegistry, array $namespaces = ['Symfony\Component\Form\Extension\Core\Type'], array $types = [], array $extensions = [], array $guessers = [], FileLinkFormatter $fileLinkFormatter = null) + public function __construct(FormRegistryInterface $formRegistry, array $namespaces = ['Symfony\Component\Form\Extension\Core\Type'], array $types = [], array $extensions = [], array $guessers = [], FileLinkFormatter|LegacyFileLinkFormatter $fileLinkFormatter = null) { parent::__construct(); diff --git a/Console/Descriptor/TextDescriptor.php b/Console/Descriptor/TextDescriptor.php index c4a2db27a0..ce84562e1b 100644 --- a/Console/Descriptor/TextDescriptor.php +++ b/Console/Descriptor/TextDescriptor.php @@ -13,8 +13,9 @@ use Symfony\Component\Console\Helper\Dumper; use Symfony\Component\Console\Helper\TableSeparator; +use Symfony\Component\ErrorHandler\ErrorRenderer\FileLinkFormatter; use Symfony\Component\Form\ResolvedFormTypeInterface; -use Symfony\Component\HttpKernel\Debug\FileLinkFormatter; +use Symfony\Component\HttpKernel\Debug\FileLinkFormatter as LegacyFileLinkFormatter; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -24,9 +25,9 @@ */ class TextDescriptor extends Descriptor { - private ?FileLinkFormatter $fileLinkFormatter; + private FileLinkFormatter|LegacyFileLinkFormatter|null $fileLinkFormatter; - public function __construct(FileLinkFormatter $fileLinkFormatter = null) + public function __construct(FileLinkFormatter|LegacyFileLinkFormatter $fileLinkFormatter = null) { $this->fileLinkFormatter = $fileLinkFormatter; } diff --git a/Console/Helper/DescriptorHelper.php b/Console/Helper/DescriptorHelper.php index 355fb95989..5944d8e18c 100644 --- a/Console/Helper/DescriptorHelper.php +++ b/Console/Helper/DescriptorHelper.php @@ -12,9 +12,10 @@ namespace Symfony\Component\Form\Console\Helper; use Symfony\Component\Console\Helper\DescriptorHelper as BaseDescriptorHelper; +use Symfony\Component\ErrorHandler\ErrorRenderer\FileLinkFormatter; use Symfony\Component\Form\Console\Descriptor\JsonDescriptor; use Symfony\Component\Form\Console\Descriptor\TextDescriptor; -use Symfony\Component\HttpKernel\Debug\FileLinkFormatter; +use Symfony\Component\HttpKernel\Debug\FileLinkFormatter as LegacyFileLinkFormatter; /** * @author Yonel Ceruto @@ -23,7 +24,7 @@ */ class DescriptorHelper extends BaseDescriptorHelper { - public function __construct(FileLinkFormatter $fileLinkFormatter = null) + public function __construct(FileLinkFormatter|LegacyFileLinkFormatter $fileLinkFormatter = null) { $this ->register('txt', new TextDescriptor($fileLinkFormatter)) From d6028631fd66977dfb51b49401f7a66af480e122 Mon Sep 17 00:00:00 2001 From: Dariusz Ruminski Date: Thu, 19 Oct 2023 16:43:30 +0200 Subject: [PATCH 138/208] DX: nullable_type_declaration --- Util/OrderedHashMapIterator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Util/OrderedHashMapIterator.php b/Util/OrderedHashMapIterator.php index 828218a452..a7a40779bb 100644 --- a/Util/OrderedHashMapIterator.php +++ b/Util/OrderedHashMapIterator.php @@ -32,7 +32,7 @@ class OrderedHashMapIterator implements \Iterator private int $cursorId; /** @var array */ private array $managedCursors; - private string|null $key = null; + private ?string $key = null; /** @var TValue|null */ private mixed $current = null; From 7da1acbe1104fe13182c011862d59d982c13799d Mon Sep 17 00:00:00 2001 From: Dariusz Ruminski Date: Fri, 27 Oct 2023 14:14:50 +0200 Subject: [PATCH 139/208] DX: re-apply self_accessor and phpdoc_types_order by PHP CS Fixer --- FormBuilderInterface.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FormBuilderInterface.php b/FormBuilderInterface.php index d4e7b525d5..c00fae46a5 100644 --- a/FormBuilderInterface.php +++ b/FormBuilderInterface.php @@ -27,7 +27,7 @@ interface FormBuilderInterface extends \Traversable, \Countable, FormConfigBuild * * @param array $options */ - public function add(string|FormBuilderInterface $child, string $type = null, array $options = []): static; + public function add(string|self $child, string $type = null, array $options = []): static; /** * Creates a form builder. From fe1882ce6f42c3dbeae8cce765046bb9962e44e5 Mon Sep 17 00:00:00 2001 From: Oskar Stark Date: Tue, 31 Oct 2023 09:28:27 +0100 Subject: [PATCH 140/208] Fix tests --- .../Core/DataTransformer/ChoiceToValueTransformerTest.php | 4 ++-- .../Core/DataTransformer/DateTimeToRfc3339TransformerTest.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php b/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php index ff5444f370..e8bb71119a 100644 --- a/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.php @@ -18,8 +18,8 @@ class ChoiceToValueTransformerTest extends TestCase { - protected ChoiceToValueTransformer $transformer; - protected ChoiceToValueTransformer $transformerWithNull; + protected ?ChoiceToValueTransformer $transformer; + protected ?ChoiceToValueTransformer $transformerWithNull; protected function setUp(): void { diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php index 53d5717406..f799f1dbb3 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php @@ -20,8 +20,8 @@ class DateTimeToRfc3339TransformerTest extends BaseDateTimeTransformerTestCase { use DateTimeEqualsTrait; - protected \DateTime $dateTime; - protected \DateTime $dateTimeWithoutSeconds; + protected ?\DateTime $dateTime; + protected ?\DateTime $dateTimeWithoutSeconds; protected function setUp(): void { From 96cdf7d749e86e8e28f190f59ed07eeb12253a50 Mon Sep 17 00:00:00 2001 From: MatTheCat Date: Sat, 18 Nov 2023 15:43:39 +0100 Subject: [PATCH 141/208] [Form] Deprecate not configuring the `default_protocol` option of the `UrlType` --- CHANGELOG.md | 5 +++++ Extension/Core/Type/UrlType.php | 7 ++++++- Tests/Extension/Core/Type/TextTypeTest.php | 8 ++++---- Tests/Extension/Core/Type/UrlTypeTest.php | 13 +++++++++++++ .../Type/UrlTypeValidatorExtensionTest.php | 2 +- composer.json | 1 + 6 files changed, 30 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c712cc141..1a10c50f93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +7.1 +--- + +* Deprecate not configuring the `default_protocol` option of the `UrlType`, it will default to `null` in 8.0 + 7.0 --- diff --git a/Extension/Core/Type/UrlType.php b/Extension/Core/Type/UrlType.php index d9cd3c6fb3..fd6025729a 100644 --- a/Extension/Core/Type/UrlType.php +++ b/Extension/Core/Type/UrlType.php @@ -16,6 +16,7 @@ use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; +use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; class UrlType extends AbstractType @@ -38,7 +39,11 @@ public function buildView(FormView $view, FormInterface $form, array $options): public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ - 'default_protocol' => 'http', + 'default_protocol' => static function (Options $options) { + trigger_deprecation('symfony/form', '7.1', 'Not configuring the "default_protocol" option when using the UrlType is deprecated. It will default to "null" in 8.0.'); + + return 'http'; + }, 'invalid_message' => 'Please enter a valid URL.', ]); diff --git a/Tests/Extension/Core/Type/TextTypeTest.php b/Tests/Extension/Core/Type/TextTypeTest.php index e14a816362..a28dfa9afa 100644 --- a/Tests/Extension/Core/Type/TextTypeTest.php +++ b/Tests/Extension/Core/Type/TextTypeTest.php @@ -22,9 +22,9 @@ public function testSubmitNull($expected = null, $norm = null, $view = null) public function testSubmitNullReturnsNullWithEmptyDataAsString() { - $form = $this->factory->create(static::TESTED_TYPE, 'name', [ + $form = $this->factory->create(static::TESTED_TYPE, 'name', array_merge($this->getTestOptions(), [ 'empty_data' => '', - ]); + ])); $form->submit(null); $this->assertSame('', $form->getData()); @@ -48,9 +48,9 @@ public static function provideZeros(): array */ public function testSetDataThroughParamsWithZero($data, $dataAsString) { - $form = $this->factory->create(static::TESTED_TYPE, null, [ + $form = $this->factory->create(static::TESTED_TYPE, null, array_merge($this->getTestOptions(), [ 'data' => $data, - ]); + ])); $view = $form->createView(); $this->assertFalse($form->isEmpty()); diff --git a/Tests/Extension/Core/Type/UrlTypeTest.php b/Tests/Extension/Core/Type/UrlTypeTest.php index b9387d01a4..28e8b9ac74 100644 --- a/Tests/Extension/Core/Type/UrlTypeTest.php +++ b/Tests/Extension/Core/Type/UrlTypeTest.php @@ -11,14 +11,21 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class UrlTypeTest extends TextTypeTest { + use ExpectDeprecationTrait; + public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\UrlType'; + /** + * @group legacy + */ public function testSubmitAddsDefaultProtocolIfNoneIsIncluded() { + $this->expectDeprecation('Since symfony/form 7.1: Not configuring the "default_protocol" option when using the UrlType is deprecated. It will default to "null" in 8.0.'); $form = $this->factory->create(static::TESTED_TYPE, 'name'); $form->submit('www.domain.com'); @@ -86,6 +93,7 @@ public function testThrowExceptionIfDefaultProtocolIsInvalid() public function testSubmitNullUsesDefaultEmptyData($emptyData = 'empty', $expectedData = 'http://empty') { $form = $this->factory->create(static::TESTED_TYPE, null, [ + 'default_protocol' => 'http', 'empty_data' => $emptyData, ]); $form->submit(null); @@ -95,4 +103,9 @@ public function testSubmitNullUsesDefaultEmptyData($emptyData = 'empty', $expect $this->assertSame($expectedData, $form->getNormData()); $this->assertSame($expectedData, $form->getData()); } + + protected function getTestOptions(): array + { + return ['default_protocol' => 'http']; + } } diff --git a/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php index e6314a3c59..edb212cbd4 100644 --- a/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/UrlTypeValidatorExtensionTest.php @@ -20,7 +20,7 @@ class UrlTypeValidatorExtensionTest extends BaseValidatorExtensionTestCase protected function createForm(array $options = []) { - return $this->factory->create(UrlType::class, null, $options); + return $this->factory->create(UrlType::class, null, $options + ['default_protocol' => 'http']); } public function testInvalidMessage() diff --git a/composer.json b/composer.json index 914ddc6c52..7ee167817f 100644 --- a/composer.json +++ b/composer.json @@ -17,6 +17,7 @@ ], "require": { "php": ">=8.2", + "symfony/deprecation-contracts": "^2.5|^3", "symfony/event-dispatcher": "^6.4|^7.0", "symfony/options-resolver": "^6.4|^7.0", "symfony/polyfill-ctype": "~1.8", From 28fc11e86087aaf0cddcbaf7dec578b1a82f260a Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Mon, 20 Nov 2023 10:13:42 +0100 Subject: [PATCH 142/208] [Form] Add missing whitespace in Changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a10c50f93..273a71c0cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ CHANGELOG 7.1 --- -* Deprecate not configuring the `default_protocol` option of the `UrlType`, it will default to `null` in 8.0 + * Deprecate not configuring the `default_protocol` option of the `UrlType`, it will default to `null` in 8.0 7.0 --- From 387ece75df4e66385014c299e4a140673b843c36 Mon Sep 17 00:00:00 2001 From: Daniel Burger <48986191+danielburger1337@users.noreply.github.com> Date: Wed, 8 Nov 2023 05:54:37 +0100 Subject: [PATCH 143/208] [HttpFoundation] Add `UploadedFile::getClientOriginalPath()` to support directory uploads --- NativeRequestHandler.php | 11 ++++++----- Tests/NativeRequestHandlerTest.php | 4 ++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/NativeRequestHandler.php b/NativeRequestHandler.php index 9ac1f2ea9a..8c74bd1ded 100644 --- a/NativeRequestHandler.php +++ b/NativeRequestHandler.php @@ -29,6 +29,7 @@ class NativeRequestHandler implements RequestHandlerInterface */ private const FILE_KEYS = [ 'error', + 'full_path', 'name', 'size', 'tmp_name', @@ -186,9 +187,7 @@ private static function fixPhpFilesArray(mixed $data): mixed return $data; } - // Remove extra key added by PHP 8.1. - unset($data['full_path']); - $keys = array_keys($data); + $keys = array_keys($data + ['full_path' => null]); sort($keys); if (self::FILE_KEYS !== $keys || !isset($data['name']) || !\is_array($data['name'])) { @@ -207,7 +206,9 @@ private static function fixPhpFilesArray(mixed $data): mixed 'type' => $data['type'][$key], 'tmp_name' => $data['tmp_name'][$key], 'size' => $data['size'][$key], - ]); + ] + (isset($data['full_path'][$key]) ? [ + 'full_path' => $data['full_path'][$key], + ] : [])); } return $files; @@ -219,7 +220,7 @@ private static function stripEmptyFiles(mixed $data): mixed return $data; } - $keys = array_keys($data); + $keys = array_keys($data + ['full_path' => null]); sort($keys); if (self::FILE_KEYS === $keys) { diff --git a/Tests/NativeRequestHandlerTest.php b/Tests/NativeRequestHandlerTest.php index bdb0763f9d..679c3366d8 100644 --- a/Tests/NativeRequestHandlerTest.php +++ b/Tests/NativeRequestHandlerTest.php @@ -99,6 +99,9 @@ public function testFixBuggyFilesArray() 'name' => [ 'field' => 'upload.txt', ], + 'full_path' => [ + 'field' => 'path/to/file/upload.txt', + ], 'type' => [ 'field' => 'text/plain', ], @@ -118,6 +121,7 @@ public function testFixBuggyFilesArray() $this->assertTrue($form->isSubmitted()); $this->assertEquals([ 'name' => 'upload.txt', + 'full_path' => 'path/to/file/upload.txt', 'type' => 'text/plain', 'tmp_name' => 'owfdskjasdfsa', 'error' => \UPLOAD_ERR_OK, From 8acd03ca09abfbdd07f9d99b2231225d4afd4186 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault Date: Mon, 20 Nov 2023 19:43:22 +0100 Subject: [PATCH 144/208] [Form] Clean unused code --- .../NumberToLocalizedStringTransformer.php | 34 ++++------- .../PercentToLocalizedStringTransformer.php | 56 +++++++------------ Form.php | 7 --- FormBuilder.php | 5 -- 4 files changed, 29 insertions(+), 73 deletions(-) diff --git a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index 911246782d..0693e79797 100644 --- a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -183,35 +183,21 @@ protected function castParsedValue(int|float $value): int|float */ private function round(int|float $number): int|float { - if (null !== $this->scale && null !== $this->roundingMode) { + if (null !== $this->scale) { // shift number to maintain the correct scale during rounding $roundingCoef = 10 ** $this->scale; // string representation to avoid rounding errors, similar to bcmul() $number = (string) ($number * $roundingCoef); - switch ($this->roundingMode) { - case \NumberFormatter::ROUND_CEILING: - $number = ceil($number); - break; - case \NumberFormatter::ROUND_FLOOR: - $number = floor($number); - break; - case \NumberFormatter::ROUND_UP: - $number = $number > 0 ? ceil($number) : floor($number); - break; - case \NumberFormatter::ROUND_DOWN: - $number = $number > 0 ? floor($number) : ceil($number); - break; - case \NumberFormatter::ROUND_HALFEVEN: - $number = round($number, 0, \PHP_ROUND_HALF_EVEN); - break; - case \NumberFormatter::ROUND_HALFUP: - $number = round($number, 0, \PHP_ROUND_HALF_UP); - break; - case \NumberFormatter::ROUND_HALFDOWN: - $number = round($number, 0, \PHP_ROUND_HALF_DOWN); - break; - } + $number = match ($this->roundingMode) { + \NumberFormatter::ROUND_CEILING => ceil($number), + \NumberFormatter::ROUND_FLOOR => floor($number), + \NumberFormatter::ROUND_UP => $number > 0 ? ceil($number) : floor($number), + \NumberFormatter::ROUND_DOWN => $number > 0 ? floor($number) : ceil($number), + \NumberFormatter::ROUND_HALFEVEN => round($number, 0, \PHP_ROUND_HALF_EVEN), + \NumberFormatter::ROUND_HALFUP => round($number, 0, \PHP_ROUND_HALF_UP), + \NumberFormatter::ROUND_HALFDOWN => round($number, 0, \PHP_ROUND_HALF_DOWN), + }; $number = 1 === $roundingCoef ? (int) $number : $number / $roundingCoef; } diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index 0915021d3b..98d62783c1 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -180,9 +180,7 @@ protected function getNumberFormatter(): \NumberFormatter $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->scale); - if (null !== $this->roundingMode) { - $formatter->setAttribute(\NumberFormatter::ROUNDING_MODE, $this->roundingMode); - } + $formatter->setAttribute(\NumberFormatter::ROUNDING_MODE, $this->roundingMode); return $formatter; } @@ -192,43 +190,27 @@ protected function getNumberFormatter(): \NumberFormatter */ private function round(int|float $number): int|float { - if (null !== $this->scale && null !== $this->roundingMode) { - // shift number to maintain the correct scale during rounding - $roundingCoef = 10 ** $this->scale; + // shift number to maintain the correct scale during rounding + $roundingCoef = 10 ** $this->scale; - if (self::FRACTIONAL == $this->type) { - $roundingCoef *= 100; - } + if (self::FRACTIONAL === $this->type) { + $roundingCoef *= 100; + } - // string representation to avoid rounding errors, similar to bcmul() - $number = (string) ($number * $roundingCoef); - - switch ($this->roundingMode) { - case \NumberFormatter::ROUND_CEILING: - $number = ceil($number); - break; - case \NumberFormatter::ROUND_FLOOR: - $number = floor($number); - break; - case \NumberFormatter::ROUND_UP: - $number = $number > 0 ? ceil($number) : floor($number); - break; - case \NumberFormatter::ROUND_DOWN: - $number = $number > 0 ? floor($number) : ceil($number); - break; - case \NumberFormatter::ROUND_HALFEVEN: - $number = round($number, 0, \PHP_ROUND_HALF_EVEN); - break; - case \NumberFormatter::ROUND_HALFUP: - $number = round($number, 0, \PHP_ROUND_HALF_UP); - break; - case \NumberFormatter::ROUND_HALFDOWN: - $number = round($number, 0, \PHP_ROUND_HALF_DOWN); - break; - } + // string representation to avoid rounding errors, similar to bcmul() + $number = (string) ($number * $roundingCoef); - $number = 1 === $roundingCoef ? (int) $number : $number / $roundingCoef; - } + $number = match ($this->roundingMode) { + \NumberFormatter::ROUND_CEILING => ceil($number), + \NumberFormatter::ROUND_FLOOR => floor($number), + \NumberFormatter::ROUND_UP => $number > 0 ? ceil($number) : floor($number), + \NumberFormatter::ROUND_DOWN => $number > 0 ? floor($number) : ceil($number), + \NumberFormatter::ROUND_HALFEVEN => round($number, 0, \PHP_ROUND_HALF_EVEN), + \NumberFormatter::ROUND_HALFUP => round($number, 0, \PHP_ROUND_HALF_UP), + \NumberFormatter::ROUND_HALFDOWN => round($number, 0, \PHP_ROUND_HALF_DOWN), + }; + + $number = 1 === $roundingCoef ? (int) $number : $number / $roundingCoef; return $number; } diff --git a/Form.php b/Form.php index 5c86d27b56..88c4376619 100644 --- a/Form.php +++ b/Form.php @@ -21,7 +21,6 @@ use Symfony\Component\Form\Exception\OutOfBoundsException; use Symfony\Component\Form\Exception\RuntimeException; use Symfony\Component\Form\Exception\TransformationFailedException; -use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Util\FormUtil; use Symfony\Component\Form\Util\InheritDataAwareIterator; @@ -727,12 +726,6 @@ public function add(FormInterface|string $child, string $type = null, array $opt } if (!$child instanceof FormInterface) { - if (!\is_string($child) && !\is_int($child)) { - throw new UnexpectedTypeException($child, 'string or Symfony\Component\Form\FormInterface'); - } - - $child = (string) $child; - // Never initialize child forms automatically $options['auto_initialize'] = false; diff --git a/FormBuilder.php b/FormBuilder.php index 33f07b0f1d..816c38810f 100644 --- a/FormBuilder.php +++ b/FormBuilder.php @@ -14,7 +14,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\Exception\BadMethodCallException; use Symfony\Component\Form\Exception\InvalidArgumentException; -use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Extension\Core\Type\TextType; /** @@ -60,10 +59,6 @@ public function add(FormBuilderInterface|string $child, string $type = null, arr return $this; } - if (!\is_string($child) && !\is_int($child)) { - throw new UnexpectedTypeException($child, 'string or Symfony\Component\Form\FormBuilderInterface'); - } - // Add to "children" to maintain order $this->children[$child] = null; $this->unresolvedChildren[$child] = [$type, $options]; From e0aa685324ca461290b6fc2dc461732d423b63d6 Mon Sep 17 00:00:00 2001 From: Cristoforo Cervino Date: Tue, 13 Apr 2021 20:02:24 +0200 Subject: [PATCH 145/208] [Form] Errors Property Paths mismatch CollectionType children when removing an entry --- CHANGELOG.md | 1 + .../Core/EventListener/ResizeFormListener.php | 18 +- Extension/Core/Type/CollectionType.php | 5 +- .../Type/FormTypeValidatorExtensionTest.php | 184 ++++++++++++++++++ Tests/Fixtures/Organization.php | 32 +++ 5 files changed, 238 insertions(+), 2 deletions(-) create mode 100644 Tests/Fixtures/Organization.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 273a71c0cd..2035e8f805 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ CHANGELOG --- * Deprecate not configuring the `default_protocol` option of the `UrlType`, it will default to `null` in 8.0 + * Add a `keep_as_list` option to `CollectionType` 7.0 --- diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index 482007d53b..641f165257 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -31,8 +31,9 @@ class ResizeFormListener implements EventSubscriberInterface protected bool $allowDelete; private \Closure|bool $deleteEmpty; + private bool $keepAsList; - public function __construct(string $type, array $options = [], bool $allowAdd = false, bool $allowDelete = false, bool|callable $deleteEmpty = false, array $prototypeOptions = null) + public function __construct(string $type, array $options = [], bool $allowAdd = false, bool $allowDelete = false, bool|callable $deleteEmpty = false, array $prototypeOptions = null, bool $keepAsList = false) { $this->type = $type; $this->allowAdd = $allowAdd; @@ -40,6 +41,7 @@ public function __construct(string $type, array $options = [], bool $allowAdd = $this->options = $options; $this->deleteEmpty = \is_bool($deleteEmpty) ? $deleteEmpty : $deleteEmpty(...); $this->prototypeOptions = $prototypeOptions ?? $options; + $this->keepAsList = $keepAsList; } public static function getSubscribedEvents(): array @@ -153,6 +155,20 @@ public function onSubmit(FormEvent $event): void } } + if ($this->keepAsList) { + $formReindex = []; + foreach ($form as $name => $child) { + $formReindex[] = $child; + $form->remove($name); + } + foreach ($formReindex as $index => $child) { + $form->add($index, $this->type, array_replace([ + 'property_path' => '['.$index.']', + ], $this->options)); + } + $data = array_values($data); + } + $event->setData($data); } } diff --git a/Extension/Core/Type/CollectionType.php b/Extension/Core/Type/CollectionType.php index c9d3ec5b7c..3cef931526 100644 --- a/Extension/Core/Type/CollectionType.php +++ b/Extension/Core/Type/CollectionType.php @@ -45,7 +45,8 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $options['allow_add'], $options['allow_delete'], $options['delete_empty'], - $resizePrototypeOptions + $resizePrototypeOptions, + $options['keep_as_list'] ); $builder->addEventSubscriber($resizeListener); @@ -114,12 +115,14 @@ public function configureOptions(OptionsResolver $resolver): void 'prototype_options' => [], 'delete_empty' => false, 'invalid_message' => 'The collection is invalid.', + 'keep_as_list' => false, ]); $resolver->setNormalizer('entry_options', $entryOptionsNormalizer); $resolver->setAllowedTypes('delete_empty', ['bool', 'callable']); $resolver->setAllowedTypes('prototype_options', 'array'); + $resolver->setAllowedTypes('keep_as_list', ['bool']); } public function getBlockPrefix(): string diff --git a/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php b/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php index 3b4cd77396..a1d1a38402 100644 --- a/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php +++ b/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php @@ -15,9 +15,12 @@ use Symfony\Component\Form\Form; use Symfony\Component\Form\Forms; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; +use Symfony\Component\Form\Tests\Extension\Core\Type\CollectionTypeTest; use Symfony\Component\Form\Tests\Extension\Core\Type\FormTypeTest; use Symfony\Component\Form\Tests\Extension\Core\Type\TextTypeTest; use Symfony\Component\Form\Tests\Fixtures\Author; +use Symfony\Component\Form\Tests\Fixtures\AuthorType; +use Symfony\Component\Form\Tests\Fixtures\Organization; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\Validator\Constraints\GroupSequence; use Symfony\Component\Validator\Constraints\Length; @@ -158,4 +161,185 @@ protected function createForm(array $options = []) { return $this->factory->create(FormTypeTest::TESTED_TYPE, null, $options); } + + public function testCollectionTypeKeepAsListOptionFalse() + { + $formMetadata = new ClassMetadata(Form::class); + $authorMetadata = (new ClassMetadata(Author::class)) + ->addPropertyConstraint('firstName', new NotBlank()); + $organizationMetadata = (new ClassMetadata(Organization::class)) + ->addPropertyConstraint('authors', new Valid()); + $metadataFactory = $this->createMock(MetadataFactoryInterface::class); + $metadataFactory->expects($this->any()) + ->method('getMetadataFor') + ->willReturnCallback(static function ($classOrObject) use ($formMetadata, $authorMetadata, $organizationMetadata) { + if (Author::class === $classOrObject || $classOrObject instanceof Author) { + return $authorMetadata; + } + + if (Organization::class === $classOrObject || $classOrObject instanceof Organization) { + return $organizationMetadata; + } + + if (Form::class === $classOrObject || $classOrObject instanceof Form) { + return $formMetadata; + } + + return new ClassMetadata(\is_string($classOrObject) ? $classOrObject : $classOrObject::class); + }); + + $validator = Validation::createValidatorBuilder() + ->setMetadataFactory($metadataFactory) + ->getValidator(); + + $form = Forms::createFormFactoryBuilder() + ->addExtension(new ValidatorExtension($validator)) + ->getFormFactory() + ->create(FormTypeTest::TESTED_TYPE, new Organization([]), [ + 'data_class' => Organization::class, + 'by_reference' => false, + ]) + ->add('authors', CollectionTypeTest::TESTED_TYPE, [ + 'entry_type' => AuthorType::class, + 'allow_add' => true, + 'allow_delete' => true, + 'keep_as_list' => false, + ]) + ; + + $form->submit([ + 'authors' => [ + 0 => [ + 'firstName' => '', // Fires a Not Blank Error + 'lastName' => 'lastName1', + ], + // key "1" could be missing if we add 4 blank form entries and then remove it. + 2 => [ + 'firstName' => '', // Fires a Not Blank Error + 'lastName' => 'lastName3', + ], + 3 => [ + 'firstName' => '', // Fires a Not Blank Error + 'lastName' => 'lastName3', + ], + ], + ]); + + // Form does have 3 not blank errors + $errors = $form->getErrors(true); + $this->assertCount(3, $errors); + + // Form behaves as expected. It has index 0, 2 and 3 (1 has been removed) + // But errors property paths mismatch happening with "keep_as_list" option set to false + $errorPaths = [ + $errors[0]->getCause()->getPropertyPath(), + $errors[1]->getCause()->getPropertyPath(), + $errors[2]->getCause()->getPropertyPath(), + ]; + + $this->assertTrue($form->get('authors')->has('0')); + $this->assertContains('data.authors[0].firstName', $errorPaths); + + $this->assertFalse($form->get('authors')->has('1')); + $this->assertContains('data.authors[1].firstName', $errorPaths); + + $this->assertTrue($form->get('authors')->has('2')); + $this->assertContains('data.authors[2].firstName', $errorPaths); + + $this->assertTrue($form->get('authors')->has('3')); + $this->assertNotContains('data.authors[3].firstName', $errorPaths); + + // As result, root form contain errors + $this->assertCount(1, $form->getErrors(false)); + } + + public function testCollectionTypeKeepAsListOptionTrue() + { + $formMetadata = new ClassMetadata(Form::class); + $authorMetadata = (new ClassMetadata(Author::class)) + ->addPropertyConstraint('firstName', new NotBlank()); + $organizationMetadata = (new ClassMetadata(Organization::class)) + ->addPropertyConstraint('authors', new Valid()); + $metadataFactory = $this->createMock(MetadataFactoryInterface::class); + $metadataFactory->expects($this->any()) + ->method('getMetadataFor') + ->willReturnCallback(static function ($classOrObject) use ($formMetadata, $authorMetadata, $organizationMetadata) { + if (Author::class === $classOrObject || $classOrObject instanceof Author) { + return $authorMetadata; + } + + if (Organization::class === $classOrObject || $classOrObject instanceof Organization) { + return $organizationMetadata; + } + + if (Form::class === $classOrObject || $classOrObject instanceof Form) { + return $formMetadata; + } + + return new ClassMetadata(\is_string($classOrObject) ? $classOrObject : $classOrObject::class); + }); + + $validator = Validation::createValidatorBuilder() + ->setMetadataFactory($metadataFactory) + ->getValidator(); + + $form = Forms::createFormFactoryBuilder() + ->addExtension(new ValidatorExtension($validator)) + ->getFormFactory() + ->create(FormTypeTest::TESTED_TYPE, new Organization([]), [ + 'data_class' => Organization::class, + 'by_reference' => false, + ]) + ->add('authors', CollectionTypeTest::TESTED_TYPE, [ + 'entry_type' => AuthorType::class, + 'allow_add' => true, + 'allow_delete' => true, + 'keep_as_list' => true, + ]) + ; + + $form->submit([ + 'authors' => [ + 0 => [ + 'firstName' => '', // Fires a Not Blank Error + 'lastName' => 'lastName1', + ], + // key "1" could be missing if we add 4 blank form entries and then remove it. + 2 => [ + 'firstName' => '', // Fires a Not Blank Error + 'lastName' => 'lastName3', + ], + 3 => [ + 'firstName' => '', // Fires a Not Blank Error + 'lastName' => 'lastName3', + ], + ], + ]); + + // Form does have 3 not blank errors + $errors = $form->getErrors(true); + $this->assertCount(3, $errors); + + // No property paths mismatch happening with "keep_as_list" option set to true + $errorPaths = [ + $errors[0]->getCause()->getPropertyPath(), + $errors[1]->getCause()->getPropertyPath(), + $errors[2]->getCause()->getPropertyPath(), + ]; + + $this->assertTrue($form->get('authors')->has('0')); + $this->assertContains('data.authors[0].firstName', $errorPaths); + + $this->assertTrue($form->get('authors')->has('1')); + $this->assertContains('data.authors[1].firstName', $errorPaths); + + $this->assertTrue($form->get('authors')->has('2')); + $this->assertContains('data.authors[2].firstName', $errorPaths); + + $this->assertFalse($form->get('authors')->has('3')); + $this->assertNotContains('data.authors[3].firstName', $errorPaths); + + // Root form does NOT contain errors + $this->assertCount(0, $form->getErrors(false)); + } } diff --git a/Tests/Fixtures/Organization.php b/Tests/Fixtures/Organization.php new file mode 100644 index 0000000000..db9cee9f96 --- /dev/null +++ b/Tests/Fixtures/Organization.php @@ -0,0 +1,32 @@ +authors = $authors; + } + + public function getAuthors(): array + { + return $this->authors; + } + + public function addAuthor(Author $author): self + { + $this->authors[] = $author; + return $this; + } + + public function removeAuthor(Author $author): self + { + if (false !== $key = array_search($author, $this->authors, true)) { + array_splice($this->authors, $key, 1); + } + return $this; + } +} From b7cb324fdb411a26e5dec51c5063f627189defaa Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Thu, 14 Dec 2023 11:03:37 +0100 Subject: [PATCH 146/208] Set `strict` parameter of `in_array` to true where possible --- Extension/Validator/Constraints/FormValidator.php | 2 +- Test/TypeTestCase.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Extension/Validator/Constraints/FormValidator.php b/Extension/Validator/Constraints/FormValidator.php index 4a05981a86..4163587576 100644 --- a/Extension/Validator/Constraints/FormValidator.php +++ b/Extension/Validator/Constraints/FormValidator.php @@ -120,7 +120,7 @@ public function validate(mixed $form, Constraint $formConstraint): void // Otherwise validate a constraint only once for the first // matching group foreach ($groups as $group) { - if (\in_array($group, $constraint->groups)) { + if (\in_array($group, $constraint->groups, true)) { $groupedConstraints[$group][] = $constraint; // Prevent duplicate validation diff --git a/Test/TypeTestCase.php b/Test/TypeTestCase.php index 5d4c2ba9c6..960b44228b 100644 --- a/Test/TypeTestCase.php +++ b/Test/TypeTestCase.php @@ -32,7 +32,7 @@ protected function getExtensions() { $extensions = []; - if (\in_array(ValidatorExtensionTrait::class, class_uses($this))) { + if (\in_array(ValidatorExtensionTrait::class, class_uses($this), true)) { $extensions[] = $this->getValidatorExtension(); } From a55a75f0c1576663c436c180a6037da71a845057 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz Date: Mon, 18 Dec 2023 08:46:12 +0100 Subject: [PATCH 147/208] Code updates --- Console/Descriptor/Descriptor.php | 2 +- Extension/Core/Type/ChoiceType.php | 2 +- Util/OrderedHashMapIterator.php | 4 ---- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/Console/Descriptor/Descriptor.php b/Console/Descriptor/Descriptor.php index b8d0399ee1..f4835fb1ee 100644 --- a/Console/Descriptor/Descriptor.php +++ b/Console/Descriptor/Descriptor.php @@ -128,7 +128,7 @@ protected function getOptionDefinition(OptionsResolver $optionsResolver, string } } - if (isset($definition['deprecation']) && isset($definition['deprecation']['message']) && \is_string($definition['deprecation']['message'])) { + if (isset($definition['deprecation']['message']) && \is_string($definition['deprecation']['message'])) { $definition['deprecationMessage'] = strtr($definition['deprecation']['message'], ['%name%' => $option]); $definition['deprecationPackage'] = $definition['deprecation']['package']; $definition['deprecationVersion'] = $definition['deprecation']['version']; diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 0030a835ff..8cdf89e511 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -437,7 +437,7 @@ private function createChoiceList(array $options): ChoiceListInterface } // Harden against NULL values (like in EntityType and ModelType) - $choices = null !== $options['choices'] ? $options['choices'] : []; + $choices = $options['choices'] ?? []; return $this->choiceListFactory->createListFromChoices( $choices, diff --git a/Util/OrderedHashMapIterator.php b/Util/OrderedHashMapIterator.php index a0c400e21a..4a8eebe61d 100644 --- a/Util/OrderedHashMapIterator.php +++ b/Util/OrderedHashMapIterator.php @@ -98,10 +98,6 @@ public function next(): void public function key(): mixed { - if (null === $this->key) { - return null; - } - return $this->key; } From 2e9671eb5636fd0e9e5085f2a60af8b3535be276 Mon Sep 17 00:00:00 2001 From: Massimiliano Arione Date: Sat, 7 Oct 2023 18:48:28 +0200 Subject: [PATCH 148/208] [Form] add "model_type" option to MoneyType --- CHANGELOG.md | 1 + .../MoneyToLocalizedStringTransformer.php | 7 ++++-- Extension/Core/Type/MoneyType.php | 14 ++++++++++- Tests/Extension/Core/Type/MoneyTypeTest.php | 24 +++++++++++++++++++ 4 files changed, 43 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2035e8f805..d78622d9fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ CHANGELOG * Deprecate not configuring the `default_protocol` option of the `UrlType`, it will default to `null` in 8.0 * Add a `keep_as_list` option to `CollectionType` + * Add a new `model_type` option to `MoneyType`, to be able to cast the transformed value to `integer` 7.0 --- diff --git a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php index fd943cc820..9a768e8979 100644 --- a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php @@ -22,12 +22,14 @@ class MoneyToLocalizedStringTransformer extends NumberToLocalizedStringTransformer { private int $divisor; + private string $modelType; - public function __construct(?int $scale = 2, ?bool $grouping = true, ?int $roundingMode = \NumberFormatter::ROUND_HALFUP, ?int $divisor = 1, string $locale = null) + public function __construct(?int $scale = 2, ?bool $grouping = true, ?int $roundingMode = \NumberFormatter::ROUND_HALFUP, ?int $divisor = 1, string $locale = null, string $modelType = 'float') { parent::__construct($scale ?? 2, $grouping ?? true, $roundingMode, $locale); $this->divisor = $divisor ?? 1; + $this->modelType = $modelType; } /** @@ -62,7 +64,8 @@ public function reverseTransform(mixed $value): int|float|null { $value = parent::reverseTransform($value); if (null !== $value && 1 !== $this->divisor) { - $value = (float) (string) ($value * $this->divisor); + $value = (string) ($value * $this->divisor); + $value = 'integer' === $this->modelType ? (int) $value : (float) $value; } return $value; diff --git a/Extension/Core/Type/MoneyType.php b/Extension/Core/Type/MoneyType.php index c82911a216..e4d402d8d0 100644 --- a/Extension/Core/Type/MoneyType.php +++ b/Extension/Core/Type/MoneyType.php @@ -34,7 +34,8 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $options['grouping'], $options['rounding_mode'], $options['divisor'], - $options['html5'] ? 'en' : null + $options['html5'] ? 'en' : null, + $options['model_type'], )) ; } @@ -59,6 +60,7 @@ public function configureOptions(OptionsResolver $resolver): void 'compound' => false, 'html5' => false, 'invalid_message' => 'Please enter a valid money amount.', + 'model_type' => 'float', ]); $resolver->setAllowedValues('rounding_mode', [ @@ -75,6 +77,8 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('html5', 'bool'); + $resolver->setAllowedValues('model_type', ['float', 'integer']); + $resolver->setNormalizer('grouping', static function (Options $options, $value) { if ($value && $options['html5']) { throw new LogicException('Cannot use the "grouping" option when the "html5" option is enabled.'); @@ -82,6 +86,14 @@ public function configureOptions(OptionsResolver $resolver): void return $value; }); + + $resolver->setNormalizer('model_type', static function (Options $options, $value) { + if ('integer' === $value && 1 === $options['divisor']) { + throw new LogicException('When the "model_type" option is set to "integer", the "divisor" option should not be set to "1".'); + } + + return $value; + }); } public function getBlockPrefix(): string diff --git a/Tests/Extension/Core/Type/MoneyTypeTest.php b/Tests/Extension/Core/Type/MoneyTypeTest.php index b00439b574..75d0729438 100644 --- a/Tests/Extension/Core/Type/MoneyTypeTest.php +++ b/Tests/Extension/Core/Type/MoneyTypeTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Intl\Util\IntlTestHelper; class MoneyTypeTest extends BaseTypeTestCase @@ -123,4 +124,27 @@ public function testHtml5EnablesSpecificFormatting() $this->assertSame('12345.60', $form->createView()->vars['value']); $this->assertSame('number', $form->createView()->vars['type']); } + + public function testDefaultModelType() + { + $form = $this->factory->create(static::TESTED_TYPE, null, ['divisor' => 100]); + $form->submit('12345.67'); + + $this->assertSame(1234567.0, $form->getData()); + } + + public function testIntegerModelType() + { + $form = $this->factory->create(static::TESTED_TYPE, null, ['divisor' => 100, 'model_type' => 'integer']); + $form->submit('12345.67'); + + $this->assertSame(1234567, $form->getData()); + } + + public function testIntegerModelTypeExpectsDivisorNotEqualToOne() + { + $this->expectException(LogicException::class); + + $form = $this->factory->create(static::TESTED_TYPE, null, ['divisor' => 1, 'model_type' => 'integer']); + } } From 766c600d0b542d29a7fba1bb4d225d358cdc3a59 Mon Sep 17 00:00:00 2001 From: Thomas Landauer Date: Fri, 1 Dec 2023 18:09:28 +0100 Subject: [PATCH 149/208] [Form] Adding `@var` PHPDoc to silence psalm --- Extension/Core/Type/ChoiceType.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 1cc25c3b6e..63ac90a967 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -30,6 +30,7 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView; use Symfony\Component\Form\ChoiceList\View\ChoiceListView; use Symfony\Component\Form\ChoiceList\View\ChoiceView; +use Symfony\Component\Form\Event\PreSubmitEvent; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataMapper\CheckboxListMapper; use Symfony\Component\Form\Extension\Core\DataMapper\RadioListMapper; @@ -101,6 +102,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) // Make sure that scalar, submitted values are converted to arrays // which can be submitted to the checkboxes/radio buttons $builder->addEventListener(FormEvents::PRE_SUBMIT, static function (FormEvent $event) use ($choiceList, $options, &$unknownValues) { + /** @var PreSubmitEvent $event */ $form = $event->getForm(); $data = $event->getData(); From 4c4ac299ea5cd57b0398ddb8c2492634831ed88a Mon Sep 17 00:00:00 2001 From: Thomas Landauer Date: Tue, 2 Jan 2024 14:41:09 +0100 Subject: [PATCH 150/208] [Form] Adding more `@var` PHPDoc's to silence psalm --- Extension/Core/Type/FileType.php | 2 ++ Extension/Core/Type/TimeType.php | 2 ++ 2 files changed, 4 insertions(+) diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index cf8e1a7439..3f430dafad 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\Event\PreSubmitEvent; use Symfony\Component\Form\FileUploadError; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormEvent; @@ -48,6 +49,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) { // Ensure that submitted data is always an uploaded file or an array of some $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($options) { + /** @var PreSubmitEvent $event */ $form = $event->getForm(); $requestHandler = $form->getConfig()->getRequestHandler(); diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 623259f17a..512a830bb2 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -18,6 +18,7 @@ use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToArrayTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToTimestampTransformer; +use Symfony\Component\Form\Event\PreSubmitEvent; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; @@ -62,6 +63,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) if ('single_text' === $options['widget']) { $builder->addEventListener(FormEvents::PRE_SUBMIT, static function (FormEvent $e) use ($options) { + /** @var PreSubmitEvent $event */ $data = $e->getData(); if ($data && preg_match('/^(?P\d{2}):(?P\d{2})(?::(?P\d{2})(?:\.\d+)?)?$/', $data, $matches)) { if ($options['with_seconds']) { From 748adbda62e1aebfb00b42f1c3ee10393629e076 Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Wed, 3 Jan 2024 09:34:12 +0100 Subject: [PATCH 151/208] [Form] Fix assigning data in PostSetDataEvent and PostSubmitEvent --- Event/PostSetDataEvent.php | 2 +- Event/PostSubmitEvent.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Event/PostSetDataEvent.php b/Event/PostSetDataEvent.php index b42012d682..7d551f8b52 100644 --- a/Event/PostSetDataEvent.php +++ b/Event/PostSetDataEvent.php @@ -11,7 +11,6 @@ namespace Symfony\Component\Form\Event; -use Symfony\Component\Form\Exception\BadMethodCallException; use Symfony\Component\Form\FormEvent; /** @@ -29,5 +28,6 @@ public function setData(mixed $data): void { trigger_deprecation('symfony/form', '6.4', 'Calling "%s()" will throw an exception as of 7.0, listen to "form.pre_set_data" instead.', __METHOD__); // throw new BadMethodCallException('Form data cannot be changed during "form.post_set_data", you should use "form.pre_set_data" instead.'); + parent::setData($data); } } diff --git a/Event/PostSubmitEvent.php b/Event/PostSubmitEvent.php index b7fb10176a..5ce6d8ecb7 100644 --- a/Event/PostSubmitEvent.php +++ b/Event/PostSubmitEvent.php @@ -28,5 +28,6 @@ public function setData(mixed $data): void { trigger_deprecation('symfony/form', '6.4', 'Calling "%s()" will throw an exception as of 7.0, listen to "form.pre_submit" or "form.submit" instead.', __METHOD__); // throw new BadMethodCallException('Form data cannot be changed during "form.post_submit", you should use "form.pre_submit" or "form.submit" instead.'); + parent::setData($data); } } From ad695cdadbdbde7c219267ee5c3ea591b3cccbd3 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Fri, 5 Jan 2024 10:21:56 +0100 Subject: [PATCH 152/208] update conflict rules --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index e501777d67..0042f8b6dc 100644 --- a/composer.json +++ b/composer.json @@ -50,7 +50,7 @@ "symfony/error-handler": "<5.4", "symfony/framework-bundle": "<5.4", "symfony/http-kernel": "<5.4", - "symfony/translation": "<5.4.35|>=6.0,<6.3.12|>=6.4,<6.4.3", + "symfony/translation": "<5.4.35|>=6.0,<6.3.12|>=6.4,<6.4.3|>=7.0,<7.0.3", "symfony/translation-contracts": "<2.5", "symfony/twig-bridge": "<6.3" }, From 27b742805ea29e858259856786a657d2d7fdd429 Mon Sep 17 00:00:00 2001 From: mboultoureau Date: Fri, 3 Nov 2023 22:00:57 +0100 Subject: [PATCH 153/208] [Form] Add option `separator` to `ChoiceType` to use a custom separator after preferred choices --- CHANGELOG.md | 1 + Extension/Core/Type/ChoiceType.php | 7 ++++++- Tests/Fixtures/Descriptor/resolved_form_type_1.json | 4 +++- Tests/Fixtures/Descriptor/resolved_form_type_1.txt | 4 ++-- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 273a71c0cd..eb374a589d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ CHANGELOG 7.1 --- + * Add option `separator` to `ChoiceType` to use a custom separator after preferred choices (use the new `separator_html` option to display the separator text as HTML) * Deprecate not configuring the `default_protocol` option of the `UrlType`, it will default to `null` in 8.0 7.0 diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 0030a835ff..8d4584761c 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -234,7 +234,8 @@ public function buildView(FormView $view, FormInterface $form, array $options): 'expanded' => $options['expanded'], 'preferred_choices' => $choiceListView->preferredChoices, 'choices' => $choiceListView->choices, - 'separator' => '-------------------', + 'separator' => $options['separator'], + 'separator_html' => $options['separator_html'], 'placeholder' => null, 'placeholder_attr' => [], 'choice_translation_domain' => $choiceTranslationDomain, @@ -342,6 +343,8 @@ public function configureOptions(OptionsResolver $resolver): void 'choice_attr' => null, 'choice_translation_parameters' => [], 'preferred_choices' => [], + 'separator' => '-------------------', + 'separator_html' => false, 'duplicate_preferred_choices' => true, 'group_by' => null, 'empty_data' => $emptyData, @@ -372,6 +375,8 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('choice_translation_parameters', ['null', 'array', 'callable', ChoiceTranslationParameters::class]); $resolver->setAllowedTypes('placeholder_attr', ['array']); $resolver->setAllowedTypes('preferred_choices', ['array', \Traversable::class, 'callable', 'string', PropertyPath::class, PreferredChoice::class]); + $resolver->setAllowedTypes('separator', ['string']); + $resolver->setAllowedTypes('separator_html', ['bool']); $resolver->setAllowedTypes('duplicate_preferred_choices', 'bool'); $resolver->setAllowedTypes('group_by', ['null', 'callable', 'string', PropertyPath::class, GroupBy::class]); } diff --git a/Tests/Fixtures/Descriptor/resolved_form_type_1.json b/Tests/Fixtures/Descriptor/resolved_form_type_1.json index 27371fd6f6..e071ec712f 100644 --- a/Tests/Fixtures/Descriptor/resolved_form_type_1.json +++ b/Tests/Fixtures/Descriptor/resolved_form_type_1.json @@ -18,7 +18,9 @@ "multiple", "placeholder", "placeholder_attr", - "preferred_choices" + "preferred_choices", + "separator", + "separator_html" ], "overridden": { "Symfony\\Component\\Form\\Extension\\Core\\Type\\FormType": [ diff --git a/Tests/Fixtures/Descriptor/resolved_form_type_1.txt b/Tests/Fixtures/Descriptor/resolved_form_type_1.txt index c8aee5e783..005bfd3e96 100644 --- a/Tests/Fixtures/Descriptor/resolved_form_type_1.txt +++ b/Tests/Fixtures/Descriptor/resolved_form_type_1.txt @@ -21,8 +21,8 @@ Symfony\Component\Form\Extension\Core\Type\ChoiceType (Block prefix: "choice") placeholder getter placeholder_attr help preferred_choices help_attr - help_html - help_translation_parameters + separator help_html + separator_html help_translation_parameters inherit_data invalid_message_parameters is_empty_callback From 2edb77e94354996c83140b5ebb8f07934457f749 Mon Sep 17 00:00:00 2001 From: Dariusz Ruminski Date: Mon, 15 Jan 2024 20:49:54 +0100 Subject: [PATCH 154/208] CS: enable ordered_types.null_adjustment=always_last --- FormRegistry.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FormRegistry.php b/FormRegistry.php index ab3f55f9fb..cf8f66b40b 100644 --- a/FormRegistry.php +++ b/FormRegistry.php @@ -33,7 +33,7 @@ class FormRegistry implements FormRegistryInterface */ private array $types = []; - private FormTypeGuesserInterface|null|false $guesser = false; + private FormTypeGuesserInterface|false|null $guesser = false; private ResolvedFormTypeFactoryInterface $resolvedTypeFactory; private array $checkedTypes = []; From 8a2b584b1c4dcba39c6779b48113e0675c0149a6 Mon Sep 17 00:00:00 2001 From: Oskar Stark Date: Wed, 10 Jan 2024 17:41:00 +0100 Subject: [PATCH 155/208] [Filesystem][Finder][Form] Use CPP --- AbstractRendererEngine.php | 8 ++---- Button.php | 7 ++--- ButtonBuilder.php | 8 +++--- ChoiceList/LazyChoiceList.php | 12 ++++---- ChoiceList/View/ChoiceGroupView.php | 11 +++----- ChoiceList/View/ChoiceListView.php | 11 +++----- ChoiceList/View/ChoiceView.php | 28 +++++-------------- Command/DebugCommand.php | 24 ++++++---------- Extension/Core/CoreExtension.php | 9 +++--- Extension/Core/DataAccessor/ChainAccessor.php | 8 ++---- .../ArrayToPartsTransformer.php | 8 ++---- .../ChoiceToValueTransformer.php | 8 ++---- .../ChoicesToValuesTransformer.php | 8 ++---- .../DataTransformer/DataTransformerChain.php | 8 ++---- .../DateIntervalToArrayTransformer.php | 8 +++--- .../DateIntervalToStringTransformer.php | 8 ++---- .../DateTimeToArrayTransformer.php | 11 +++++--- .../DateTimeToLocalizedStringTransformer.php | 14 ++++++---- .../DateTimeZoneToStringTransformer.php | 8 ++---- .../IntlTimeZoneToStringTransformer.php | 8 ++---- .../MoneyToLocalizedStringTransformer.php | 12 +++++--- .../NumberToLocalizedStringTransformer.php | 13 ++++----- .../PercentToLocalizedStringTransformer.php | 12 ++++---- .../StringToFloatTransformer.php | 8 ++---- .../ValueToDuplicatesTransformer.php | 8 ++---- .../EventListener/FixUrlProtocolListener.php | 8 ++---- .../EventListener/MergeCollectionListener.php | 11 +++----- .../Core/EventListener/ResizeFormListener.php | 21 ++++++-------- .../TransformationFailureListener.php | 8 ++---- Extension/Core/Type/ColorType.php | 8 ++---- Extension/Core/Type/FileType.php | 8 ++---- .../Type/TransformationFailureExtension.php | 8 ++---- Extension/Csrf/CsrfExtension.php | 14 ++++------ .../EventListener/CsrfValidationListener.php | 22 ++++++--------- Extension/Csrf/Type/FormTypeCsrfExtension.php | 23 ++++++--------- .../DataCollector/DataCollectorExtension.php | 8 ++---- .../EventListener/DataCollectorListener.php | 8 ++---- Extension/DataCollector/FormDataCollector.php | 9 ++---- .../Proxy/ResolvedTypeDataCollectorProxy.php | 11 +++----- .../ResolvedTypeFactoryDataCollectorProxy.php | 11 +++----- .../DependencyInjectionExtension.php | 13 ++++----- .../EventListener/ValidationListener.php | 11 +++----- .../Type/FormTypeValidatorExtension.php | 11 ++++---- .../Type/UploadValidatorExtension.php | 11 +++----- Extension/Validator/ValidatorExtension.php | 19 ++++--------- Extension/Validator/ValidatorTypeGuesser.php | 8 ++---- .../Validator/ViolationMapper/MappingRule.php | 14 ++++------ .../ViolationMapper/RelativePath.php | 9 +++--- .../ViolationMapper/ViolationMapper.php | 10 +++---- Form.php | 7 ++--- FormConfigBuilder.php | 12 ++++---- FormError.php | 18 +++++------- FormErrorIterator.php | 9 +++--- FormEvent.php | 12 +++----- FormFactory.php | 8 ++---- FormFactoryBuilder.php | 8 ++---- FormRegistry.php | 8 +++--- FormRenderer.php | 10 +++---- FormView.php | 14 ++++------ Guess/TypeGuess.php | 13 ++++----- Guess/ValueGuess.php | 10 +++---- PreloadedExtension.php | 12 ++++---- ResolvedFormType.php | 13 ++++----- ReversedTransformer.php | 8 ++---- Util/OrderedHashMap.php | 15 +++------- Util/OrderedHashMapIterator.php | 16 ++++------- Util/ServerParams.php | 8 ++---- 67 files changed, 299 insertions(+), 454 deletions(-) diff --git a/AbstractRendererEngine.php b/AbstractRendererEngine.php index bccdf69cc5..1968f5a376 100644 --- a/AbstractRendererEngine.php +++ b/AbstractRendererEngine.php @@ -25,8 +25,6 @@ abstract class AbstractRendererEngine implements FormRendererEngineInterface, Re */ public const CACHE_KEY_VAR = 'cache_key'; - protected array $defaultThemes; - /** * @var array[] */ @@ -53,9 +51,9 @@ abstract class AbstractRendererEngine implements FormRendererEngineInterface, Re * @param array $defaultThemes The default themes. The type of these * themes is open to the implementation. */ - public function __construct(array $defaultThemes = []) - { - $this->defaultThemes = $defaultThemes; + public function __construct( + protected array $defaultThemes = [], + ) { } public function setTheme(FormView $view, mixed $themes, bool $useDefaultThemes = true): void diff --git a/Button.php b/Button.php index 67772ccfe1..ef0ee1f9c4 100644 --- a/Button.php +++ b/Button.php @@ -26,15 +26,14 @@ class Button implements \IteratorAggregate, FormInterface { private ?FormInterface $parent = null; - private FormConfigInterface $config; private bool $submitted = false; /** * Creates a new button from a form configuration. */ - public function __construct(FormConfigInterface $config) - { - $this->config = $config; + public function __construct( + private FormConfigInterface $config, + ) { } /** diff --git a/ButtonBuilder.php b/ButtonBuilder.php index e640149bb8..269412f639 100644 --- a/ButtonBuilder.php +++ b/ButtonBuilder.php @@ -31,19 +31,19 @@ class ButtonBuilder implements \IteratorAggregate, FormBuilderInterface private ResolvedFormTypeInterface $type; private string $name; private array $attributes = []; - private array $options; /** * @throws InvalidArgumentException if the name is empty */ - public function __construct(?string $name, array $options = []) - { + public function __construct( + ?string $name, + private array $options = [], + ) { if ('' === $name || null === $name) { throw new InvalidArgumentException('Buttons cannot have empty names.'); } $this->name = $name; - $this->options = $options; FormConfigBuilder::validateName($name); } diff --git a/ChoiceList/LazyChoiceList.php b/ChoiceList/LazyChoiceList.php index b34d3708ab..28f0a2a450 100644 --- a/ChoiceList/LazyChoiceList.php +++ b/ChoiceList/LazyChoiceList.php @@ -27,8 +27,6 @@ */ class LazyChoiceList implements ChoiceListInterface { - private ChoiceLoaderInterface $loader; - /** * The callable creating string values for each choice. * @@ -43,11 +41,13 @@ class LazyChoiceList implements ChoiceListInterface * The callable receives the choice as first and the array key as the second * argument. * - * @param callable|null $value The callable generating the choice values + * @param callable|null $value The callable creating string values for each choice. + * If null, choices are cast to strings. */ - public function __construct(ChoiceLoaderInterface $loader, callable $value = null) - { - $this->loader = $loader; + public function __construct( + private ChoiceLoaderInterface $loader, + callable $value = null, + ) { $this->value = null === $value ? null : $value(...); } diff --git a/ChoiceList/View/ChoiceGroupView.php b/ChoiceList/View/ChoiceGroupView.php index 562515012c..923fab2241 100644 --- a/ChoiceList/View/ChoiceGroupView.php +++ b/ChoiceList/View/ChoiceGroupView.php @@ -20,18 +20,15 @@ */ class ChoiceGroupView implements \IteratorAggregate { - public string $label; - public array $choices; - /** * Creates a new choice group view. * * @param array $choices the choice views in the group */ - public function __construct(string $label, array $choices = []) - { - $this->label = $label; - $this->choices = $choices; + public function __construct( + public string $label, + public array $choices = [], + ) { } /** diff --git a/ChoiceList/View/ChoiceListView.php b/ChoiceList/View/ChoiceListView.php index 15afc4a8a5..f64d10e761 100644 --- a/ChoiceList/View/ChoiceListView.php +++ b/ChoiceList/View/ChoiceListView.php @@ -22,19 +22,16 @@ */ class ChoiceListView { - public array $choices; - public array $preferredChoices; - /** * Creates a new choice list view. * * @param array $choices The choice views * @param array $preferredChoices the preferred choice views */ - public function __construct(array $choices = [], array $preferredChoices = []) - { - $this->choices = $choices; - $this->preferredChoices = $preferredChoices; + public function __construct( + public array $choices = [], + public array $preferredChoices = [], + ) { } /** diff --git a/ChoiceList/View/ChoiceView.php b/ChoiceList/View/ChoiceView.php index 52587fd363..d59a7c947b 100644 --- a/ChoiceList/View/ChoiceView.php +++ b/ChoiceList/View/ChoiceView.php @@ -20,20 +20,6 @@ */ class ChoiceView { - public string|TranslatableInterface|false $label; - public string $value; - public mixed $data; - - /** - * Additional attributes for the HTML tag. - */ - public array $attr; - - /** - * Additional parameters used to translate the label. - */ - public array $labelTranslationParameters; - /** * Creates a new choice view. * @@ -43,12 +29,12 @@ class ChoiceView * @param array $attr Additional attributes for the HTML tag * @param array $labelTranslationParameters Additional parameters used to translate the label */ - public function __construct(mixed $data, string $value, string|TranslatableInterface|false $label, array $attr = [], array $labelTranslationParameters = []) - { - $this->data = $data; - $this->value = $value; - $this->label = $label; - $this->attr = $attr; - $this->labelTranslationParameters = $labelTranslationParameters; + public function __construct( + public mixed $data, + public string $value, + public string|TranslatableInterface|false $label, + public array $attr = [], + public array $labelTranslationParameters = [], + ) { } } diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index a208be3e5b..4d99012298 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -35,23 +35,15 @@ #[AsCommand(name: 'debug:form', description: 'Display form type information')] class DebugCommand extends Command { - private FormRegistryInterface $formRegistry; - private array $namespaces; - private array $types; - private array $extensions; - private array $guessers; - private ?FileLinkFormatter $fileLinkFormatter; - - public function __construct(FormRegistryInterface $formRegistry, array $namespaces = ['Symfony\Component\Form\Extension\Core\Type'], array $types = [], array $extensions = [], array $guessers = [], FileLinkFormatter $fileLinkFormatter = null) - { + public function __construct( + private FormRegistryInterface $formRegistry, + private array $namespaces = ['Symfony\Component\Form\Extension\Core\Type'], + private array $types = [], + private array $extensions = [], + private array $guessers = [], + private ?FileLinkFormatter $fileLinkFormatter = null, + ) { parent::__construct(); - - $this->formRegistry = $formRegistry; - $this->namespaces = $namespaces; - $this->types = $types; - $this->extensions = $extensions; - $this->guessers = $guessers; - $this->fileLinkFormatter = $fileLinkFormatter; } protected function configure(): void diff --git a/Extension/Core/CoreExtension.php b/Extension/Core/CoreExtension.php index 951bf345c0..f9b7cc1394 100644 --- a/Extension/Core/CoreExtension.php +++ b/Extension/Core/CoreExtension.php @@ -30,13 +30,14 @@ class CoreExtension extends AbstractExtension { private PropertyAccessorInterface $propertyAccessor; private ChoiceListFactoryInterface $choiceListFactory; - private ?TranslatorInterface $translator; - public function __construct(PropertyAccessorInterface $propertyAccessor = null, ChoiceListFactoryInterface $choiceListFactory = null, TranslatorInterface $translator = null) - { + public function __construct( + PropertyAccessorInterface $propertyAccessor = null, + ChoiceListFactoryInterface $choiceListFactory = null, + private ?TranslatorInterface $translator = null, + ) { $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor(); $this->choiceListFactory = $choiceListFactory ?? new CachingFactoryDecorator(new PropertyAccessDecorator(new DefaultChoiceListFactory(), $this->propertyAccessor)); - $this->translator = $translator; } protected function loadTypes(): array diff --git a/Extension/Core/DataAccessor/ChainAccessor.php b/Extension/Core/DataAccessor/ChainAccessor.php index ac600f16f0..e7b9da09ea 100644 --- a/Extension/Core/DataAccessor/ChainAccessor.php +++ b/Extension/Core/DataAccessor/ChainAccessor.php @@ -20,14 +20,12 @@ */ class ChainAccessor implements DataAccessorInterface { - private iterable $accessors; - /** * @param DataAccessorInterface[]|iterable $accessors */ - public function __construct(iterable $accessors) - { - $this->accessors = $accessors; + public function __construct( + private iterable $accessors, + ) { } public function getValue(object|array $data, FormInterface $form): mixed diff --git a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php index 9256c0a094..828bd811e5 100644 --- a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php +++ b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php @@ -21,11 +21,9 @@ */ class ArrayToPartsTransformer implements DataTransformerInterface { - private array $partMapping; - - public function __construct(array $partMapping) - { - $this->partMapping = $partMapping; + public function __construct( + private array $partMapping, + ) { } public function transform(mixed $array): mixed diff --git a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php index daec9d7195..52ee25e93e 100644 --- a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php +++ b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php @@ -22,11 +22,9 @@ */ class ChoiceToValueTransformer implements DataTransformerInterface { - private ChoiceListInterface $choiceList; - - public function __construct(ChoiceListInterface $choiceList) - { - $this->choiceList = $choiceList; + public function __construct( + private ChoiceListInterface $choiceList, + ) { } public function transform(mixed $choice): mixed diff --git a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php index f284ff34f9..aa22338549 100644 --- a/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php +++ b/Extension/Core/DataTransformer/ChoicesToValuesTransformer.php @@ -22,11 +22,9 @@ */ class ChoicesToValuesTransformer implements DataTransformerInterface { - private ChoiceListInterface $choiceList; - - public function __construct(ChoiceListInterface $choiceList) - { - $this->choiceList = $choiceList; + public function __construct( + private ChoiceListInterface $choiceList, + ) { } /** diff --git a/Extension/Core/DataTransformer/DataTransformerChain.php b/Extension/Core/DataTransformer/DataTransformerChain.php index ec5def4695..e34be74556 100644 --- a/Extension/Core/DataTransformer/DataTransformerChain.php +++ b/Extension/Core/DataTransformer/DataTransformerChain.php @@ -21,16 +21,14 @@ */ class DataTransformerChain implements DataTransformerInterface { - protected array $transformers; - /** * Uses the given value transformers to transform values. * * @param DataTransformerInterface[] $transformers */ - public function __construct(array $transformers) - { - $this->transformers = $transformers; + public function __construct( + protected array $transformers, + ) { } /** diff --git a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php index 8638e4a842..281769d2e9 100644 --- a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php @@ -42,16 +42,16 @@ class DateIntervalToArrayTransformer implements DataTransformerInterface self::INVERT => 'r', ]; private array $fields; - private bool $pad; /** * @param string[]|null $fields The date fields * @param bool $pad Whether to use padding */ - public function __construct(array $fields = null, bool $pad = false) - { + public function __construct( + array $fields = null, + private bool $pad = false, + ) { $this->fields = $fields ?? ['years', 'months', 'days', 'hours', 'minutes', 'seconds', 'invert']; - $this->pad = $pad; } /** diff --git a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php index 4160f8f34c..e1a3d97246 100644 --- a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php @@ -24,8 +24,6 @@ */ class DateIntervalToStringTransformer implements DataTransformerInterface { - private string $format; - /** * Transforms a \DateInterval instance to a string. * @@ -33,9 +31,9 @@ class DateIntervalToStringTransformer implements DataTransformerInterface * * @param string $format The date format */ - public function __construct(string $format = 'P%yY%mM%dDT%hH%iM%sS') - { - $this->format = $format; + public function __construct( + private string $format = 'P%yY%mM%dDT%hH%iM%sS', + ) { } /** diff --git a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php index 6675d1c24a..0596b0bcdd 100644 --- a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php @@ -23,7 +23,6 @@ */ class DateTimeToArrayTransformer extends BaseDateTimeTransformer { - private bool $pad; private array $fields; private \DateTimeInterface $referenceDate; @@ -33,12 +32,16 @@ class DateTimeToArrayTransformer extends BaseDateTimeTransformer * @param string[]|null $fields The date fields * @param bool $pad Whether to use padding */ - public function __construct(string $inputTimezone = null, string $outputTimezone = null, array $fields = null, bool $pad = false, \DateTimeInterface $referenceDate = null) - { + public function __construct( + string $inputTimezone = null, + string $outputTimezone = null, + array $fields = null, + private bool $pad = false, + \DateTimeInterface $referenceDate = null, + ) { parent::__construct($inputTimezone, $outputTimezone); $this->fields = $fields ?? ['year', 'month', 'day', 'hour', 'minute', 'second']; - $this->pad = $pad; $this->referenceDate = $referenceDate ?? new \DateTimeImmutable('1970-01-01 00:00:00'); } diff --git a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php index 22a5d41b5f..68e23071be 100644 --- a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php @@ -26,8 +26,6 @@ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer { private int $dateFormat; private int $timeFormat; - private ?string $pattern; - private int $calendar; /** * @see BaseDateTimeTransformer::formats for available format options @@ -41,8 +39,14 @@ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer * * @throws UnexpectedTypeException If a format is not supported or if a timezone is not a string */ - public function __construct(string $inputTimezone = null, string $outputTimezone = null, int $dateFormat = null, int $timeFormat = null, int $calendar = \IntlDateFormatter::GREGORIAN, string $pattern = null) - { + public function __construct( + string $inputTimezone = null, + string $outputTimezone = null, + int $dateFormat = null, + int $timeFormat = null, + private int $calendar = \IntlDateFormatter::GREGORIAN, + private ?string $pattern = null, + ) { parent::__construct($inputTimezone, $outputTimezone); $dateFormat ??= \IntlDateFormatter::MEDIUM; @@ -58,8 +62,6 @@ public function __construct(string $inputTimezone = null, string $outputTimezone $this->dateFormat = $dateFormat; $this->timeFormat = $timeFormat; - $this->calendar = $calendar; - $this->pattern = $pattern; } /** diff --git a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php index f7bda17511..50767f7a01 100644 --- a/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeZoneToStringTransformer.php @@ -23,11 +23,9 @@ */ class DateTimeZoneToStringTransformer implements DataTransformerInterface { - private bool $multiple; - - public function __construct(bool $multiple = false) - { - $this->multiple = $multiple; + public function __construct( + private bool $multiple = false, + ) { } public function transform(mixed $dateTimeZone): mixed diff --git a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php index d379164a7a..446a95f708 100644 --- a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php @@ -23,11 +23,9 @@ */ class IntlTimeZoneToStringTransformer implements DataTransformerInterface { - private bool $multiple; - - public function __construct(bool $multiple = false) - { - $this->multiple = $multiple; + public function __construct( + private bool $multiple = false, + ) { } public function transform(mixed $intlTimeZone): mixed diff --git a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php index 9a768e8979..6f8cac989c 100644 --- a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php @@ -22,14 +22,18 @@ class MoneyToLocalizedStringTransformer extends NumberToLocalizedStringTransformer { private int $divisor; - private string $modelType; - public function __construct(?int $scale = 2, ?bool $grouping = true, ?int $roundingMode = \NumberFormatter::ROUND_HALFUP, ?int $divisor = 1, string $locale = null, string $modelType = 'float') - { + public function __construct( + ?int $scale = 2, + ?bool $grouping = true, + ?int $roundingMode = \NumberFormatter::ROUND_HALFUP, + ?int $divisor = 1, + string $locale = null, + private string $modelType = 'float', + ) { parent::__construct($scale ?? 2, $grouping ?? true, $roundingMode, $locale); $this->divisor = $divisor ?? 1; - $this->modelType = $modelType; } /** diff --git a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index 0693e79797..6e1c495aee 100644 --- a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -28,15 +28,14 @@ class NumberToLocalizedStringTransformer implements DataTransformerInterface protected bool $grouping; protected int $roundingMode; - private ?int $scale; - private ?string $locale; - - public function __construct(int $scale = null, ?bool $grouping = false, ?int $roundingMode = \NumberFormatter::ROUND_HALFUP, string $locale = null) - { - $this->scale = $scale; + public function __construct( + private ?int $scale = null, + ?bool $grouping = false, + ?int $roundingMode = \NumberFormatter::ROUND_HALFUP, + private ?string $locale = null, + ) { $this->grouping = $grouping ?? false; $this->roundingMode = $roundingMode ?? \NumberFormatter::ROUND_HALFUP; - $this->locale = $locale; } /** diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index 98d62783c1..cb46708b22 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -33,10 +33,8 @@ class PercentToLocalizedStringTransformer implements DataTransformerInterface self::INTEGER, ]; - private int $roundingMode; private string $type; private int $scale; - private bool $html5Format; /** * @see self::$types for a list of supported types @@ -46,8 +44,12 @@ class PercentToLocalizedStringTransformer implements DataTransformerInterface * * @throws UnexpectedTypeException if the given value of type is unknown */ - public function __construct(int $scale = null, string $type = null, int $roundingMode = \NumberFormatter::ROUND_HALFUP, bool $html5Format = false) - { + public function __construct( + int $scale = null, + string $type = null, + private int $roundingMode = \NumberFormatter::ROUND_HALFUP, + private bool $html5Format = false, + ) { $type ??= self::FRACTIONAL; if (!\in_array($type, self::$types, true)) { @@ -56,8 +58,6 @@ public function __construct(int $scale = null, string $type = null, int $roundin $this->type = $type; $this->scale = $scale ?? 0; - $this->roundingMode = $roundingMode; - $this->html5Format = $html5Format; } /** diff --git a/Extension/Core/DataTransformer/StringToFloatTransformer.php b/Extension/Core/DataTransformer/StringToFloatTransformer.php index 09b5e51faf..f47fcb6254 100644 --- a/Extension/Core/DataTransformer/StringToFloatTransformer.php +++ b/Extension/Core/DataTransformer/StringToFloatTransformer.php @@ -19,11 +19,9 @@ */ class StringToFloatTransformer implements DataTransformerInterface { - private ?int $scale; - - public function __construct(int $scale = null) - { - $this->scale = $scale; + public function __construct( + private ?int $scale = null, + ) { } public function transform(mixed $value): ?float diff --git a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php index 2399abf73c..9700b0424e 100644 --- a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php +++ b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php @@ -21,11 +21,9 @@ */ class ValueToDuplicatesTransformer implements DataTransformerInterface { - private array $keys; - - public function __construct(array $keys) - { - $this->keys = $keys; + public function __construct( + private array $keys, + ) { } /** diff --git a/Extension/Core/EventListener/FixUrlProtocolListener.php b/Extension/Core/EventListener/FixUrlProtocolListener.php index d648d6f508..97cd3ad474 100644 --- a/Extension/Core/EventListener/FixUrlProtocolListener.php +++ b/Extension/Core/EventListener/FixUrlProtocolListener.php @@ -22,14 +22,12 @@ */ class FixUrlProtocolListener implements EventSubscriberInterface { - private ?string $defaultProtocol; - /** * @param string|null $defaultProtocol The URL scheme to add when there is none or null to not modify the data */ - public function __construct(?string $defaultProtocol = 'http') - { - $this->defaultProtocol = $defaultProtocol; + public function __construct( + private ?string $defaultProtocol = 'http', + ) { } public function onSubmit(FormEvent $event): void diff --git a/Extension/Core/EventListener/MergeCollectionListener.php b/Extension/Core/EventListener/MergeCollectionListener.php index 23ee47bd2f..61428d5dfa 100644 --- a/Extension/Core/EventListener/MergeCollectionListener.php +++ b/Extension/Core/EventListener/MergeCollectionListener.php @@ -21,17 +21,14 @@ */ class MergeCollectionListener implements EventSubscriberInterface { - private bool $allowAdd; - private bool $allowDelete; - /** * @param bool $allowAdd Whether values might be added to the collection * @param bool $allowDelete Whether values might be removed from the collection */ - public function __construct(bool $allowAdd = false, bool $allowDelete = false) - { - $this->allowAdd = $allowAdd; - $this->allowDelete = $allowDelete; + public function __construct( + private bool $allowAdd = false, + private bool $allowDelete = false, + ) { } public static function getSubscribedEvents(): array diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index 641f165257..7e432d5af0 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -24,24 +24,21 @@ */ class ResizeFormListener implements EventSubscriberInterface { - protected string $type; - protected array $options; protected array $prototypeOptions; - protected bool $allowAdd; - protected bool $allowDelete; private \Closure|bool $deleteEmpty; - private bool $keepAsList; - public function __construct(string $type, array $options = [], bool $allowAdd = false, bool $allowDelete = false, bool|callable $deleteEmpty = false, array $prototypeOptions = null, bool $keepAsList = false) - { - $this->type = $type; - $this->allowAdd = $allowAdd; - $this->allowDelete = $allowDelete; - $this->options = $options; + public function __construct( + private string $type, + private array $options = [], + private bool $allowAdd = false, + private bool $allowDelete = false, + bool|callable $deleteEmpty = false, + array $prototypeOptions = null, + private bool $keepAsList = false, + ) { $this->deleteEmpty = \is_bool($deleteEmpty) ? $deleteEmpty : $deleteEmpty(...); $this->prototypeOptions = $prototypeOptions ?? $options; - $this->keepAsList = $keepAsList; } public static function getSubscribedEvents(): array diff --git a/Extension/Core/EventListener/TransformationFailureListener.php b/Extension/Core/EventListener/TransformationFailureListener.php index 570a285aae..48f0b9ac9f 100644 --- a/Extension/Core/EventListener/TransformationFailureListener.php +++ b/Extension/Core/EventListener/TransformationFailureListener.php @@ -22,11 +22,9 @@ */ class TransformationFailureListener implements EventSubscriberInterface { - private ?TranslatorInterface $translator; - - public function __construct(TranslatorInterface $translator = null) - { - $this->translator = $translator; + public function __construct( + private ?TranslatorInterface $translator = null, + ) { } public static function getSubscribedEvents(): array diff --git a/Extension/Core/Type/ColorType.php b/Extension/Core/Type/ColorType.php index 476050fbee..d67d6dc73b 100644 --- a/Extension/Core/Type/ColorType.php +++ b/Extension/Core/Type/ColorType.php @@ -26,11 +26,9 @@ class ColorType extends AbstractType */ private const HTML5_PATTERN = '/^#[0-9a-f]{6}$/i'; - private ?TranslatorInterface $translator; - - public function __construct(TranslatorInterface $translator = null) - { - $this->translator = $translator; + public function __construct( + private ?TranslatorInterface $translator = null, + ) { } public function buildForm(FormBuilderInterface $builder, array $options): void diff --git a/Extension/Core/Type/FileType.php b/Extension/Core/Type/FileType.php index 948f897f68..b4b4d86d95 100644 --- a/Extension/Core/Type/FileType.php +++ b/Extension/Core/Type/FileType.php @@ -35,11 +35,9 @@ class FileType extends AbstractType self::MIB_BYTES => 'MiB', ]; - private ?TranslatorInterface $translator; - - public function __construct(TranslatorInterface $translator = null) - { - $this->translator = $translator; + public function __construct( + private ?TranslatorInterface $translator = null, + ) { } public function buildForm(FormBuilderInterface $builder, array $options): void diff --git a/Extension/Core/Type/TransformationFailureExtension.php b/Extension/Core/Type/TransformationFailureExtension.php index 5539e57f9f..e90cd714e8 100644 --- a/Extension/Core/Type/TransformationFailureExtension.php +++ b/Extension/Core/Type/TransformationFailureExtension.php @@ -21,11 +21,9 @@ */ class TransformationFailureExtension extends AbstractTypeExtension { - private ?TranslatorInterface $translator; - - public function __construct(TranslatorInterface $translator = null) - { - $this->translator = $translator; + public function __construct( + private ?TranslatorInterface $translator = null, + ) { } public function buildForm(FormBuilderInterface $builder, array $options): void diff --git a/Extension/Csrf/CsrfExtension.php b/Extension/Csrf/CsrfExtension.php index 026bed3604..33c4616b4c 100644 --- a/Extension/Csrf/CsrfExtension.php +++ b/Extension/Csrf/CsrfExtension.php @@ -22,15 +22,11 @@ */ class CsrfExtension extends AbstractExtension { - private CsrfTokenManagerInterface $tokenManager; - private ?TranslatorInterface $translator; - private ?string $translationDomain; - - public function __construct(CsrfTokenManagerInterface $tokenManager, TranslatorInterface $translator = null, string $translationDomain = null) - { - $this->tokenManager = $tokenManager; - $this->translator = $translator; - $this->translationDomain = $translationDomain; + public function __construct( + private CsrfTokenManagerInterface $tokenManager, + private ?TranslatorInterface $translator = null, + private ?string $translationDomain = null, + ) { } protected function loadTypeExtensions(): array diff --git a/Extension/Csrf/EventListener/CsrfValidationListener.php b/Extension/Csrf/EventListener/CsrfValidationListener.php index dab31fb65f..5b018e8c8a 100644 --- a/Extension/Csrf/EventListener/CsrfValidationListener.php +++ b/Extension/Csrf/EventListener/CsrfValidationListener.php @@ -25,12 +25,6 @@ */ class CsrfValidationListener implements EventSubscriberInterface { - private string $fieldName; - private CsrfTokenManagerInterface $tokenManager; - private string $tokenId; - private string $errorMessage; - private ?TranslatorInterface $translator; - private ?string $translationDomain; private ServerParams $serverParams; public static function getSubscribedEvents(): array @@ -40,14 +34,16 @@ public static function getSubscribedEvents(): array ]; } - public function __construct(string $fieldName, CsrfTokenManagerInterface $tokenManager, string $tokenId, string $errorMessage, TranslatorInterface $translator = null, string $translationDomain = null, ServerParams $serverParams = null) + public function __construct( + private string $fieldName, + private CsrfTokenManagerInterface $tokenManager, + private string $tokenId, + private string $errorMessage, + private ?TranslatorInterface $translator = null, + private ?string $translationDomain = null, + ServerParams $serverParams = null, + ) { - $this->fieldName = $fieldName; - $this->tokenManager = $tokenManager; - $this->tokenId = $tokenId; - $this->errorMessage = $errorMessage; - $this->translator = $translator; - $this->translationDomain = $translationDomain; $this->serverParams = $serverParams ?? new ServerParams(); } diff --git a/Extension/Csrf/Type/FormTypeCsrfExtension.php b/Extension/Csrf/Type/FormTypeCsrfExtension.php index 7096b8957d..0ad4daeb3c 100644 --- a/Extension/Csrf/Type/FormTypeCsrfExtension.php +++ b/Extension/Csrf/Type/FormTypeCsrfExtension.php @@ -28,21 +28,14 @@ */ class FormTypeCsrfExtension extends AbstractTypeExtension { - private CsrfTokenManagerInterface $defaultTokenManager; - private bool $defaultEnabled; - private string $defaultFieldName; - private ?TranslatorInterface $translator; - private ?string $translationDomain; - private ?ServerParams $serverParams; - - public function __construct(CsrfTokenManagerInterface $defaultTokenManager, bool $defaultEnabled = true, string $defaultFieldName = '_token', TranslatorInterface $translator = null, string $translationDomain = null, ServerParams $serverParams = null) - { - $this->defaultTokenManager = $defaultTokenManager; - $this->defaultEnabled = $defaultEnabled; - $this->defaultFieldName = $defaultFieldName; - $this->translator = $translator; - $this->translationDomain = $translationDomain; - $this->serverParams = $serverParams; + public function __construct( + private CsrfTokenManagerInterface $defaultTokenManager, + private bool $defaultEnabled = true, + private string $defaultFieldName = '_token', + private ?TranslatorInterface $translator = null, + private ?string $translationDomain = null, + private ?ServerParams $serverParams = null, + ) { } /** diff --git a/Extension/DataCollector/DataCollectorExtension.php b/Extension/DataCollector/DataCollectorExtension.php index 50b36bd67f..9fb8422447 100644 --- a/Extension/DataCollector/DataCollectorExtension.php +++ b/Extension/DataCollector/DataCollectorExtension.php @@ -21,11 +21,9 @@ */ class DataCollectorExtension extends AbstractExtension { - private FormDataCollectorInterface $dataCollector; - - public function __construct(FormDataCollectorInterface $dataCollector) - { - $this->dataCollector = $dataCollector; + public function __construct( + private FormDataCollectorInterface $dataCollector, + ) { } protected function loadTypeExtensions(): array diff --git a/Extension/DataCollector/EventListener/DataCollectorListener.php b/Extension/DataCollector/EventListener/DataCollectorListener.php index f32dc9bc7d..02cffbeffe 100644 --- a/Extension/DataCollector/EventListener/DataCollectorListener.php +++ b/Extension/DataCollector/EventListener/DataCollectorListener.php @@ -24,11 +24,9 @@ */ class DataCollectorListener implements EventSubscriberInterface { - private FormDataCollectorInterface $dataCollector; - - public function __construct(FormDataCollectorInterface $dataCollector) - { - $this->dataCollector = $dataCollector; + public function __construct( + private FormDataCollectorInterface $dataCollector, + ) { } public static function getSubscribedEvents(): array diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index dab72bb309..f83b7b4951 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -33,8 +33,6 @@ */ class FormDataCollector extends DataCollector implements FormDataCollectorInterface { - private FormDataExtractorInterface $dataExtractor; - /** * Stores the collected data per {@link FormInterface} instance. * @@ -62,14 +60,13 @@ class FormDataCollector extends DataCollector implements FormDataCollectorInterf */ private array $formsByView; - public function __construct(FormDataExtractorInterface $dataExtractor) - { + public function __construct( + private FormDataExtractorInterface $dataExtractor, + ) { if (!class_exists(ClassStub::class)) { throw new \LogicException(sprintf('The VarDumper component is needed for using the "%s" class. Install symfony/var-dumper version 3.4 or above.', __CLASS__)); } - $this->dataExtractor = $dataExtractor; - $this->reset(); } diff --git a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php index 1e922ff2ea..bb16e31890 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeDataCollectorProxy.php @@ -27,13 +27,10 @@ */ class ResolvedTypeDataCollectorProxy implements ResolvedFormTypeInterface { - private ResolvedFormTypeInterface $proxiedType; - private FormDataCollectorInterface $dataCollector; - - public function __construct(ResolvedFormTypeInterface $proxiedType, FormDataCollectorInterface $dataCollector) - { - $this->proxiedType = $proxiedType; - $this->dataCollector = $dataCollector; + public function __construct( + private ResolvedFormTypeInterface $proxiedType, + private FormDataCollectorInterface $dataCollector, + ) { } public function getBlockPrefix(): string diff --git a/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php b/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php index eea5bfd4ae..898c5dfa80 100644 --- a/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php +++ b/Extension/DataCollector/Proxy/ResolvedTypeFactoryDataCollectorProxy.php @@ -24,13 +24,10 @@ */ class ResolvedTypeFactoryDataCollectorProxy implements ResolvedFormTypeFactoryInterface { - private ResolvedFormTypeFactoryInterface $proxiedFactory; - private FormDataCollectorInterface $dataCollector; - - public function __construct(ResolvedFormTypeFactoryInterface $proxiedFactory, FormDataCollectorInterface $dataCollector) - { - $this->proxiedFactory = $proxiedFactory; - $this->dataCollector = $dataCollector; + public function __construct( + private ResolvedFormTypeFactoryInterface $proxiedFactory, + private FormDataCollectorInterface $dataCollector, + ) { } public function createResolvedType(FormTypeInterface $type, array $typeExtensions, ResolvedFormTypeInterface $parent = null): ResolvedFormTypeInterface diff --git a/Extension/DependencyInjection/DependencyInjectionExtension.php b/Extension/DependencyInjection/DependencyInjectionExtension.php index 6564bd5657..420f26b743 100644 --- a/Extension/DependencyInjection/DependencyInjectionExtension.php +++ b/Extension/DependencyInjection/DependencyInjectionExtension.php @@ -23,18 +23,15 @@ class DependencyInjectionExtension implements FormExtensionInterface { private ?FormTypeGuesserChain $guesser = null; private bool $guesserLoaded = false; - private ContainerInterface $typeContainer; - private array $typeExtensionServices; - private iterable $guesserServices; /** * @param array> $typeExtensionServices */ - public function __construct(ContainerInterface $typeContainer, array $typeExtensionServices, iterable $guesserServices) - { - $this->typeContainer = $typeContainer; - $this->typeExtensionServices = $typeExtensionServices; - $this->guesserServices = $guesserServices; + public function __construct( + private ContainerInterface $typeContainer, + private array $typeExtensionServices, + private iterable $guesserServices, + ) { } public function getType(string $name): FormTypeInterface diff --git a/Extension/Validator/EventListener/ValidationListener.php b/Extension/Validator/EventListener/ValidationListener.php index d24264f244..b3c16dbad2 100644 --- a/Extension/Validator/EventListener/ValidationListener.php +++ b/Extension/Validator/EventListener/ValidationListener.php @@ -23,18 +23,15 @@ */ class ValidationListener implements EventSubscriberInterface { - private ValidatorInterface $validator; - private ViolationMapperInterface $violationMapper; - public static function getSubscribedEvents(): array { return [FormEvents::POST_SUBMIT => 'validateForm']; } - public function __construct(ValidatorInterface $validator, ViolationMapperInterface $violationMapper) - { - $this->validator = $validator; - $this->violationMapper = $violationMapper; + public function __construct( + private ValidatorInterface $validator, + private ViolationMapperInterface $violationMapper, + ) { } public function validateForm(FormEvent $event): void diff --git a/Extension/Validator/Type/FormTypeValidatorExtension.php b/Extension/Validator/Type/FormTypeValidatorExtension.php index e904a4f16e..82ee63399d 100644 --- a/Extension/Validator/Type/FormTypeValidatorExtension.php +++ b/Extension/Validator/Type/FormTypeValidatorExtension.php @@ -27,13 +27,14 @@ */ class FormTypeValidatorExtension extends BaseValidatorExtension { - private ValidatorInterface $validator; private ViolationMapper $violationMapper; - private bool $legacyErrorMessages; - public function __construct(ValidatorInterface $validator, bool $legacyErrorMessages = true, FormRendererInterface $formRenderer = null, TranslatorInterface $translator = null) - { - $this->validator = $validator; + public function __construct( + private ValidatorInterface $validator, + private bool $legacyErrorMessages = true, + FormRendererInterface $formRenderer = null, + TranslatorInterface $translator = null, + ) { $this->violationMapper = new ViolationMapper($formRenderer, $translator); } diff --git a/Extension/Validator/Type/UploadValidatorExtension.php b/Extension/Validator/Type/UploadValidatorExtension.php index 80e3315ae9..7c1e965aba 100644 --- a/Extension/Validator/Type/UploadValidatorExtension.php +++ b/Extension/Validator/Type/UploadValidatorExtension.php @@ -23,13 +23,10 @@ */ class UploadValidatorExtension extends AbstractTypeExtension { - private TranslatorInterface $translator; - private ?string $translationDomain; - - public function __construct(TranslatorInterface $translator, string $translationDomain = null) - { - $this->translator = $translator; - $this->translationDomain = $translationDomain; + public function __construct( + private TranslatorInterface $translator, + private ?string $translationDomain = null, + ) { } public function configureOptions(OptionsResolver $resolver): void diff --git a/Extension/Validator/ValidatorExtension.php b/Extension/Validator/ValidatorExtension.php index fe1bd33f5f..522a769629 100644 --- a/Extension/Validator/ValidatorExtension.php +++ b/Extension/Validator/ValidatorExtension.php @@ -27,15 +27,12 @@ */ class ValidatorExtension extends AbstractExtension { - private ValidatorInterface $validator; - private ?FormRendererInterface $formRenderer; - private ?TranslatorInterface $translator; - private bool $legacyErrorMessages; - - public function __construct(ValidatorInterface $validator, bool $legacyErrorMessages = true, FormRendererInterface $formRenderer = null, TranslatorInterface $translator = null) - { - $this->legacyErrorMessages = $legacyErrorMessages; - + public function __construct( + private ValidatorInterface $validator, + private bool $legacyErrorMessages = true, + private ?FormRendererInterface $formRenderer = null, + private ?TranslatorInterface $translator = null, + ) { $metadata = $validator->getMetadataFor(\Symfony\Component\Form\Form::class); // Register the form constraints in the validator programmatically. @@ -46,10 +43,6 @@ public function __construct(ValidatorInterface $validator, bool $legacyErrorMess /* @var $metadata ClassMetadata */ $metadata->addConstraint(new Form()); $metadata->addConstraint(new Traverse(false)); - - $this->validator = $validator; - $this->formRenderer = $formRenderer; - $this->translator = $translator; } public function loadTypeGuesser(): ?FormTypeGuesserInterface diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index 57bccaa39f..72ae8ddd57 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -57,11 +57,9 @@ class ValidatorTypeGuesser implements FormTypeGuesserInterface { - private MetadataFactoryInterface $metadataFactory; - - public function __construct(MetadataFactoryInterface $metadataFactory) - { - $this->metadataFactory = $metadataFactory; + public function __construct( + private MetadataFactoryInterface $metadataFactory, + ) { } public function guessType(string $class, string $property): ?TypeGuess diff --git a/Extension/Validator/ViolationMapper/MappingRule.php b/Extension/Validator/ViolationMapper/MappingRule.php index 6e33f22297..f9a61cc817 100644 --- a/Extension/Validator/ViolationMapper/MappingRule.php +++ b/Extension/Validator/ViolationMapper/MappingRule.php @@ -19,15 +19,11 @@ */ class MappingRule { - private FormInterface $origin; - private string $propertyPath; - private string $targetPath; - - public function __construct(FormInterface $origin, string $propertyPath, string $targetPath) - { - $this->origin = $origin; - $this->propertyPath = $propertyPath; - $this->targetPath = $targetPath; + public function __construct( + private FormInterface $origin, + private string $propertyPath, + private string $targetPath, + ) { } public function getOrigin(): FormInterface diff --git a/Extension/Validator/ViolationMapper/RelativePath.php b/Extension/Validator/ViolationMapper/RelativePath.php index 0384edb444..dbf0712e2f 100644 --- a/Extension/Validator/ViolationMapper/RelativePath.php +++ b/Extension/Validator/ViolationMapper/RelativePath.php @@ -19,13 +19,12 @@ */ class RelativePath extends PropertyPath { - private FormInterface $root; - - public function __construct(FormInterface $root, string $propertyPath) + public function __construct( + private FormInterface $root, + string $propertyPath, + ) { parent::__construct($propertyPath); - - $this->root = $root; } public function getRoot(): FormInterface diff --git a/Extension/Validator/ViolationMapper/ViolationMapper.php b/Extension/Validator/ViolationMapper/ViolationMapper.php index fca010d70e..faca255b5d 100644 --- a/Extension/Validator/ViolationMapper/ViolationMapper.php +++ b/Extension/Validator/ViolationMapper/ViolationMapper.php @@ -28,14 +28,12 @@ */ class ViolationMapper implements ViolationMapperInterface { - private ?FormRendererInterface $formRenderer; - private ?TranslatorInterface $translator; private bool $allowNonSynchronized = false; - public function __construct(FormRendererInterface $formRenderer = null, TranslatorInterface $translator = null) - { - $this->formRenderer = $formRenderer; - $this->translator = $translator; + public function __construct( + private ?FormRendererInterface $formRenderer = null, + private ?TranslatorInterface $translator = null, + ) { } public function mapViolation(ConstraintViolation $violation, FormInterface $form, bool $allowNonSynchronized = false): void diff --git a/Form.php b/Form.php index 88c4376619..7ff939a2d8 100644 --- a/Form.php +++ b/Form.php @@ -70,7 +70,6 @@ */ class Form implements \IteratorAggregate, FormInterface, ClearableErrorsInterface { - private FormConfigInterface $config; private ?FormInterface $parent = null; /** @@ -135,8 +134,9 @@ class Form implements \IteratorAggregate, FormInterface, ClearableErrorsInterfac /** * @throws LogicException if a data mapper is not provided for a compound form */ - public function __construct(FormConfigInterface $config) - { + public function __construct( + private FormConfigInterface $config, + ) { // Compound forms always need a data mapper, otherwise calls to // `setData` and `add` will not lead to the correct population of // the child forms. @@ -150,7 +150,6 @@ public function __construct(FormConfigInterface $config) $this->defaultDataSet = true; } - $this->config = $config; $this->children = new OrderedHashMap(); $this->name = $config->getName(); } diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index 49aa89ab04..e0fb01dad9 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -33,7 +33,6 @@ class FormConfigBuilder implements FormConfigBuilderInterface */ private static NativeRequestHandler $nativeRequestHandler; - private EventDispatcherInterface $dispatcher; private string $name; private ?PropertyPathInterface $propertyPath = null; private bool $mapped = true; @@ -57,7 +56,6 @@ class FormConfigBuilder implements FormConfigBuilderInterface private string $method = 'POST'; private RequestHandlerInterface $requestHandler; private bool $autoInitialize = false; - private array $options; private ?\Closure $isEmptyCallback = null; /** @@ -69,8 +67,12 @@ class FormConfigBuilder implements FormConfigBuilderInterface * @throws InvalidArgumentException if the data class is not a valid class or if * the name contains invalid characters */ - public function __construct(?string $name, ?string $dataClass, EventDispatcherInterface $dispatcher, array $options = []) - { + public function __construct( + ?string $name, + ?string $dataClass, + private EventDispatcherInterface $dispatcher, + private array $options = [], + ) { self::validateName($name); if (null !== $dataClass && !class_exists($dataClass) && !interface_exists($dataClass, false)) { @@ -79,8 +81,6 @@ public function __construct(?string $name, ?string $dataClass, EventDispatcherIn $this->name = (string) $name; $this->dataClass = $dataClass; - $this->dispatcher = $dispatcher; - $this->options = $options; } public function addEventListener(string $eventName, callable $listener, int $priority = 0): static diff --git a/FormError.php b/FormError.php index face43bcef..7c3f5dd0bc 100644 --- a/FormError.php +++ b/FormError.php @@ -21,11 +21,6 @@ class FormError { protected string $messageTemplate; - protected array $messageParameters; - protected ?int $messagePluralization; - - private string $message; - private mixed $cause; /** * The form that spawned this error. @@ -45,13 +40,14 @@ class FormError * * @see \Symfony\Component\Translation\Translator */ - public function __construct(string $message, string $messageTemplate = null, array $messageParameters = [], int $messagePluralization = null, mixed $cause = null) - { - $this->message = $message; + public function __construct( + private string $message, + string $messageTemplate = null, + protected array $messageParameters = [], + protected ?int $messagePluralization = null, + private mixed $cause = null, + ) { $this->messageTemplate = $messageTemplate ?: $message; - $this->messageParameters = $messageParameters; - $this->messagePluralization = $messagePluralization; - $this->cause = $cause; } /** diff --git a/FormErrorIterator.php b/FormErrorIterator.php index 42de0c8358..a614e72c2e 100644 --- a/FormErrorIterator.php +++ b/FormErrorIterator.php @@ -42,8 +42,6 @@ class FormErrorIterator implements \RecursiveIterator, \SeekableIterator, \Array */ public const INDENTATION = ' '; - private FormInterface $form; - /** * @var list */ @@ -54,15 +52,16 @@ class FormErrorIterator implements \RecursiveIterator, \SeekableIterator, \Array * * @throws InvalidArgumentException If the errors are invalid */ - public function __construct(FormInterface $form, array $errors) - { + public function __construct( + private FormInterface $form, + array $errors, + ) { foreach ($errors as $error) { if (!($error instanceof FormError || $error instanceof self)) { throw new InvalidArgumentException(sprintf('The errors must be instances of "Symfony\Component\Form\FormError" or "%s". Got: "%s".', __CLASS__, get_debug_type($error))); } } - $this->form = $form; $this->errors = $errors; } diff --git a/FormEvent.php b/FormEvent.php index e46fbb6a6a..e6a3878f6d 100644 --- a/FormEvent.php +++ b/FormEvent.php @@ -18,14 +18,10 @@ */ class FormEvent extends Event { - protected mixed $data; - - private FormInterface $form; - - public function __construct(FormInterface $form, mixed $data) - { - $this->form = $form; - $this->data = $data; + public function __construct( + private FormInterface $form, + protected mixed $data, + ) { } /** diff --git a/FormFactory.php b/FormFactory.php index 9e1234f831..dcf7b36f28 100644 --- a/FormFactory.php +++ b/FormFactory.php @@ -16,11 +16,9 @@ class FormFactory implements FormFactoryInterface { - private FormRegistryInterface $registry; - - public function __construct(FormRegistryInterface $registry) - { - $this->registry = $registry; + public function __construct( + private FormRegistryInterface $registry, + ) { } public function create(string $type = FormType::class, mixed $data = null, array $options = []): FormInterface diff --git a/FormFactoryBuilder.php b/FormFactoryBuilder.php index 42b8dec9f4..90e3bf20ca 100644 --- a/FormFactoryBuilder.php +++ b/FormFactoryBuilder.php @@ -20,8 +20,6 @@ */ class FormFactoryBuilder implements FormFactoryBuilderInterface { - private bool $forceCoreExtension; - private ResolvedFormTypeFactoryInterface $resolvedTypeFactory; /** @@ -44,9 +42,9 @@ class FormFactoryBuilder implements FormFactoryBuilderInterface */ private array $typeGuessers = []; - public function __construct(bool $forceCoreExtension = false) - { - $this->forceCoreExtension = $forceCoreExtension; + public function __construct( + private bool $forceCoreExtension = false, + ) { } public function setResolvedTypeFactory(ResolvedFormTypeFactoryInterface $resolvedTypeFactory): static diff --git a/FormRegistry.php b/FormRegistry.php index cf8f66b40b..95a0077378 100644 --- a/FormRegistry.php +++ b/FormRegistry.php @@ -34,7 +34,6 @@ class FormRegistry implements FormRegistryInterface private array $types = []; private FormTypeGuesserInterface|false|null $guesser = false; - private ResolvedFormTypeFactoryInterface $resolvedTypeFactory; private array $checkedTypes = []; /** @@ -42,8 +41,10 @@ class FormRegistry implements FormRegistryInterface * * @throws UnexpectedTypeException if any extension does not implement FormExtensionInterface */ - public function __construct(array $extensions, ResolvedFormTypeFactoryInterface $resolvedTypeFactory) - { + public function __construct( + array $extensions, + private ResolvedFormTypeFactoryInterface $resolvedTypeFactory, + ) { foreach ($extensions as $extension) { if (!$extension instanceof FormExtensionInterface) { throw new UnexpectedTypeException($extension, FormExtensionInterface::class); @@ -51,7 +52,6 @@ public function __construct(array $extensions, ResolvedFormTypeFactoryInterface } $this->extensions = $extensions; - $this->resolvedTypeFactory = $resolvedTypeFactory; } public function getType(string $name): ResolvedFormTypeInterface diff --git a/FormRenderer.php b/FormRenderer.php index c2771d28c9..a9ffd4f41e 100644 --- a/FormRenderer.php +++ b/FormRenderer.php @@ -25,16 +25,14 @@ class FormRenderer implements FormRendererInterface { public const CACHE_KEY_VAR = 'unique_block_prefix'; - private FormRendererEngineInterface $engine; - private ?CsrfTokenManagerInterface $csrfTokenManager; private array $blockNameHierarchyMap = []; private array $hierarchyLevelMap = []; private array $variableStack = []; - public function __construct(FormRendererEngineInterface $engine, CsrfTokenManagerInterface $csrfTokenManager = null) - { - $this->engine = $engine; - $this->csrfTokenManager = $csrfTokenManager; + public function __construct( + private FormRendererEngineInterface $engine, + private ?CsrfTokenManagerInterface $csrfTokenManager = null, + ) { } public function getEngine(): FormRendererEngineInterface diff --git a/FormView.php b/FormView.php index e9e9e9957b..93804bb879 100644 --- a/FormView.php +++ b/FormView.php @@ -29,11 +29,6 @@ class FormView implements \ArrayAccess, \IteratorAggregate, \Countable 'attr' => [], ]; - /** - * The parent view. - */ - public ?self $parent = null; - /** * The child views. * @@ -52,9 +47,12 @@ class FormView implements \ArrayAccess, \IteratorAggregate, \Countable private bool $methodRendered = false; - public function __construct(self $parent = null) - { - $this->parent = $parent; + /** + * @param FormView|null $parent The parent view + */ + public function __construct( + public ?self $parent = null, + ) { } /** diff --git a/Guess/TypeGuess.php b/Guess/TypeGuess.php index 8ede78eb8c..b62873daa4 100644 --- a/Guess/TypeGuess.php +++ b/Guess/TypeGuess.php @@ -19,9 +19,6 @@ */ class TypeGuess extends Guess { - private string $type; - private array $options; - /** * @param string $type The guessed field type * @param array $options The options for creating instances of the @@ -29,12 +26,12 @@ class TypeGuess extends Guess * @param int $confidence The confidence that the guessed class name * is correct */ - public function __construct(string $type, array $options, int $confidence) - { + public function __construct( + private string $type, + private array $options, + int $confidence, + ) { parent::__construct($confidence); - - $this->type = $type; - $this->options = $options; } /** diff --git a/Guess/ValueGuess.php b/Guess/ValueGuess.php index 36abe6602d..2283287472 100644 --- a/Guess/ValueGuess.php +++ b/Guess/ValueGuess.php @@ -18,16 +18,14 @@ */ class ValueGuess extends Guess { - private string|int|bool|null $value; - /** * @param int $confidence The confidence that the guessed class name is correct */ - public function __construct(string|int|bool|null $value, int $confidence) - { + public function __construct( + private string|int|bool|null $value, + int $confidence, + ) { parent::__construct($confidence); - - $this->value = $value; } /** diff --git a/PreloadedExtension.php b/PreloadedExtension.php index c8e628d2d2..58d8f13b1b 100644 --- a/PreloadedExtension.php +++ b/PreloadedExtension.php @@ -21,8 +21,6 @@ class PreloadedExtension implements FormExtensionInterface { private array $types = []; - private array $typeExtensions = []; - private ?FormTypeGuesserInterface $typeGuesser; /** * Creates a new preloaded extension. @@ -30,11 +28,11 @@ class PreloadedExtension implements FormExtensionInterface * @param FormTypeInterface[] $types The types that the extension should support * @param FormTypeExtensionInterface[][] $typeExtensions The type extensions that the extension should support */ - public function __construct(array $types, array $typeExtensions, FormTypeGuesserInterface $typeGuesser = null) - { - $this->typeExtensions = $typeExtensions; - $this->typeGuesser = $typeGuesser; - + public function __construct( + array $types, + private array $typeExtensions, + private ?FormTypeGuesserInterface $typeGuesser = null, + ) { foreach ($types as $type) { $this->types[$type::class] = $type; } diff --git a/ResolvedFormType.php b/ResolvedFormType.php index 1acdce8375..6c856db8b4 100644 --- a/ResolvedFormType.php +++ b/ResolvedFormType.php @@ -23,31 +23,28 @@ */ class ResolvedFormType implements ResolvedFormTypeInterface { - private FormTypeInterface $innerType; - /** * @var FormTypeExtensionInterface[] */ private array $typeExtensions; - private ?ResolvedFormTypeInterface $parent; - private OptionsResolver $optionsResolver; /** * @param FormTypeExtensionInterface[] $typeExtensions */ - public function __construct(FormTypeInterface $innerType, array $typeExtensions = [], ResolvedFormTypeInterface $parent = null) - { + public function __construct( + private FormTypeInterface $innerType, + array $typeExtensions = [], + private ?ResolvedFormTypeInterface $parent = null, + ) { foreach ($typeExtensions as $extension) { if (!$extension instanceof FormTypeExtensionInterface) { throw new UnexpectedTypeException($extension, FormTypeExtensionInterface::class); } } - $this->innerType = $innerType; $this->typeExtensions = $typeExtensions; - $this->parent = $parent; } public function getBlockPrefix(): string diff --git a/ReversedTransformer.php b/ReversedTransformer.php index b683879080..4aa92450a2 100644 --- a/ReversedTransformer.php +++ b/ReversedTransformer.php @@ -21,11 +21,9 @@ */ class ReversedTransformer implements DataTransformerInterface { - protected DataTransformerInterface $reversedTransformer; - - public function __construct(DataTransformerInterface $reversedTransformer) - { - $this->reversedTransformer = $reversedTransformer; + public function __construct( + protected DataTransformerInterface $reversedTransformer, + ) { } public function transform(mixed $value): mixed diff --git a/Util/OrderedHashMap.php b/Util/OrderedHashMap.php index 32d08caa8f..c0cab7aac6 100644 --- a/Util/OrderedHashMap.php +++ b/Util/OrderedHashMap.php @@ -71,13 +71,6 @@ */ class OrderedHashMap implements \ArrayAccess, \IteratorAggregate, \Countable { - /** - * The elements of the map, indexed by their keys. - * - * @var TValue[] - */ - private array $elements = []; - /** * The keys of the map in the order in which they were inserted or changed. * @@ -95,11 +88,11 @@ class OrderedHashMap implements \ArrayAccess, \IteratorAggregate, \Countable /** * Creates a new map. * - * @param TValue[] $elements The elements to insert initially + * @param TValue[] $elements The initial elements of the map, indexed by their keys. */ - public function __construct(array $elements = []) - { - $this->elements = $elements; + public function __construct( + private array $elements = [], + ) { // the explicit string type-cast is necessary as digit-only keys would be returned as integers otherwise $this->orderedKeys = array_map(strval(...), array_keys($elements)); } diff --git a/Util/OrderedHashMapIterator.php b/Util/OrderedHashMapIterator.php index 4a8eebe61d..927a28c04a 100644 --- a/Util/OrderedHashMapIterator.php +++ b/Util/OrderedHashMapIterator.php @@ -24,14 +24,8 @@ */ class OrderedHashMapIterator implements \Iterator { - /** @var TValue[] */ - private array $elements; - /** @var list */ - private array $orderedKeys; private int $cursor = 0; private int $cursorId; - /** @var array */ - private array $managedCursors; private ?string $key = null; /** @var TValue|null */ private mixed $current = null; @@ -47,11 +41,11 @@ class OrderedHashMapIterator implements \Iterator * {@link OrderedHashMap} instance to support * recognizing the deletion of elements. */ - public function __construct(array &$elements, array &$orderedKeys, array &$managedCursors) - { - $this->elements = &$elements; - $this->orderedKeys = &$orderedKeys; - $this->managedCursors = &$managedCursors; + public function __construct( + private array &$elements, + private array &$orderedKeys, + private array &$managedCursors, + ) { $this->cursorId = \count($managedCursors); $this->managedCursors[$this->cursorId] = &$this->cursor; diff --git a/Util/ServerParams.php b/Util/ServerParams.php index eb317ff36a..2c23efcc88 100644 --- a/Util/ServerParams.php +++ b/Util/ServerParams.php @@ -18,11 +18,9 @@ */ class ServerParams { - private ?RequestStack $requestStack; - - public function __construct(RequestStack $requestStack = null) - { - $this->requestStack = $requestStack; + public function __construct( + private ?RequestStack $requestStack = null, + ) { } /** From 425454873300b112d82e4eadea1910a202dc12dc Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 23 Jan 2024 15:42:10 +0100 Subject: [PATCH 156/208] Fix bad merge --- .../Core/DataMapper/PropertyPathMapper.php | 118 ------------------ 1 file changed, 118 deletions(-) delete mode 100644 Extension/Core/DataMapper/PropertyPathMapper.php diff --git a/Extension/Core/DataMapper/PropertyPathMapper.php b/Extension/Core/DataMapper/PropertyPathMapper.php deleted file mode 100644 index fe3fe1886b..0000000000 --- a/Extension/Core/DataMapper/PropertyPathMapper.php +++ /dev/null @@ -1,118 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Form\Extension\Core\DataMapper; - -use Symfony\Component\Form\DataMapperInterface; -use Symfony\Component\Form\Exception\UnexpectedTypeException; -use Symfony\Component\PropertyAccess\Exception\AccessException; -use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException; -use Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException; -use Symfony\Component\PropertyAccess\PropertyAccess; -use Symfony\Component\PropertyAccess\PropertyAccessorInterface; - -trigger_deprecation('symfony/form', '5.2', 'The "%s" class is deprecated. Use "%s" instead.', PropertyPathMapper::class, DataMapper::class); - -/** - * Maps arrays/objects to/from forms using property paths. - * - * @author Bernhard Schussek - * - * @deprecated since symfony/form 5.2. Use {@see DataMapper} instead. - */ -class PropertyPathMapper implements DataMapperInterface -{ - private $propertyAccessor; - - public function __construct(?PropertyAccessorInterface $propertyAccessor = null) - { - $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor(); - } - - /** - * {@inheritdoc} - */ - public function mapDataToForms($data, iterable $forms) - { - $empty = null === $data || [] === $data; - - if (!$empty && !\is_array($data) && !\is_object($data)) { - throw new UnexpectedTypeException($data, 'object, array or empty'); - } - - foreach ($forms as $form) { - $propertyPath = $form->getPropertyPath(); - $config = $form->getConfig(); - - if (!$empty && null !== $propertyPath && $config->getMapped()) { - $form->setData($this->getPropertyValue($data, $propertyPath)); - } else { - $form->setData($config->getData()); - } - } - } - - /** - * {@inheritdoc} - */ - public function mapFormsToData(iterable $forms, &$data) - { - if (null === $data) { - return; - } - - if (!\is_array($data) && !\is_object($data)) { - throw new UnexpectedTypeException($data, 'object, array or empty'); - } - - foreach ($forms as $form) { - $propertyPath = $form->getPropertyPath(); - $config = $form->getConfig(); - - // Write-back is disabled if the form is not synchronized (transformation failed), - // if the form was not submitted and if the form is disabled (modification not allowed) - if (null !== $propertyPath && $config->getMapped() && $form->isSubmitted() && $form->isSynchronized() && !$form->isDisabled()) { - $propertyValue = $form->getData(); - // If the field is of type DateTimeInterface and the data is the same skip the update to - // keep the original object hash - if ($propertyValue instanceof \DateTimeInterface && $propertyValue == $this->getPropertyValue($data, $propertyPath)) { - continue; - } - - // If the data is identical to the value in $data, we are - // dealing with a reference - if (!\is_object($data) || !$config->getByReference() || $propertyValue !== $this->getPropertyValue($data, $propertyPath)) { - $this->propertyAccessor->setValue($data, $propertyPath, $propertyValue); - } - } - } - } - - private function getPropertyValue($data, $propertyPath) - { - try { - return $this->propertyAccessor->getValue($data, $propertyPath); - } catch (AccessException $e) { - if (\is_array($data) && $e instanceof NoSuchIndexException) { - return null; - } - - if (!$e instanceof UninitializedPropertyException - // For versions without UninitializedPropertyException check the exception message - && (class_exists(UninitializedPropertyException::class) || !str_contains($e->getMessage(), 'You should initialize it')) - ) { - throw $e; - } - - return null; - } - } -} From 3d545bea7066520d1e7b275634f339bcbef1f15d Mon Sep 17 00:00:00 2001 From: Fan2Shrek Date: Wed, 14 Feb 2024 19:02:05 +0100 Subject: [PATCH 157/208] Throw error if the number is too high on moneyTransformer --- .../MoneyToLocalizedStringTransformer.php | 11 ++++++++++- .../MoneyToLocalizedStringTransformerTest.php | 9 +++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php index d9a75a2604..6ce24d3c63 100644 --- a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php @@ -69,7 +69,16 @@ public function reverseTransform(mixed $value): int|float|null $value = parent::reverseTransform($value); if (null !== $value && 1 !== $this->divisor) { $value = (string) ($value * $this->divisor); - $value = 'integer' === $this->modelType ? (int) $value : (float) $value; + + if ('float' === $this->modelType) { + return (float) $value; + } + + if ($value > \PHP_INT_MAX || $value < \PHP_INT_MIN) { + throw new TransformationFailedException(sprintf("The value '%d' is too large you should pass the 'model_type' to 'float'.", $value)); + } + + $value = (int) $value; } return $value; diff --git a/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php index 2d43e95332..e5733ad96a 100644 --- a/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.php @@ -118,4 +118,13 @@ public function testValidNumericValuesWithNonDotDecimalPointCharacter() $this->assertSame('0,0035', $transformer->transform(12 / 34)); } + + public function testHighIntNumberConversion() + { + $transformer = new MoneyToLocalizedStringTransformer(4, null, null, 100); + + $this->expectException(TransformationFailedException::class); + + $transformer->reverseTransform(111111111111111110.00); + } } From fd6e0a55e5f7526d4fe5a07a4dc3fbb42ec7cb78 Mon Sep 17 00:00:00 2001 From: patrickmaynard Date: Sun, 23 Apr 2023 13:58:03 +0200 Subject: [PATCH 158/208] 46867 - add more helpful property path accessor exceptions --- Extension/Core/DataAccessor/PropertyPathAccessor.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Extension/Core/DataAccessor/PropertyPathAccessor.php b/Extension/Core/DataAccessor/PropertyPathAccessor.php index 85efa150f4..6ea8b8ddef 100644 --- a/Extension/Core/DataAccessor/PropertyPathAccessor.php +++ b/Extension/Core/DataAccessor/PropertyPathAccessor.php @@ -16,6 +16,7 @@ use Symfony\Component\Form\FormInterface; use Symfony\Component\PropertyAccess\Exception\AccessException as PropertyAccessException; use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException; +use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; use Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; @@ -60,7 +61,11 @@ public function setValue(object|array &$data, mixed $value, FormInterface $form) // If the data is identical to the value in $data, we are // dealing with a reference if (!\is_object($data) || !$form->getConfig()->getByReference() || $value !== $this->getPropertyValue($data, $propertyPath)) { - $this->propertyAccessor->setValue($data, $propertyPath, $value); + try { + $this->propertyAccessor->setValue($data, $propertyPath, $value); + } catch (NoSuchPropertyException $e) { + throw new NoSuchPropertyException($e->getMessage().' Make the property public, add a setter, or set the "mapped" field option in the form type to be false.', 0, $e); + } } } From 7b4f01d319061c21f55b051577049660737a7fd0 Mon Sep 17 00:00:00 2001 From: Dariusz Ruminski Date: Mon, 18 Mar 2024 20:27:13 +0100 Subject: [PATCH 159/208] chore: CS fixes --- Button.php | 2 +- Extension/Core/Type/TimeType.php | 2 +- Extension/Csrf/EventListener/CsrfValidationListener.php | 3 +-- Extension/Validator/ViolationMapper/RelativePath.php | 3 +-- Form.php | 2 +- NativeRequestHandler.php | 2 +- Tests/Extension/Validator/ValidatorTypeGuesserTest.php | 2 +- Tests/FormFactoryTest.php | 8 ++++---- Util/OrderedHashMap.php | 2 +- 9 files changed, 12 insertions(+), 14 deletions(-) diff --git a/Button.php b/Button.php index f172a7ee31..c35f93d606 100644 --- a/Button.php +++ b/Button.php @@ -311,7 +311,7 @@ public function handleRequest(mixed $request = null): static * * @return $this * - * @throws Exception\AlreadySubmittedException if the button has already been submitted + * @throws AlreadySubmittedException if the button has already been submitted */ public function submit(array|string|null $submittedData, bool $clearMissing = true): static { diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index cf46b76acd..4e01489e73 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -12,13 +12,13 @@ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\Event\PreSubmitEvent; use Symfony\Component\Form\Exception\InvalidConfigurationException; use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeImmutableToDateTimeTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToArrayTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToTimestampTransformer; -use Symfony\Component\Form\Event\PreSubmitEvent; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; diff --git a/Extension/Csrf/EventListener/CsrfValidationListener.php b/Extension/Csrf/EventListener/CsrfValidationListener.php index 5aac521c84..44922402ff 100644 --- a/Extension/Csrf/EventListener/CsrfValidationListener.php +++ b/Extension/Csrf/EventListener/CsrfValidationListener.php @@ -42,8 +42,7 @@ public function __construct( private ?TranslatorInterface $translator = null, private ?string $translationDomain = null, ?ServerParams $serverParams = null, - ) - { + ) { $this->serverParams = $serverParams ?? new ServerParams(); } diff --git a/Extension/Validator/ViolationMapper/RelativePath.php b/Extension/Validator/ViolationMapper/RelativePath.php index dbf0712e2f..c139933743 100644 --- a/Extension/Validator/ViolationMapper/RelativePath.php +++ b/Extension/Validator/ViolationMapper/RelativePath.php @@ -22,8 +22,7 @@ class RelativePath extends PropertyPath public function __construct( private FormInterface $root, string $propertyPath, - ) - { + ) { parent::__construct($propertyPath); } diff --git a/Form.php b/Form.php index ee75311a14..44b97261bd 100644 --- a/Form.php +++ b/Form.php @@ -613,7 +613,7 @@ public function isSynchronized(): bool return null === $this->transformationFailure; } - public function getTransformationFailure(): ?Exception\TransformationFailedException + public function getTransformationFailure(): ?TransformationFailedException { return $this->transformationFailure; } diff --git a/NativeRequestHandler.php b/NativeRequestHandler.php index 4c03df13d5..bee54fa60d 100644 --- a/NativeRequestHandler.php +++ b/NativeRequestHandler.php @@ -42,7 +42,7 @@ public function __construct(?ServerParams $params = null) } /** - * @throws Exception\UnexpectedTypeException If the $request is not null + * @throws UnexpectedTypeException If the $request is not null */ public function handleRequest(FormInterface $form, mixed $request = null): void { diff --git a/Tests/Extension/Validator/ValidatorTypeGuesserTest.php b/Tests/Extension/Validator/ValidatorTypeGuesserTest.php index 0ac6b39148..c561cd76f2 100644 --- a/Tests/Extension/Validator/ValidatorTypeGuesserTest.php +++ b/Tests/Extension/Validator/ValidatorTypeGuesserTest.php @@ -50,7 +50,7 @@ class ValidatorTypeGuesserTest extends TestCase /** * @var MetadataFactoryInterface */ - private \Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory $metadataFactory; + private FakeMetadataFactory $metadataFactory; protected function setUp(): void { diff --git a/Tests/FormFactoryTest.php b/Tests/FormFactoryTest.php index bb18464c78..0cb3cad730 100644 --- a/Tests/FormFactoryTest.php +++ b/Tests/FormFactoryTest.php @@ -173,10 +173,10 @@ public function testCreateBuilderUsesPatternIfFound() class ConfigurableFormTypeGuesser implements FormTypeGuesserInterface { - private ?\Symfony\Component\Form\Guess\TypeGuess $typeGuess = null; - private ?\Symfony\Component\Form\Guess\ValueGuess $requiredGuess = null; - private ?\Symfony\Component\Form\Guess\ValueGuess $maxLengthGuess = null; - private ?\Symfony\Component\Form\Guess\ValueGuess $patternGuess = null; + private ?TypeGuess $typeGuess = null; + private ?ValueGuess $requiredGuess = null; + private ?ValueGuess $maxLengthGuess = null; + private ?ValueGuess $patternGuess = null; public function guessType($class, $property): ?TypeGuess { diff --git a/Util/OrderedHashMap.php b/Util/OrderedHashMap.php index c0cab7aac6..145bd2e25e 100644 --- a/Util/OrderedHashMap.php +++ b/Util/OrderedHashMap.php @@ -88,7 +88,7 @@ class OrderedHashMap implements \ArrayAccess, \IteratorAggregate, \Countable /** * Creates a new map. * - * @param TValue[] $elements The initial elements of the map, indexed by their keys. + * @param TValue[] $elements The initial elements of the map, indexed by their keys */ public function __construct( private array $elements = [], From 57bc474472f488f3c7fcf1b1448f793caadb4ed0 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Wed, 27 Mar 2024 22:24:38 +0100 Subject: [PATCH 160/208] stop marking parameters implicitly as nullable --- Tests/Fixtures/TranslatableTextAlign.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Fixtures/TranslatableTextAlign.php b/Tests/Fixtures/TranslatableTextAlign.php index 7a5d5cdff6..4464088c78 100644 --- a/Tests/Fixtures/TranslatableTextAlign.php +++ b/Tests/Fixtures/TranslatableTextAlign.php @@ -20,7 +20,7 @@ enum TranslatableTextAlign implements TranslatableInterface case Center; case Right; - public function trans(TranslatorInterface $translator, string $locale = null): string + public function trans(TranslatorInterface $translator, ?string $locale = null): string { return $translator->trans($this->name, locale: $locale); } From 2d1c888f00866164b7705107070db1c73fb41e37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Ostroluck=C3=BD?= Date: Sun, 31 Mar 2024 15:15:18 +0200 Subject: [PATCH 161/208] Remove unnecessary empty usages --- Extension/Core/DataTransformer/DateTimeToStringTransformer.php | 2 +- Extension/Validator/Type/BaseValidatorExtension.php | 2 +- Tests/Extension/Core/Type/CollectionTypeTest.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php index 96bdc7c0de..1353614208 100644 --- a/Extension/Core/DataTransformer/DateTimeToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToStringTransformer.php @@ -101,7 +101,7 @@ public function transform(mixed $dateTime): string */ public function reverseTransform(mixed $value): ?\DateTime { - if (empty($value)) { + if (!$value) { return null; } diff --git a/Extension/Validator/Type/BaseValidatorExtension.php b/Extension/Validator/Type/BaseValidatorExtension.php index 4b3fb49624..6b70df75fa 100644 --- a/Extension/Validator/Type/BaseValidatorExtension.php +++ b/Extension/Validator/Type/BaseValidatorExtension.php @@ -32,7 +32,7 @@ public function configureOptions(OptionsResolver $resolver): void return []; } - if (empty($groups)) { + if (!$groups) { return null; } diff --git a/Tests/Extension/Core/Type/CollectionTypeTest.php b/Tests/Extension/Core/Type/CollectionTypeTest.php index 08d512caf1..79134db993 100644 --- a/Tests/Extension/Core/Type/CollectionTypeTest.php +++ b/Tests/Extension/Core/Type/CollectionTypeTest.php @@ -120,7 +120,7 @@ public function testResizedDownWithDeleteEmptyCallable() $form = $this->factory->create(static::TESTED_TYPE, null, [ 'entry_type' => AuthorType::class, 'allow_delete' => true, - 'delete_empty' => fn (?Author $obj = null) => null === $obj || empty($obj->firstName), + 'delete_empty' => fn (?Author $obj = null) => null === $obj || !$obj->firstName, ]); $form->setData([new Author('Bob'), new Author('Alice')]); From 5a7886b3d342d58f1e54031cec9d421a7be02d51 Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Sun, 7 Apr 2024 23:52:35 +0200 Subject: [PATCH 162/208] Proofread UPGRADE guide --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e42aebae7..836823fa19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ CHANGELOG --- * Add option `separator` to `ChoiceType` to use a custom separator after preferred choices (use the new `separator_html` option to display the separator text as HTML) - * Deprecate not configuring the `default_protocol` option of the `UrlType`, it will default to `null` in 8.0 + * Deprecate not configuring the `default_protocol` option of the `UrlType`, it will default to `null` in 8.0 (the current default is `'http'`) * Add a `keep_as_list` option to `CollectionType` * Add a new `model_type` option to `MoneyType`, to be able to cast the transformed value to `integer` From a492b5cc53f90d0da5ca5ee0cd0c27072f8d4377 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Mon, 29 Apr 2024 15:41:47 +0200 Subject: [PATCH 163/208] rename the model_type option to input and rework it --- CHANGELOG.md | 2 +- .../MoneyToLocalizedStringTransformer.php | 8 ++++---- Extension/Core/Type/MoneyType.php | 14 +++----------- Tests/Extension/Core/Type/MoneyTypeTest.php | 14 +++++++------- 4 files changed, 15 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 836823fa19..0420af3413 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ CHANGELOG * Add option `separator` to `ChoiceType` to use a custom separator after preferred choices (use the new `separator_html` option to display the separator text as HTML) * Deprecate not configuring the `default_protocol` option of the `UrlType`, it will default to `null` in 8.0 (the current default is `'http'`) * Add a `keep_as_list` option to `CollectionType` - * Add a new `model_type` option to `MoneyType`, to be able to cast the transformed value to `integer` + * Add an `input` option to `MoneyType`, to be able to cast the transformed value to `integer` 7.0 --- diff --git a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php index 6ce24d3c63..caf6750e9f 100644 --- a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php @@ -29,7 +29,7 @@ public function __construct( ?int $roundingMode = \NumberFormatter::ROUND_HALFUP, ?int $divisor = 1, ?string $locale = null, - private string $modelType = 'float', + private readonly string $input = 'float', ) { parent::__construct($scale ?? 2, $grouping ?? true, $roundingMode, $locale); @@ -67,15 +67,15 @@ public function transform(mixed $value): string public function reverseTransform(mixed $value): int|float|null { $value = parent::reverseTransform($value); - if (null !== $value && 1 !== $this->divisor) { + if (null !== $value) { $value = (string) ($value * $this->divisor); - if ('float' === $this->modelType) { + if ('float' === $this->input) { return (float) $value; } if ($value > \PHP_INT_MAX || $value < \PHP_INT_MIN) { - throw new TransformationFailedException(sprintf("The value '%d' is too large you should pass the 'model_type' to 'float'.", $value)); + throw new TransformationFailedException(sprintf('Cannot cast "%s" to an integer. Try setting the input to "float" instead.', $value)); } $value = (int) $value; diff --git a/Extension/Core/Type/MoneyType.php b/Extension/Core/Type/MoneyType.php index e4d402d8d0..2657b03afb 100644 --- a/Extension/Core/Type/MoneyType.php +++ b/Extension/Core/Type/MoneyType.php @@ -35,7 +35,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $options['rounding_mode'], $options['divisor'], $options['html5'] ? 'en' : null, - $options['model_type'], + $options['input'], )) ; } @@ -60,7 +60,7 @@ public function configureOptions(OptionsResolver $resolver): void 'compound' => false, 'html5' => false, 'invalid_message' => 'Please enter a valid money amount.', - 'model_type' => 'float', + 'input' => 'float', ]); $resolver->setAllowedValues('rounding_mode', [ @@ -77,7 +77,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('html5', 'bool'); - $resolver->setAllowedValues('model_type', ['float', 'integer']); + $resolver->setAllowedValues('input', ['float', 'integer']); $resolver->setNormalizer('grouping', static function (Options $options, $value) { if ($value && $options['html5']) { @@ -86,14 +86,6 @@ public function configureOptions(OptionsResolver $resolver): void return $value; }); - - $resolver->setNormalizer('model_type', static function (Options $options, $value) { - if ('integer' === $value && 1 === $options['divisor']) { - throw new LogicException('When the "model_type" option is set to "integer", the "divisor" option should not be set to "1".'); - } - - return $value; - }); } public function getBlockPrefix(): string diff --git a/Tests/Extension/Core/Type/MoneyTypeTest.php b/Tests/Extension/Core/Type/MoneyTypeTest.php index 75d0729438..58e33af19b 100644 --- a/Tests/Extension/Core/Type/MoneyTypeTest.php +++ b/Tests/Extension/Core/Type/MoneyTypeTest.php @@ -11,7 +11,6 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; -use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Intl\Util\IntlTestHelper; class MoneyTypeTest extends BaseTypeTestCase @@ -125,7 +124,7 @@ public function testHtml5EnablesSpecificFormatting() $this->assertSame('number', $form->createView()->vars['type']); } - public function testDefaultModelType() + public function testDefaultInput() { $form = $this->factory->create(static::TESTED_TYPE, null, ['divisor' => 100]); $form->submit('12345.67'); @@ -133,18 +132,19 @@ public function testDefaultModelType() $this->assertSame(1234567.0, $form->getData()); } - public function testIntegerModelType() + public function testIntegerInput() { - $form = $this->factory->create(static::TESTED_TYPE, null, ['divisor' => 100, 'model_type' => 'integer']); + $form = $this->factory->create(static::TESTED_TYPE, null, ['divisor' => 100, 'input' => 'integer']); $form->submit('12345.67'); $this->assertSame(1234567, $form->getData()); } - public function testIntegerModelTypeExpectsDivisorNotEqualToOne() + public function testIntegerInputWithoutDivisor() { - $this->expectException(LogicException::class); + $form = $this->factory->create(static::TESTED_TYPE, null, ['input' => 'integer']); + $form->submit('1234567'); - $form = $this->factory->create(static::TESTED_TYPE, null, ['divisor' => 1, 'model_type' => 'integer']); + $this->assertSame(1234567, $form->getData()); } } From 50a9e64496b4d6cba7c7cc29be308593e34f6883 Mon Sep 17 00:00:00 2001 From: Antoine Lamirault Date: Mon, 20 May 2024 18:41:11 +0200 Subject: [PATCH 164/208] Fix singular phpdoc --- FormRegistryInterface.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FormRegistryInterface.php b/FormRegistryInterface.php index b1e77898e2..5c76b5c678 100644 --- a/FormRegistryInterface.php +++ b/FormRegistryInterface.php @@ -21,7 +21,7 @@ interface FormRegistryInterface /** * Returns a form type by name. * - * This methods registers the type extensions from the form extensions. + * This method registers the type extensions from the form extensions. * * @throws Exception\InvalidArgumentException if the type cannot be retrieved from any extension */ From 0981f0b0955a764393f77bd22ed961e0449a3aa6 Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Thu, 20 Jun 2024 17:52:34 +0200 Subject: [PATCH 165/208] Prefix all sprintf() calls --- AbstractExtension.php | 2 +- Command/DebugCommand.php | 10 +++++----- Console/Descriptor/Descriptor.php | 2 +- Console/Descriptor/TextDescriptor.php | 8 ++++---- DependencyInjection/FormPass.php | 2 +- Exception/UnexpectedTypeException.php | 2 +- .../DataTransformer/ArrayToPartsTransformer.php | 2 +- .../DataTransformer/BaseDateTimeTransformer.php | 4 ++-- .../DataTransformer/ChoiceToValueTransformer.php | 2 +- .../DateIntervalToArrayTransformer.php | 8 ++++---- .../DateIntervalToStringTransformer.php | 2 +- .../DataTransformer/DateTimeToArrayTransformer.php | 4 ++-- .../DateTimeToHtml5LocalDateTimeTransformer.php | 4 ++-- .../DateTimeToLocalizedStringTransformer.php | 4 ++-- .../DateTimeToRfc3339Transformer.php | 4 ++-- .../IntegerToLocalizedStringTransformer.php | 2 +- .../IntlTimeZoneToStringTransformer.php | 2 +- .../MoneyToLocalizedStringTransformer.php | 2 +- .../NumberToLocalizedStringTransformer.php | 2 +- .../PercentToLocalizedStringTransformer.php | 2 +- .../DataTransformer/UlidToStringTransformer.php | 2 +- .../DataTransformer/UuidToStringTransformer.php | 4 ++-- .../ValueToDuplicatesTransformer.php | 2 +- .../DataTransformer/WeekToArrayTransformer.php | 14 +++++++------- Extension/Core/Type/BaseType.php | 6 +++--- Extension/Core/Type/ChoiceType.php | 4 ++-- Extension/Core/Type/CountryType.php | 2 +- Extension/Core/Type/CurrencyType.php | 2 +- Extension/Core/Type/DateTimeType.php | 10 +++++----- Extension/Core/Type/DateType.php | 8 ++++---- Extension/Core/Type/LanguageType.php | 2 +- Extension/Core/Type/LocaleType.php | 2 +- Extension/Core/Type/TimeType.php | 8 ++++---- Extension/Core/Type/TimezoneType.php | 2 +- Extension/Core/Type/WeekType.php | 2 +- Extension/DataCollector/FormDataCollector.php | 2 +- .../DependencyInjectionExtension.php | 4 ++-- .../EventListener/PasswordHasherListener.php | 2 +- Extension/Validator/Constraints/FormValidator.php | 6 +++--- Extension/Validator/ValidatorTypeGuesser.php | 4 ++-- .../Validator/ViolationMapper/MappingRule.php | 2 +- .../Validator/ViolationMapper/ViolationPath.php | 8 ++++---- Form.php | 12 ++++++------ FormBuilder.php | 2 +- FormConfigBuilder.php | 4 ++-- FormErrorIterator.php | 4 ++-- FormRegistry.php | 6 +++--- FormRenderer.php | 8 ++++---- PreloadedExtension.php | 2 +- ResolvedFormType.php | 2 +- Test/FormPerformanceTestCase.php | 2 +- Test/Traits/ValidatorExtensionTrait.php | 2 +- .../Descriptor/AbstractDescriptorTestCase.php | 2 +- .../Core/Type/ChoiceTypeTranslationTest.php | 2 +- .../DependencyInjectionExtensionTest.php | 2 +- Tests/ResolvedFormTypeTest.php | 2 +- Tests/Resources/TranslationFilesTest.php | 4 ++-- Tests/VersionAwareTest.php | 2 +- Util/OrderedHashMap.php | 2 +- 59 files changed, 114 insertions(+), 114 deletions(-) diff --git a/AbstractExtension.php b/AbstractExtension.php index 908f4f86ff..27665727cf 100644 --- a/AbstractExtension.php +++ b/AbstractExtension.php @@ -50,7 +50,7 @@ public function getType(string $name): FormTypeInterface } if (!isset($this->types[$name])) { - throw new InvalidArgumentException(sprintf('The type "%s" cannot be loaded by this extension.', $name)); + throw new InvalidArgumentException(\sprintf('The type "%s" cannot be loaded by this extension.', $name)); } return $this->types[$name]; diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index 4d99012298..18d208cbe8 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -53,7 +53,7 @@ protected function configure(): void new InputArgument('class', InputArgument::OPTIONAL, 'The form type class'), new InputArgument('option', InputArgument::OPTIONAL, 'The form type option'), new InputOption('show-deprecated', null, InputOption::VALUE_NONE, 'Display deprecated options in form types'), - new InputOption('format', null, InputOption::VALUE_REQUIRED, sprintf('The output format ("%s")', implode('", "', $this->getAvailableFormatOptions())), 'txt'), + new InputOption('format', null, InputOption::VALUE_REQUIRED, \sprintf('The output format ("%s")', implode('", "', $this->getAvailableFormatOptions())), 'txt'), ]) ->setHelp(<<<'EOF' The %command.name% command displays information about form types. @@ -114,7 +114,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $object = $resolvedType->getOptionsResolver(); if (!$object->isDefined($option)) { - $message = sprintf('Option "%s" is not defined in "%s".', $option, $resolvedType->getInnerType()::class); + $message = \sprintf('Option "%s" is not defined in "%s".', $option, $resolvedType->getInnerType()::class); if ($alternatives = $this->findAlternatives($option, $object->getDefinedOptions())) { if (1 === \count($alternatives)) { @@ -148,7 +148,7 @@ private function getFqcnTypeClass(InputInterface $input, SymfonyStyle $io, strin $classes = $this->getFqcnTypeClasses($shortClassName); if (0 === $count = \count($classes)) { - $message = sprintf("Could not find type \"%s\" into the following namespaces:\n %s", $shortClassName, implode("\n ", $this->namespaces)); + $message = \sprintf("Could not find type \"%s\" into the following namespaces:\n %s", $shortClassName, implode("\n ", $this->namespaces)); $allTypes = array_merge($this->getCoreTypes(), $this->types); if ($alternatives = $this->findAlternatives($shortClassName, $allTypes)) { @@ -166,10 +166,10 @@ private function getFqcnTypeClass(InputInterface $input, SymfonyStyle $io, strin return $classes[0]; } if (!$input->isInteractive()) { - throw new InvalidArgumentException(sprintf("The type \"%s\" is ambiguous.\n\nDid you mean one of these?\n %s.", $shortClassName, implode("\n ", $classes))); + throw new InvalidArgumentException(\sprintf("The type \"%s\" is ambiguous.\n\nDid you mean one of these?\n %s.", $shortClassName, implode("\n ", $classes))); } - return $io->choice(sprintf("The type \"%s\" is ambiguous.\n\nSelect one of the following form types to display its information:", $shortClassName), $classes, $classes[0]); + return $io->choice(\sprintf("The type \"%s\" is ambiguous.\n\nSelect one of the following form types to display its information:", $shortClassName), $classes, $classes[0]); } private function getFqcnTypeClasses(string $shortClassName): array diff --git a/Console/Descriptor/Descriptor.php b/Console/Descriptor/Descriptor.php index f4835fb1ee..c910acdf4d 100644 --- a/Console/Descriptor/Descriptor.php +++ b/Console/Descriptor/Descriptor.php @@ -46,7 +46,7 @@ public function describe(OutputInterface $output, ?object $object, array $option null === $object => $this->describeDefaults($options), $object instanceof ResolvedFormTypeInterface => $this->describeResolvedFormType($object, $options), $object instanceof OptionsResolver => $this->describeOption($object, $options), - default => throw new \InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object))), + default => throw new \InvalidArgumentException(\sprintf('Object of type "%s" is not describable.', get_debug_type($object))), }; } diff --git a/Console/Descriptor/TextDescriptor.php b/Console/Descriptor/TextDescriptor.php index 7b723a0af6..630b872535 100644 --- a/Console/Descriptor/TextDescriptor.php +++ b/Console/Descriptor/TextDescriptor.php @@ -80,7 +80,7 @@ protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedF 'extension' => 'Extension options', ], $formOptions); - $this->output->title(sprintf('%s (Block prefix: "%s")', $resolvedFormType->getInnerType()::class, $resolvedFormType->getInnerType()->getBlockPrefix())); + $this->output->title(\sprintf('%s (Block prefix: "%s")', $resolvedFormType->getInnerType()::class, $resolvedFormType->getInnerType()->getBlockPrefix())); if ($formOptions) { $this->output->table($tableHeaders, $this->buildTableRows($tableHeaders, $formOptions)); @@ -131,7 +131,7 @@ protected function describeOption(OptionsResolver $optionsResolver, array $optio } array_pop($rows); - $this->output->title(sprintf('%s (%s)', $options['type']::class, $options['option'])); + $this->output->title(\sprintf('%s (%s)', $options['type']::class, $options['option'])); $this->output->table([], $rows); } @@ -172,7 +172,7 @@ private function normalizeAndSortOptionsColumns(array $options): array } else { $options[$group][] = null; } - $options[$group][] = sprintf('%s', (new \ReflectionClass($class))->getShortName()); + $options[$group][] = \sprintf('%s', (new \ReflectionClass($class))->getShortName()); $options[$group][] = new TableSeparator(); sort($opt); @@ -196,7 +196,7 @@ private function formatClassLink(string $class, ?string $text = null): string return $text; } - return sprintf('%s', $fileLink, $text); + return \sprintf('%s', $fileLink, $text); } private function getFileLink(string $class): string diff --git a/DependencyInjection/FormPass.php b/DependencyInjection/FormPass.php index 4087311631..1d2b2a87e5 100644 --- a/DependencyInjection/FormPass.php +++ b/DependencyInjection/FormPass.php @@ -89,7 +89,7 @@ private function processFormTypeExtensions(ContainerBuilder $container): array } if (!$extendsTypes) { - throw new InvalidArgumentException(sprintf('The getExtendedTypes() method for service "%s" does not return any extended types.', $serviceId)); + throw new InvalidArgumentException(\sprintf('The getExtendedTypes() method for service "%s" does not return any extended types.', $serviceId)); } } } diff --git a/Exception/UnexpectedTypeException.php b/Exception/UnexpectedTypeException.php index 7a4dc295c6..223061b77b 100644 --- a/Exception/UnexpectedTypeException.php +++ b/Exception/UnexpectedTypeException.php @@ -15,6 +15,6 @@ class UnexpectedTypeException extends InvalidArgumentException { public function __construct(mixed $value, string $expectedType) { - parent::__construct(sprintf('Expected argument of type "%s", "%s" given', $expectedType, get_debug_type($value))); + parent::__construct(\sprintf('Expected argument of type "%s", "%s" given', $expectedType, get_debug_type($value))); } } diff --git a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php index 828bd811e5..92f59c906e 100644 --- a/Extension/Core/DataTransformer/ArrayToPartsTransformer.php +++ b/Extension/Core/DataTransformer/ArrayToPartsTransformer.php @@ -72,7 +72,7 @@ public function reverseTransform(mixed $array): mixed return null; } - throw new TransformationFailedException(sprintf('The keys "%s" should not be empty.', implode('", "', $emptyKeys))); + throw new TransformationFailedException(\sprintf('The keys "%s" should not be empty.', implode('", "', $emptyKeys))); } return $result; diff --git a/Extension/Core/DataTransformer/BaseDateTimeTransformer.php b/Extension/Core/DataTransformer/BaseDateTimeTransformer.php index 8d311b3f8f..ca85fd44d0 100644 --- a/Extension/Core/DataTransformer/BaseDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/BaseDateTimeTransformer.php @@ -47,13 +47,13 @@ public function __construct(?string $inputTimezone = null, ?string $outputTimezo try { new \DateTimeZone($this->inputTimezone); } catch (\Exception $e) { - throw new InvalidArgumentException(sprintf('Input timezone is invalid: "%s".', $this->inputTimezone), $e->getCode(), $e); + throw new InvalidArgumentException(\sprintf('Input timezone is invalid: "%s".', $this->inputTimezone), $e->getCode(), $e); } try { new \DateTimeZone($this->outputTimezone); } catch (\Exception $e) { - throw new InvalidArgumentException(sprintf('Output timezone is invalid: "%s".', $this->outputTimezone), $e->getCode(), $e); + throw new InvalidArgumentException(\sprintf('Output timezone is invalid: "%s".', $this->outputTimezone), $e->getCode(), $e); } } } diff --git a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php index 52ee25e93e..e75bc31dee 100644 --- a/Extension/Core/DataTransformer/ChoiceToValueTransformer.php +++ b/Extension/Core/DataTransformer/ChoiceToValueTransformer.php @@ -45,7 +45,7 @@ public function reverseTransform(mixed $value): mixed return null; } - throw new TransformationFailedException(sprintf('The choice "%s" does not exist or is not unique.', $value)); + throw new TransformationFailedException(\sprintf('The choice "%s" does not exist or is not unique.', $value)); } return current($choices); diff --git a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php index 08c0585979..0475b55bfd 100644 --- a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php @@ -124,19 +124,19 @@ public function reverseTransform(mixed $value): ?\DateInterval } } if (\count($emptyFields) > 0) { - throw new TransformationFailedException(sprintf('The fields "%s" should not be empty.', implode('", "', $emptyFields))); + throw new TransformationFailedException(\sprintf('The fields "%s" should not be empty.', implode('", "', $emptyFields))); } if (isset($value['invert']) && !\is_bool($value['invert'])) { throw new TransformationFailedException('The value of "invert" must be boolean.'); } foreach (self::AVAILABLE_FIELDS as $field => $char) { if ('invert' !== $field && isset($value[$field]) && !ctype_digit((string) $value[$field])) { - throw new TransformationFailedException(sprintf('This amount of "%s" is invalid.', $field)); + throw new TransformationFailedException(\sprintf('This amount of "%s" is invalid.', $field)); } } try { if (!empty($value['weeks'])) { - $interval = sprintf( + $interval = \sprintf( 'P%sY%sM%sWT%sH%sM%sS', empty($value['years']) ? '0' : $value['years'], empty($value['months']) ? '0' : $value['months'], @@ -146,7 +146,7 @@ public function reverseTransform(mixed $value): ?\DateInterval empty($value['seconds']) ? '0' : $value['seconds'] ); } else { - $interval = sprintf( + $interval = \sprintf( 'P%sY%sM%sDT%sH%sM%sS', empty($value['years']) ? '0' : $value['years'], empty($value['months']) ? '0' : $value['months'], diff --git a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php index e1a3d97246..527836bf55 100644 --- a/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToStringTransformer.php @@ -79,7 +79,7 @@ public function reverseTransform(mixed $value): ?\DateInterval } $valuePattern = '/^'.preg_replace('/%([yYmMdDhHiIsSwW])(\w)/', '(?P<$1>\d+)$2', $this->format).'$/'; if (!preg_match($valuePattern, $value)) { - throw new TransformationFailedException(sprintf('Value "%s" contains intervals not accepted by format "%s".', $value, $this->format)); + throw new TransformationFailedException(\sprintf('Value "%s" contains intervals not accepted by format "%s".', $value, $this->format)); } try { $dateInterval = new \DateInterval($value); diff --git a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php index 8c3d2d2266..06d24cf8e0 100644 --- a/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToArrayTransformer.php @@ -126,7 +126,7 @@ public function reverseTransform(mixed $value): ?\DateTime } if (\count($emptyFields) > 0) { - throw new TransformationFailedException(sprintf('The fields "%s" should not be empty.', implode('", "', $emptyFields))); + throw new TransformationFailedException(\sprintf('The fields "%s" should not be empty.', implode('", "', $emptyFields))); } if (isset($value['month']) && !ctype_digit((string) $value['month'])) { @@ -158,7 +158,7 @@ public function reverseTransform(mixed $value): ?\DateTime } try { - $dateTime = new \DateTime(sprintf( + $dateTime = new \DateTime(\sprintf( '%s-%s-%s %s:%s:%s', empty($value['year']) ? $this->referenceDate->format('Y') : $value['year'], empty($value['month']) ? $this->referenceDate->format('m') : $value['month'], diff --git a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php index 855b22a499..dbeed8e490 100644 --- a/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToHtml5LocalDateTimeTransformer.php @@ -85,7 +85,7 @@ public function reverseTransform(mixed $dateTimeLocal): ?\DateTime // to maintain backwards compatibility we do not strictly validate the submitted date // see https://github.com/symfony/symfony/issues/28699 if (!preg_match('/^(\d{4})-(\d{2})-(\d{2})[T ]\d{2}:\d{2}(?::\d{2})?/', $dateTimeLocal, $matches)) { - throw new TransformationFailedException(sprintf('The date "%s" is not a valid date.', $dateTimeLocal)); + throw new TransformationFailedException(\sprintf('The date "%s" is not a valid date.', $dateTimeLocal)); } try { @@ -99,7 +99,7 @@ public function reverseTransform(mixed $dateTimeLocal): ?\DateTime } if (!checkdate($matches[2], $matches[3], $matches[1])) { - throw new TransformationFailedException(sprintf('The date "%s-%s-%s" is not a valid date.', $matches[1], $matches[2], $matches[3])); + throw new TransformationFailedException(\sprintf('The date "%s-%s-%s" is not a valid date.', $matches[1], $matches[2], $matches[3])); } return $dateTime; diff --git a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php index b7ea092591..a93803cd8b 100644 --- a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php @@ -128,7 +128,7 @@ public function reverseTransform(mixed $value): ?\DateTime } elseif (false === $timestamp) { // the value couldn't be parsed but the Intl extension didn't report an error code, this // could be the case when the Intl polyfill is used which always returns 0 as the error code - throw new TransformationFailedException(sprintf('"%s" could not be parsed as a date.', $value)); + throw new TransformationFailedException(\sprintf('"%s" could not be parsed as a date.', $value)); } try { @@ -137,7 +137,7 @@ public function reverseTransform(mixed $value): ?\DateTime $dateTime = new \DateTime(gmdate('Y-m-d', $timestamp), new \DateTimeZone($this->outputTimezone)); } else { // read timestamp into DateTime object - the formatter delivers a timestamp - $dateTime = new \DateTime(sprintf('@%s', $timestamp)); + $dateTime = new \DateTime(\sprintf('@%s', $timestamp)); } // set timezone separately, as it would be ignored if set via the constructor, // see https://php.net/datetime.construct diff --git a/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php b/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php index 41e63e57ca..d32b3eae2b 100644 --- a/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php +++ b/Extension/Core/DataTransformer/DateTimeToRfc3339Transformer.php @@ -64,7 +64,7 @@ public function reverseTransform(mixed $rfc3339): ?\DateTime } if (!preg_match('/^(\d{4})-(\d{2})-(\d{2})T\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|(?:(?:\+|-)\d{2}:\d{2}))$/', $rfc3339, $matches)) { - throw new TransformationFailedException(sprintf('The date "%s" is not a valid date.', $rfc3339)); + throw new TransformationFailedException(\sprintf('The date "%s" is not a valid date.', $rfc3339)); } try { @@ -78,7 +78,7 @@ public function reverseTransform(mixed $rfc3339): ?\DateTime } if (!checkdate($matches[2], $matches[3], $matches[1])) { - throw new TransformationFailedException(sprintf('The date "%s-%s-%s" is not a valid date.', $matches[1], $matches[2], $matches[3])); + throw new TransformationFailedException(\sprintf('The date "%s-%s-%s" is not a valid date.', $matches[1], $matches[2], $matches[3])); } return $dateTime; diff --git a/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php index eb5a2d6ff1..d83e31b42d 100644 --- a/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformer.php @@ -38,7 +38,7 @@ public function reverseTransform(mixed $value): int|float|null $decimalSeparator = $this->getNumberFormatter()->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL); if (\is_string($value) && str_contains($value, $decimalSeparator)) { - throw new TransformationFailedException(sprintf('The value "%s" is not a valid integer.', $value)); + throw new TransformationFailedException(\sprintf('The value "%s" is not a valid integer.', $value)); } $result = parent::reverseTransform($value); diff --git a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php index 446a95f708..19626e49ca 100644 --- a/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php +++ b/Extension/Core/DataTransformer/IntlTimeZoneToStringTransformer.php @@ -70,7 +70,7 @@ public function reverseTransform(mixed $value): mixed $intlTimeZone = \IntlTimeZone::createTimeZone($value); if ('Etc/Unknown' === $intlTimeZone->getID()) { - throw new TransformationFailedException(sprintf('Unknown timezone identifier "%s".', $value)); + throw new TransformationFailedException(\sprintf('Unknown timezone identifier "%s".', $value)); } return $intlTimeZone; diff --git a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php index caf6750e9f..b03f8da444 100644 --- a/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformer.php @@ -75,7 +75,7 @@ public function reverseTransform(mixed $value): int|float|null } if ($value > \PHP_INT_MAX || $value < \PHP_INT_MIN) { - throw new TransformationFailedException(sprintf('Cannot cast "%s" to an integer. Try setting the input to "float" instead.', $value)); + throw new TransformationFailedException(\sprintf('Cannot cast "%s" to an integer. Try setting the input to "float" instead.', $value)); } $value = (int) $value; diff --git a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index 6e1c495aee..2a6d146f90 100644 --- a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -140,7 +140,7 @@ public function reverseTransform(mixed $value): int|float|null $remainder = trim($remainder, " \t\n\r\0\x0b\xc2\xa0"); if ('' !== $remainder) { - throw new TransformationFailedException(sprintf('The number contains unrecognized characters: "%s".', $remainder)); + throw new TransformationFailedException(\sprintf('The number contains unrecognized characters: "%s".', $remainder)); } } diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index d4d8aad9d4..8ae5e4c968 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -158,7 +158,7 @@ public function reverseTransform(mixed $value): int|float|null $remainder = trim($remainder, " \t\n\r\0\x0b\xc2\xa0"); if ('' !== $remainder) { - throw new TransformationFailedException(sprintf('The number contains unrecognized characters: "%s".', $remainder)); + throw new TransformationFailedException(\sprintf('The number contains unrecognized characters: "%s".', $remainder)); } } diff --git a/Extension/Core/DataTransformer/UlidToStringTransformer.php b/Extension/Core/DataTransformer/UlidToStringTransformer.php index 7ace73ad09..9365cab15e 100644 --- a/Extension/Core/DataTransformer/UlidToStringTransformer.php +++ b/Extension/Core/DataTransformer/UlidToStringTransformer.php @@ -65,7 +65,7 @@ public function reverseTransform(mixed $value): ?Ulid try { $ulid = new Ulid($value); } catch (\InvalidArgumentException $e) { - throw new TransformationFailedException(sprintf('The value "%s" is not a valid ULID.', $value), $e->getCode(), $e); + throw new TransformationFailedException(\sprintf('The value "%s" is not a valid ULID.', $value), $e->getCode(), $e); } return $ulid; diff --git a/Extension/Core/DataTransformer/UuidToStringTransformer.php b/Extension/Core/DataTransformer/UuidToStringTransformer.php index cc794a0247..43326eb644 100644 --- a/Extension/Core/DataTransformer/UuidToStringTransformer.php +++ b/Extension/Core/DataTransformer/UuidToStringTransformer.php @@ -63,13 +63,13 @@ public function reverseTransform(mixed $value): ?Uuid } if (!Uuid::isValid($value)) { - throw new TransformationFailedException(sprintf('The value "%s" is not a valid UUID.', $value)); + throw new TransformationFailedException(\sprintf('The value "%s" is not a valid UUID.', $value)); } try { return Uuid::fromString($value); } catch (\InvalidArgumentException $e) { - throw new TransformationFailedException(sprintf('The value "%s" is not a valid UUID.', $value), $e->getCode(), $e); + throw new TransformationFailedException(\sprintf('The value "%s" is not a valid UUID.', $value), $e->getCode(), $e); } } } diff --git a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php index 9700b0424e..43ed176491 100644 --- a/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php +++ b/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php @@ -71,7 +71,7 @@ public function reverseTransform(mixed $array): mixed return null; } - throw new TransformationFailedException(sprintf('The keys "%s" should not be empty.', implode('", "', $emptyKeys))); + throw new TransformationFailedException(\sprintf('The keys "%s" should not be empty.', implode('", "', $emptyKeys))); } return $result; diff --git a/Extension/Core/DataTransformer/WeekToArrayTransformer.php b/Extension/Core/DataTransformer/WeekToArrayTransformer.php index c10bc735f6..448ae4278b 100644 --- a/Extension/Core/DataTransformer/WeekToArrayTransformer.php +++ b/Extension/Core/DataTransformer/WeekToArrayTransformer.php @@ -40,7 +40,7 @@ public function transform(mixed $value): array } if (!\is_string($value)) { - throw new TransformationFailedException(sprintf('Value is expected to be a string but was "%s".', get_debug_type($value))); + throw new TransformationFailedException(\sprintf('Value is expected to be a string but was "%s".', get_debug_type($value))); } if (0 === preg_match('/^(?P\d{4})-W(?P\d{2})$/', $value, $matches)) { @@ -70,7 +70,7 @@ public function reverseTransform(mixed $value): ?string } if (!\is_array($value)) { - throw new TransformationFailedException(sprintf('Value is expected to be an array, but was "%s".', get_debug_type($value))); + throw new TransformationFailedException(\sprintf('Value is expected to be an array, but was "%s".', get_debug_type($value))); } if (!\array_key_exists('year', $value)) { @@ -82,7 +82,7 @@ public function reverseTransform(mixed $value): ?string } if ($additionalKeys = array_diff(array_keys($value), ['year', 'week'])) { - throw new TransformationFailedException(sprintf('Expected only keys "year" and "week" to be present, but also got ["%s"].', implode('", "', $additionalKeys))); + throw new TransformationFailedException(\sprintf('Expected only keys "year" and "week" to be present, but also got ["%s"].', implode('", "', $additionalKeys))); } if (null === $value['year'] && null === $value['week']) { @@ -90,18 +90,18 @@ public function reverseTransform(mixed $value): ?string } if (!\is_int($value['year'])) { - throw new TransformationFailedException(sprintf('Year is expected to be an integer, but was "%s".', get_debug_type($value['year']))); + throw new TransformationFailedException(\sprintf('Year is expected to be an integer, but was "%s".', get_debug_type($value['year']))); } if (!\is_int($value['week'])) { - throw new TransformationFailedException(sprintf('Week is expected to be an integer, but was "%s".', get_debug_type($value['week']))); + throw new TransformationFailedException(\sprintf('Week is expected to be an integer, but was "%s".', get_debug_type($value['week']))); } // The 28th December is always in the last week of the year if (date('W', strtotime('28th December '.$value['year'])) < $value['week']) { - throw new TransformationFailedException(sprintf('Week "%d" does not exist for year "%d".', $value['week'], $value['year'])); + throw new TransformationFailedException(\sprintf('Week "%d" does not exist for year "%d".', $value['week'], $value['year'])); } - return sprintf('%d-W%02d', $value['year'], $value['week']); + return \sprintf('%d-W%02d', $value['year'], $value['week']); } } diff --git a/Extension/Core/Type/BaseType.php b/Extension/Core/Type/BaseType.php index 68190c742f..a7f745d78a 100644 --- a/Extension/Core/Type/BaseType.php +++ b/Extension/Core/Type/BaseType.php @@ -46,9 +46,9 @@ public function buildView(FormView $view, FormInterface $form, array $options): if ($view->parent) { if ('' !== ($parentFullName = $view->parent->vars['full_name'])) { - $id = sprintf('%s_%s', $view->parent->vars['id'], $name); - $fullName = sprintf('%s[%s]', $parentFullName, $name); - $uniqueBlockPrefix = sprintf('%s_%s', $view->parent->vars['unique_block_prefix'], $blockName); + $id = \sprintf('%s_%s', $view->parent->vars['id'], $name); + $fullName = \sprintf('%s[%s]', $parentFullName, $name); + $uniqueBlockPrefix = \sprintf('%s_%s', $view->parent->vars['unique_block_prefix'], $blockName); } else { $id = $name; $fullName = $name; diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 2e9cb7087f..36ebe6c840 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -158,7 +158,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void // Throw exception if unknown values were submitted (multiple choices will be handled in a different event listener below) if (\count($unknownValues) > 0 && !$options['multiple']) { - throw new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.', implode('", "', array_keys($unknownValues)))); + throw new TransformationFailedException(\sprintf('The choices "%s" do not exist in the choice list.', implode('", "', array_keys($unknownValues)))); } $event->setData($knownValues); @@ -182,7 +182,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $message = strtr($messageTemplate, ['{{ value }}' => $clientDataAsString]); } - $form->addError(new FormError($message, $messageTemplate, ['{{ value }}' => $clientDataAsString], null, new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.', $clientDataAsString)))); + $form->addError(new FormError($message, $messageTemplate, ['{{ value }}' => $clientDataAsString], null, new TransformationFailedException(\sprintf('The choices "%s" do not exist in the choice list.', $clientDataAsString)))); } }); diff --git a/Extension/Core/Type/CountryType.php b/Extension/Core/Type/CountryType.php index adef745c54..503bc8327e 100644 --- a/Extension/Core/Type/CountryType.php +++ b/Extension/Core/Type/CountryType.php @@ -27,7 +27,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setDefaults([ 'choice_loader' => function (Options $options) { if (!class_exists(Intl::class)) { - throw new LogicException(sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class)); + throw new LogicException(\sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class)); } $choiceTranslationLocale = $options['choice_translation_locale']; diff --git a/Extension/Core/Type/CurrencyType.php b/Extension/Core/Type/CurrencyType.php index 3581a77d9b..abfa39729b 100644 --- a/Extension/Core/Type/CurrencyType.php +++ b/Extension/Core/Type/CurrencyType.php @@ -27,7 +27,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setDefaults([ 'choice_loader' => function (Options $options) { if (!class_exists(Intl::class)) { - throw new LogicException(sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class)); + throw new LogicException(\sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class)); } $choiceTranslationLocale = $options['choice_translation_locale']; diff --git a/Extension/Core/Type/DateTimeType.php b/Extension/Core/Type/DateTimeType.php index 1c67eeb159..cf4c2b7416 100644 --- a/Extension/Core/Type/DateTimeType.php +++ b/Extension/Core/Type/DateTimeType.php @@ -203,7 +203,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void } if ($date->getTimezone()->getName() !== $options['model_timezone']) { - throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', get_debug_type($date), $date->getTimezone()->getName(), $options['model_timezone'])); + throw new LogicException(\sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', get_debug_type($date), $date->getTimezone()->getName(), $options['model_timezone'])); } }); } @@ -311,7 +311,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setNormalizer('date_format', static function (Options $options, $dateFormat) { if (null !== $dateFormat && 'single_text' === $options['widget'] && self::HTML5_FORMAT === $options['format']) { - throw new LogicException(sprintf('Cannot use the "date_format" option of the "%s" with an HTML5 date.', self::class)); + throw new LogicException(\sprintf('Cannot use the "date_format" option of the "%s" with an HTML5 date.', self::class)); } return $dateFormat; @@ -319,10 +319,10 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setNormalizer('widget', static function (Options $options, $widget) { if ('single_text' === $widget) { if (null !== $options['date_widget']) { - throw new LogicException(sprintf('Cannot use the "date_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class)); + throw new LogicException(\sprintf('Cannot use the "date_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class)); } if (null !== $options['time_widget']) { - throw new LogicException(sprintf('Cannot use the "time_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class)); + throw new LogicException(\sprintf('Cannot use the "time_widget" option of the "%s" when the "widget" option is set to "single_text".', self::class)); } } elseif (null === $widget && null === $options['date_widget'] && null === $options['time_widget']) { return 'single_text'; @@ -332,7 +332,7 @@ public function configureOptions(OptionsResolver $resolver): void }); $resolver->setNormalizer('html5', static function (Options $options, $html5) { if ($html5 && self::HTML5_FORMAT !== $options['format']) { - throw new LogicException(sprintf('Cannot use the "format" option of "%s" when the "html5" option is enabled.', self::class)); + throw new LogicException(\sprintf('Cannot use the "format" option of "%s" when the "html5" option is enabled.', self::class)); } return $html5; diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index cfbbaf4c0d..773a51cbdd 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -58,7 +58,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void if ('single_text' === $options['widget']) { if ('' !== $pattern && !str_contains($pattern, 'y') && !str_contains($pattern, 'M') && !str_contains($pattern, 'd')) { - throw new InvalidOptionsException(sprintf('The "format" option should contain the letters "y", "M" or "d". Its current value is "%s".', $pattern)); + throw new InvalidOptionsException(\sprintf('The "format" option should contain the letters "y", "M" or "d". Its current value is "%s".', $pattern)); } $builder->addViewTransformer(new DateTimeToLocalizedStringTransformer( @@ -71,7 +71,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void )); } else { if ('' !== $pattern && (!str_contains($pattern, 'y') || !str_contains($pattern, 'M') || !str_contains($pattern, 'd'))) { - throw new InvalidOptionsException(sprintf('The "format" option should contain the letters "y", "M" and "d". Its current value is "%s".', $pattern)); + throw new InvalidOptionsException(\sprintf('The "format" option should contain the letters "y", "M" and "d". Its current value is "%s".', $pattern)); } $yearOptions = $monthOptions = $dayOptions = [ @@ -187,7 +187,7 @@ class_exists(\IntlTimeZone::class, false) ? \IntlTimeZone::createDefault() : nul } if ($date->getTimezone()->getName() !== $options['model_timezone']) { - throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', get_debug_type($date), $date->getTimezone()->getName(), $options['model_timezone'])); + throw new LogicException(\sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', get_debug_type($date), $date->getTimezone()->getName(), $options['model_timezone'])); } }); } @@ -323,7 +323,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setNormalizer('html5', static function (Options $options, $html5) { if ($html5 && 'single_text' === $options['widget'] && self::HTML5_FORMAT !== $options['format']) { - throw new LogicException(sprintf('Cannot use the "format" option of "%s" when the "html5" option is enabled.', self::class)); + throw new LogicException(\sprintf('Cannot use the "format" option of "%s" when the "html5" option is enabled.', self::class)); } return $html5; diff --git a/Extension/Core/Type/LanguageType.php b/Extension/Core/Type/LanguageType.php index e81571f8c4..638976a8cf 100644 --- a/Extension/Core/Type/LanguageType.php +++ b/Extension/Core/Type/LanguageType.php @@ -28,7 +28,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setDefaults([ 'choice_loader' => function (Options $options) { if (!class_exists(Intl::class)) { - throw new LogicException(sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class)); + throw new LogicException(\sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class)); } $choiceTranslationLocale = $options['choice_translation_locale']; $useAlpha3Codes = $options['alpha3']; diff --git a/Extension/Core/Type/LocaleType.php b/Extension/Core/Type/LocaleType.php index d0124e6000..1529ca83f9 100644 --- a/Extension/Core/Type/LocaleType.php +++ b/Extension/Core/Type/LocaleType.php @@ -27,7 +27,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setDefaults([ 'choice_loader' => function (Options $options) { if (!class_exists(Intl::class)) { - throw new LogicException(sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class)); + throw new LogicException(\sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class)); } $choiceTranslationLocale = $options['choice_translation_locale']; diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 4e01489e73..ad559760d1 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -45,7 +45,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void } if (null !== $options['reference_date'] && $options['reference_date']->getTimezone()->getName() !== $options['model_timezone']) { - throw new InvalidConfigurationException(sprintf('The configured "model_timezone" (%s) must match the timezone of the "reference_date" (%s).', $options['model_timezone'], $options['reference_date']->getTimezone()->getName())); + throw new InvalidConfigurationException(\sprintf('The configured "model_timezone" (%s) must match the timezone of the "reference_date" (%s).', $options['model_timezone'], $options['reference_date']->getTimezone()->getName())); } if ($options['with_minutes']) { @@ -66,9 +66,9 @@ public function buildForm(FormBuilderInterface $builder, array $options): void if ($options['with_seconds']) { // handle seconds ignored by user's browser when with_seconds enabled // https://codereview.chromium.org/450533009/ - $e->setData(sprintf('%s:%s:%s', $matches['hours'], $matches['minutes'], $matches['seconds'] ?? '00')); + $e->setData(\sprintf('%s:%s:%s', $matches['hours'], $matches['minutes'], $matches['seconds'] ?? '00')); } else { - $e->setData(sprintf('%s:%s', $matches['hours'], $matches['minutes'])); + $e->setData(\sprintf('%s:%s', $matches['hours'], $matches['minutes'])); } } }); @@ -217,7 +217,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void } if ($date->getTimezone()->getName() !== $options['model_timezone']) { - throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', get_debug_type($date), $date->getTimezone()->getName(), $options['model_timezone'])); + throw new LogicException(\sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', get_debug_type($date), $date->getTimezone()->getName(), $options['model_timezone'])); } }); } diff --git a/Extension/Core/Type/TimezoneType.php b/Extension/Core/Type/TimezoneType.php index 01ce68ce37..2316d666b5 100644 --- a/Extension/Core/Type/TimezoneType.php +++ b/Extension/Core/Type/TimezoneType.php @@ -43,7 +43,7 @@ public function configureOptions(OptionsResolver $resolver): void if ($options['intl']) { if (!class_exists(Intl::class)) { - throw new LogicException(sprintf('The "symfony/intl" component is required to use "%s" with option "intl=true". Try running "composer require symfony/intl".', static::class)); + throw new LogicException(\sprintf('The "symfony/intl" component is required to use "%s" with option "intl=true". Try running "composer require symfony/intl".', static::class)); } $choiceTranslationLocale = $options['choice_translation_locale']; diff --git a/Extension/Core/Type/WeekType.php b/Extension/Core/Type/WeekType.php index c3ffae0617..ec5cc93037 100644 --- a/Extension/Core/Type/WeekType.php +++ b/Extension/Core/Type/WeekType.php @@ -145,7 +145,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setNormalizer('choice_translation_domain', $choiceTranslationDomainNormalizer); $resolver->setNormalizer('html5', static function (Options $options, $html5) { if ($html5 && 'single_text' !== $options['widget']) { - throw new LogicException(sprintf('The "widget" option of "%s" must be set to "single_text" when the "html5" option is enabled.', self::class)); + throw new LogicException(\sprintf('The "widget" option of "%s" must be set to "single_text" when the "html5" option is enabled.', self::class)); } return $html5; diff --git a/Extension/DataCollector/FormDataCollector.php b/Extension/DataCollector/FormDataCollector.php index 348be44aaa..e6cae863e8 100644 --- a/Extension/DataCollector/FormDataCollector.php +++ b/Extension/DataCollector/FormDataCollector.php @@ -64,7 +64,7 @@ public function __construct( private FormDataExtractorInterface $dataExtractor, ) { if (!class_exists(ClassStub::class)) { - throw new \LogicException(sprintf('The VarDumper component is needed for using the "%s" class. Install symfony/var-dumper version 3.4 or above.', __CLASS__)); + throw new \LogicException(\sprintf('The VarDumper component is needed for using the "%s" class. Install symfony/var-dumper version 3.4 or above.', __CLASS__)); } $this->reset(); diff --git a/Extension/DependencyInjection/DependencyInjectionExtension.php b/Extension/DependencyInjection/DependencyInjectionExtension.php index 420f26b743..f986bda415 100644 --- a/Extension/DependencyInjection/DependencyInjectionExtension.php +++ b/Extension/DependencyInjection/DependencyInjectionExtension.php @@ -37,7 +37,7 @@ public function __construct( public function getType(string $name): FormTypeInterface { if (!$this->typeContainer->has($name)) { - throw new InvalidArgumentException(sprintf('The field type "%s" is not registered in the service container.', $name)); + throw new InvalidArgumentException(\sprintf('The field type "%s" is not registered in the service container.', $name)); } return $this->typeContainer->get($name); @@ -63,7 +63,7 @@ public function getTypeExtensions(string $name): array // validate the result of getExtendedTypes() to ensure it is consistent with the service definition if (!\in_array($name, $extendedTypes, true)) { - throw new InvalidArgumentException(sprintf('The extended type "%s" specified for the type extension class "%s" does not match any of the actual extended types (["%s"]).', $name, $extension::class, implode('", "', $extendedTypes))); + throw new InvalidArgumentException(\sprintf('The extended type "%s" specified for the type extension class "%s" does not match any of the actual extended types (["%s"]).', $name, $extension::class, implode('", "', $extendedTypes))); } } } diff --git a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php index 3ddac5ff35..0144cc3ffa 100644 --- a/Extension/PasswordHasher/EventListener/PasswordHasherListener.php +++ b/Extension/PasswordHasher/EventListener/PasswordHasherListener.php @@ -95,7 +95,7 @@ private function getUser(FormInterface $form): PasswordAuthenticatedUserInterfac $parent = $this->getTargetForm($form)->getParent(); if (!($user = $parent?->getData()) || !$user instanceof PasswordAuthenticatedUserInterface) { - throw new InvalidConfigurationException(sprintf('The "hash_property_path" option only supports "%s" objects, "%s" given.', PasswordAuthenticatedUserInterface::class, get_debug_type($user))); + throw new InvalidConfigurationException(\sprintf('The "hash_property_path" option only supports "%s" objects, "%s" given.', PasswordAuthenticatedUserInterface::class, get_debug_type($user))); } return $user; diff --git a/Extension/Validator/Constraints/FormValidator.php b/Extension/Validator/Constraints/FormValidator.php index 4163587576..703bac1484 100644 --- a/Extension/Validator/Constraints/FormValidator.php +++ b/Extension/Validator/Constraints/FormValidator.php @@ -92,7 +92,7 @@ public function validate(mixed $form, Constraint $formConstraint): void $fieldFormConstraint = new Form(); $fieldFormConstraint->groups = $group; $this->context->setNode($this->context->getValue(), $field, $this->context->getMetadata(), $this->context->getPropertyPath()); - $validator->atPath(sprintf('children[%s]', $field->getName()))->validate($field, $fieldFormConstraint, $group); + $validator->atPath(\sprintf('children[%s]', $field->getName()))->validate($field, $fieldFormConstraint, $group); } } @@ -139,7 +139,7 @@ public function validate(mixed $form, Constraint $formConstraint): void if ($field->isSubmitted()) { $this->resolvedGroups[$field] = $groups; $this->context->setNode($this->context->getValue(), $field, $this->context->getMetadata(), $this->context->getPropertyPath()); - $validator->atPath(sprintf('children[%s]', $field->getName()))->validate($field, $formConstraint); + $validator->atPath(\sprintf('children[%s]', $field->getName()))->validate($field, $formConstraint); } } } @@ -156,7 +156,7 @@ public function validate(mixed $form, Constraint $formConstraint): void if (!$child->isSynchronized()) { $childrenSynchronized = false; $this->context->setNode($this->context->getValue(), $child, $this->context->getMetadata(), $this->context->getPropertyPath()); - $validator->atPath(sprintf('children[%s]', $child->getName()))->validate($child, $formConstraint); + $validator->atPath(\sprintf('children[%s]', $child->getName()))->validate($child, $formConstraint); } } diff --git a/Extension/Validator/ValidatorTypeGuesser.php b/Extension/Validator/ValidatorTypeGuesser.php index 72ae8ddd57..08dc6e2d58 100644 --- a/Extension/Validator/ValidatorTypeGuesser.php +++ b/Extension/Validator/ValidatorTypeGuesser.php @@ -230,7 +230,7 @@ public function guessPatternForConstraint(Constraint $constraint): ?ValueGuess switch ($constraint::class) { case Length::class: if (is_numeric($constraint->min)) { - return new ValueGuess(sprintf('.{%s,}', (string) $constraint->min), Guess::LOW_CONFIDENCE); + return new ValueGuess(\sprintf('.{%s,}', (string) $constraint->min), Guess::LOW_CONFIDENCE); } break; @@ -244,7 +244,7 @@ public function guessPatternForConstraint(Constraint $constraint): ?ValueGuess case Range::class: if (is_numeric($constraint->min)) { - return new ValueGuess(sprintf('.{%s,}', \strlen((string) $constraint->min)), Guess::LOW_CONFIDENCE); + return new ValueGuess(\sprintf('.{%s,}', \strlen((string) $constraint->min)), Guess::LOW_CONFIDENCE); } break; diff --git a/Extension/Validator/ViolationMapper/MappingRule.php b/Extension/Validator/ViolationMapper/MappingRule.php index f9a61cc817..3263f66df2 100644 --- a/Extension/Validator/ViolationMapper/MappingRule.php +++ b/Extension/Validator/ViolationMapper/MappingRule.php @@ -64,7 +64,7 @@ public function getTarget(): FormInterface foreach ($childNames as $childName) { if (!$target->has($childName)) { - throw new ErrorMappingException(sprintf('The child "%s" of "%s" mapped by the rule "%s" in "%s" does not exist.', $childName, $target->getName(), $this->targetPath, $this->origin->getName())); + throw new ErrorMappingException(\sprintf('The child "%s" of "%s" mapped by the rule "%s" in "%s" does not exist.', $childName, $target->getName(), $this->targetPath, $this->origin->getName())); } $target = $target->get($childName); } diff --git a/Extension/Validator/ViolationMapper/ViolationPath.php b/Extension/Validator/ViolationMapper/ViolationPath.php index a9a0f15d6e..0c2a130cc8 100644 --- a/Extension/Validator/ViolationMapper/ViolationPath.php +++ b/Extension/Validator/ViolationMapper/ViolationPath.php @@ -132,7 +132,7 @@ public function getElements(): array public function getElement(int $index): string { if (!isset($this->elements[$index])) { - throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index)); + throw new OutOfBoundsException(\sprintf('The index "%s" is not within the violation path.', $index)); } return $this->elements[$index]; @@ -141,7 +141,7 @@ public function getElement(int $index): string public function isProperty(int $index): bool { if (!isset($this->isIndex[$index])) { - throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index)); + throw new OutOfBoundsException(\sprintf('The index "%s" is not within the violation path.', $index)); } return !$this->isIndex[$index]; @@ -150,7 +150,7 @@ public function isProperty(int $index): bool public function isIndex(int $index): bool { if (!isset($this->isIndex[$index])) { - throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index)); + throw new OutOfBoundsException(\sprintf('The index "%s" is not within the violation path.', $index)); } return $this->isIndex[$index]; @@ -176,7 +176,7 @@ public function isNullSafe(int $index): bool public function mapsForm(int $index): bool { if (!isset($this->mapsForm[$index])) { - throw new OutOfBoundsException(sprintf('The index "%s" is not within the violation path.', $index)); + throw new OutOfBoundsException(\sprintf('The index "%s" is not within the violation path.', $index)); } return $this->mapsForm[$index]; diff --git a/Form.php b/Form.php index 44b97261bd..72c60ee41a 100644 --- a/Form.php +++ b/Form.php @@ -738,7 +738,7 @@ public function add(FormInterface|string $child, ?string $type = null, array $op $child = $this->config->getFormFactory()->createNamed($child, $type, null, $options); } } elseif ($child->getConfig()->getAutoInitialize()) { - throw new RuntimeException(sprintf('Automatic initialization is only supported on root forms. You should set the "auto_initialize" option to false on the field "%s".', $child->getName())); + throw new RuntimeException(\sprintf('Automatic initialization is only supported on root forms. You should set the "auto_initialize" option to false on the field "%s".', $child->getName())); } $this->children[$child->getName()] = $child; @@ -800,7 +800,7 @@ public function get(string $name): FormInterface return $this->children[$name]; } - throw new OutOfBoundsException(sprintf('Child "%s" does not exist.', $name)); + throw new OutOfBoundsException(\sprintf('Child "%s" does not exist.', $name)); } /** @@ -933,7 +933,7 @@ private function modelToNorm(mixed $value): mixed $value = $transformer->transform($value); } } catch (TransformationFailedException $exception) { - throw new TransformationFailedException(sprintf('Unable to transform data for property path "%s": ', $this->getPropertyPath()).$exception->getMessage(), $exception->getCode(), $exception, $exception->getInvalidMessage(), $exception->getInvalidMessageParameters()); + throw new TransformationFailedException(\sprintf('Unable to transform data for property path "%s": ', $this->getPropertyPath()).$exception->getMessage(), $exception->getCode(), $exception, $exception->getInvalidMessage(), $exception->getInvalidMessageParameters()); } return $value; @@ -953,7 +953,7 @@ private function normToModel(mixed $value): mixed $value = $transformers[$i]->reverseTransform($value); } } catch (TransformationFailedException $exception) { - throw new TransformationFailedException(sprintf('Unable to reverse value for property path "%s": ', $this->getPropertyPath()).$exception->getMessage(), $exception->getCode(), $exception, $exception->getInvalidMessage(), $exception->getInvalidMessageParameters()); + throw new TransformationFailedException(\sprintf('Unable to reverse value for property path "%s": ', $this->getPropertyPath()).$exception->getMessage(), $exception->getCode(), $exception, $exception->getInvalidMessage(), $exception->getInvalidMessageParameters()); } return $value; @@ -980,7 +980,7 @@ private function normToView(mixed $value): mixed $value = $transformer->transform($value); } } catch (TransformationFailedException $exception) { - throw new TransformationFailedException(sprintf('Unable to transform value for property path "%s": ', $this->getPropertyPath()).$exception->getMessage(), $exception->getCode(), $exception, $exception->getInvalidMessage(), $exception->getInvalidMessageParameters()); + throw new TransformationFailedException(\sprintf('Unable to transform value for property path "%s": ', $this->getPropertyPath()).$exception->getMessage(), $exception->getCode(), $exception, $exception->getInvalidMessage(), $exception->getInvalidMessageParameters()); } return $value; @@ -1002,7 +1002,7 @@ private function viewToNorm(mixed $value): mixed $value = $transformers[$i]->reverseTransform($value); } } catch (TransformationFailedException $exception) { - throw new TransformationFailedException(sprintf('Unable to reverse value for property path "%s": ', $this->getPropertyPath()).$exception->getMessage(), $exception->getCode(), $exception, $exception->getInvalidMessage(), $exception->getInvalidMessageParameters()); + throw new TransformationFailedException(\sprintf('Unable to reverse value for property path "%s": ', $this->getPropertyPath()).$exception->getMessage(), $exception->getCode(), $exception, $exception->getInvalidMessage(), $exception->getInvalidMessageParameters()); } return $value; diff --git a/FormBuilder.php b/FormBuilder.php index 58bc9c86d9..2bfd92a688 100644 --- a/FormBuilder.php +++ b/FormBuilder.php @@ -97,7 +97,7 @@ public function get(string $name): FormBuilderInterface return $this->children[$name]; } - throw new InvalidArgumentException(sprintf('The child with the name "%s" does not exist.', $name)); + throw new InvalidArgumentException(\sprintf('The child with the name "%s" does not exist.', $name)); } public function remove(string $name): static diff --git a/FormConfigBuilder.php b/FormConfigBuilder.php index e0fb01dad9..5d6bd653d4 100644 --- a/FormConfigBuilder.php +++ b/FormConfigBuilder.php @@ -76,7 +76,7 @@ public function __construct( self::validateName($name); if (null !== $dataClass && !class_exists($dataClass) && !interface_exists($dataClass, false)) { - throw new InvalidArgumentException(sprintf('Class "%s" not found. Is the "data_class" form option set correctly?', $dataClass)); + throw new InvalidArgumentException(\sprintf('Class "%s" not found. Is the "data_class" form option set correctly?', $dataClass)); } $this->name = (string) $name; @@ -632,7 +632,7 @@ public function setIsEmptyCallback(?callable $isEmptyCallback): static final public static function validateName(?string $name): void { if (!self::isValidName($name)) { - throw new InvalidArgumentException(sprintf('The name "%s" contains illegal characters. Names should start with a letter, digit or underscore and only contain letters, digits, numbers, underscores ("_"), hyphens ("-") and colons (":").', $name)); + throw new InvalidArgumentException(\sprintf('The name "%s" contains illegal characters. Names should start with a letter, digit or underscore and only contain letters, digits, numbers, underscores ("_"), hyphens ("-") and colons (":").', $name)); } } diff --git a/FormErrorIterator.php b/FormErrorIterator.php index a614e72c2e..4f4a2574d2 100644 --- a/FormErrorIterator.php +++ b/FormErrorIterator.php @@ -58,7 +58,7 @@ public function __construct( ) { foreach ($errors as $error) { if (!($error instanceof FormError || $error instanceof self)) { - throw new InvalidArgumentException(sprintf('The errors must be instances of "Symfony\Component\Form\FormError" or "%s". Got: "%s".', __CLASS__, get_debug_type($error))); + throw new InvalidArgumentException(\sprintf('The errors must be instances of "Symfony\Component\Form\FormError" or "%s". Got: "%s".', __CLASS__, get_debug_type($error))); } } @@ -198,7 +198,7 @@ public function hasChildren(): bool public function getChildren(): self { if (!$this->hasChildren()) { - throw new LogicException(sprintf('The current element is not iterable. Use "%s" to get the current element.', self::class.'::current()')); + throw new LogicException(\sprintf('The current element is not iterable. Use "%s" to get the current element.', self::class.'::current()')); } /** @var self $children */ diff --git a/FormRegistry.php b/FormRegistry.php index 95a0077378..ecf654a2a3 100644 --- a/FormRegistry.php +++ b/FormRegistry.php @@ -69,10 +69,10 @@ public function getType(string $name): ResolvedFormTypeInterface if (!$type) { // Support fully-qualified class names if (!class_exists($name)) { - throw new InvalidArgumentException(sprintf('Could not load type "%s": class does not exist.', $name)); + throw new InvalidArgumentException(\sprintf('Could not load type "%s": class does not exist.', $name)); } if (!is_subclass_of($name, FormTypeInterface::class)) { - throw new InvalidArgumentException(sprintf('Could not load type "%s": class does not implement "Symfony\Component\Form\FormTypeInterface".', $name)); + throw new InvalidArgumentException(\sprintf('Could not load type "%s": class does not implement "Symfony\Component\Form\FormTypeInterface".', $name)); } $type = new $name(); @@ -94,7 +94,7 @@ private function resolveType(FormTypeInterface $type): ResolvedFormTypeInterface if (isset($this->checkedTypes[$fqcn])) { $types = implode(' > ', array_merge(array_keys($this->checkedTypes), [$fqcn])); - throw new LogicException(sprintf('Circular reference detected for form type "%s" (%s).', $fqcn, $types)); + throw new LogicException(\sprintf('Circular reference detected for form type "%s" (%s).', $fqcn, $types)); } $this->checkedTypes[$fqcn] = true; diff --git a/FormRenderer.php b/FormRenderer.php index a9ffd4f41e..4478432b26 100644 --- a/FormRenderer.php +++ b/FormRenderer.php @@ -59,7 +59,7 @@ public function renderBlock(FormView $view, string $blockName, array $variables $resource = $this->engine->getResourceForBlockName($view, $blockName); if (!$resource) { - throw new LogicException(sprintf('No block "%s" found while rendering the form.', $blockName)); + throw new LogicException(\sprintf('No block "%s" found while rendering the form.', $blockName)); } $viewCacheKey = $view->vars[self::CACHE_KEY_VAR]; @@ -116,7 +116,7 @@ public function searchAndRenderBlock(FormView $view, string $blockNameSuffix, ar if ($renderOnlyOnce && $view->isRendered()) { // This is not allowed, because it would result in rendering same IDs multiple times, which is not valid. - throw new BadMethodCallException(sprintf('Field "%s" has already been rendered, save the result of previous render call to a variable and output that instead.', $view->vars['name'])); + throw new BadMethodCallException(\sprintf('Field "%s" has already been rendered, save the result of previous render call to a variable and output that instead.', $view->vars['name'])); } // The cache key for storing the variables and types @@ -203,10 +203,10 @@ public function searchAndRenderBlock(FormView $view, string $blockNameSuffix, ar // Escape if no resource exists for this block if (!$resource) { if (\count($blockNameHierarchy) !== \count(array_unique($blockNameHierarchy))) { - throw new LogicException(sprintf('Unable to render the form because the block names array contains duplicates: "%s".', implode('", "', array_reverse($blockNameHierarchy)))); + throw new LogicException(\sprintf('Unable to render the form because the block names array contains duplicates: "%s".', implode('", "', array_reverse($blockNameHierarchy)))); } - throw new LogicException(sprintf('Unable to render the form as none of the following blocks exist: "%s".', implode('", "', array_reverse($blockNameHierarchy)))); + throw new LogicException(\sprintf('Unable to render the form as none of the following blocks exist: "%s".', implode('", "', array_reverse($blockNameHierarchy)))); } // Merge the passed with the existing attributes diff --git a/PreloadedExtension.php b/PreloadedExtension.php index 58d8f13b1b..26090e00df 100644 --- a/PreloadedExtension.php +++ b/PreloadedExtension.php @@ -41,7 +41,7 @@ public function __construct( public function getType(string $name): FormTypeInterface { if (!isset($this->types[$name])) { - throw new InvalidArgumentException(sprintf('The type "%s" cannot be loaded by this extension.', $name)); + throw new InvalidArgumentException(\sprintf('The type "%s" cannot be loaded by this extension.', $name)); } return $this->types[$name]; diff --git a/ResolvedFormType.php b/ResolvedFormType.php index 964619c396..82065f6511 100644 --- a/ResolvedFormType.php +++ b/ResolvedFormType.php @@ -72,7 +72,7 @@ public function createBuilder(FormFactoryInterface $factory, string $name, array try { $options = $this->getOptionsResolver()->resolve($options); } catch (ExceptionInterface $e) { - throw new $e(sprintf('An error has occurred resolving the options of the form "%s": ', get_debug_type($this->getInnerType())).$e->getMessage(), $e->getCode(), $e); + throw new $e(\sprintf('An error has occurred resolving the options of the form "%s": ', get_debug_type($this->getInnerType())).$e->getMessage(), $e->getCode(), $e); } // Should be decoupled from the specific option at some point diff --git a/Test/FormPerformanceTestCase.php b/Test/FormPerformanceTestCase.php index 54ccc67cfd..1d631a2fde 100644 --- a/Test/FormPerformanceTestCase.php +++ b/Test/FormPerformanceTestCase.php @@ -34,7 +34,7 @@ protected function runTest(): mixed $time = microtime(true) - $s; if (0 != $this->maxRunningTime && $time > $this->maxRunningTime) { - $this->fail(sprintf('expected running time: <= %s but was: %s', $this->maxRunningTime, $time)); + $this->fail(\sprintf('expected running time: <= %s but was: %s', $this->maxRunningTime, $time)); } return $result; diff --git a/Test/Traits/ValidatorExtensionTrait.php b/Test/Traits/ValidatorExtensionTrait.php index b89095de72..5d0486e8cf 100644 --- a/Test/Traits/ValidatorExtensionTrait.php +++ b/Test/Traits/ValidatorExtensionTrait.php @@ -28,7 +28,7 @@ protected function getValidatorExtension(): ValidatorExtension } if (!$this instanceof TypeTestCase) { - throw new \Exception(sprintf('The trait "ValidatorExtensionTrait" can only be added to a class that extends "%s".', TypeTestCase::class)); + throw new \Exception(\sprintf('The trait "ValidatorExtensionTrait" can only be added to a class that extends "%s".', TypeTestCase::class)); } $this->validator = $this->createMock(ValidatorInterface::class); diff --git a/Tests/Console/Descriptor/AbstractDescriptorTestCase.php b/Tests/Console/Descriptor/AbstractDescriptorTestCase.php index fa8745b584..8a99c205cb 100644 --- a/Tests/Console/Descriptor/AbstractDescriptorTestCase.php +++ b/Tests/Console/Descriptor/AbstractDescriptorTestCase.php @@ -153,7 +153,7 @@ private function getExpectedDescription($name) private function getFixtureFilename($name) { - return sprintf('%s/../../Fixtures/Descriptor/%s.%s', __DIR__, $name, $this->getFormat()); + return \sprintf('%s/../../Fixtures/Descriptor/%s.%s', __DIR__, $name, $this->getFormat()); } } diff --git a/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php b/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php index 26055c203c..5d1e77eece 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php @@ -31,7 +31,7 @@ protected function getExtensions() { $translator = $this->createMock(TranslatorInterface::class); $translator->expects($this->any())->method('trans') - ->willReturnCallback(fn ($key, $params) => strtr(sprintf('Translation of: %s', $key), $params) + ->willReturnCallback(fn ($key, $params) => strtr(\sprintf('Translation of: %s', $key), $params) ); return array_merge(parent::getExtensions(), [new CoreExtension(null, null, $translator)]); diff --git a/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php b/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php index b99240c8cb..8f2cbdcd5d 100644 --- a/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php +++ b/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php @@ -44,7 +44,7 @@ public function testGetTypeExtensions() public function testThrowExceptionForInvalidExtendedType() { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage(sprintf('The extended type "unmatched" specified for the type extension class "%s" does not match any of the actual extended types (["test"]).', TestTypeExtension::class)); + $this->expectExceptionMessage(\sprintf('The extended type "unmatched" specified for the type extension class "%s" does not match any of the actual extended types (["test"]).', TestTypeExtension::class)); $extensions = [ 'unmatched' => new \ArrayIterator([new TestTypeExtension()]), diff --git a/Tests/ResolvedFormTypeTest.php b/Tests/ResolvedFormTypeTest.php index ba0bf243d0..fa28f75472 100644 --- a/Tests/ResolvedFormTypeTest.php +++ b/Tests/ResolvedFormTypeTest.php @@ -100,7 +100,7 @@ public function testCreateBuilderWithDataClassOption() public function testFailsCreateBuilderOnInvalidFormOptionsResolution() { $this->expectException(MissingOptionsException::class); - $this->expectExceptionMessage(sprintf('An error has occurred resolving the options of the form "%s": The required option "foo" is missing.', UsageTrackingFormType::class)); + $this->expectExceptionMessage(\sprintf('An error has occurred resolving the options of the form "%s": The required option "foo" is missing.', UsageTrackingFormType::class)); $this->resolvedType->createBuilder($this->formFactory, 'name'); } diff --git a/Tests/Resources/TranslationFilesTest.php b/Tests/Resources/TranslationFilesTest.php index 3b2fe40f4d..157335dc6d 100644 --- a/Tests/Resources/TranslationFilesTest.php +++ b/Tests/Resources/TranslationFilesTest.php @@ -26,7 +26,7 @@ public function testTranslationFileIsValid($filePath) $errors = XliffUtils::validateSchema($document); - $this->assertCount(0, $errors, sprintf('"%s" is invalid:%s', $filePath, \PHP_EOL.implode(\PHP_EOL, array_column($errors, 'message')))); + $this->assertCount(0, $errors, \sprintf('"%s" is invalid:%s', $filePath, \PHP_EOL.implode(\PHP_EOL, array_column($errors, 'message')))); } /** @@ -39,7 +39,7 @@ public function testTranslationFileIsValidWithoutEntityLoader($filePath) $errors = XliffUtils::validateSchema($document); - $this->assertCount(0, $errors, sprintf('"%s" is invalid:%s', $filePath, \PHP_EOL.implode(\PHP_EOL, array_column($errors, 'message')))); + $this->assertCount(0, $errors, \sprintf('"%s" is invalid:%s', $filePath, \PHP_EOL.implode(\PHP_EOL, array_column($errors, 'message')))); } public static function provideTranslationFiles() diff --git a/Tests/VersionAwareTest.php b/Tests/VersionAwareTest.php index 1a35b72fc0..90e0d10af6 100644 --- a/Tests/VersionAwareTest.php +++ b/Tests/VersionAwareTest.php @@ -18,7 +18,7 @@ trait VersionAwareTest protected function requiresFeatureSet(int $requiredFeatureSetVersion) { if ($requiredFeatureSetVersion > static::$supportedFeatureSetVersion) { - $this->markTestSkipped(sprintf('Test requires features from symfony/form %.2f but only version %.2f is supported.', $requiredFeatureSetVersion / 100, static::$supportedFeatureSetVersion / 100)); + $this->markTestSkipped(\sprintf('Test requires features from symfony/form %.2f but only version %.2f is supported.', $requiredFeatureSetVersion / 100, static::$supportedFeatureSetVersion / 100)); } } } diff --git a/Util/OrderedHashMap.php b/Util/OrderedHashMap.php index 145bd2e25e..7f81c07390 100644 --- a/Util/OrderedHashMap.php +++ b/Util/OrderedHashMap.php @@ -105,7 +105,7 @@ public function offsetExists(mixed $key): bool public function offsetGet(mixed $key): mixed { if (!isset($this->elements[$key])) { - throw new \OutOfBoundsException(sprintf('The offset "%s" does not exist.', $key)); + throw new \OutOfBoundsException(\sprintf('The offset "%s" does not exist.', $key)); } return $this->elements[$key]; From d131e439bb20f5c3d39cfde0b0d8eedf7c7a9fa5 Mon Sep 17 00:00:00 2001 From: Dariusz Ruminski Date: Sun, 16 Jun 2024 17:17:26 +0200 Subject: [PATCH 166/208] chore: CS fixes --- AbstractTypeExtension.php | 3 -- FormTypeExtensionInterface.php | 3 -- .../Factory/DefaultChoiceListFactoryTest.php | 10 +++---- .../Loader/CallbackChoiceLoaderTest.php | 4 +-- Tests/Extension/Core/Type/ChoiceTypeTest.php | 4 +-- Tests/Extension/Core/Type/FormTypeTest.php | 18 +++++------ .../DataCollector/FormDataCollectorTest.php | 14 ++++----- .../FormValidatorFunctionalTest.php | 6 ++-- .../Constraints/FormValidatorTest.php | 30 +++++++++---------- Tests/NativeRequestHandlerTest.php | 4 +-- Tests/SimpleFormTest.php | 6 ++-- Tests/Util/StringUtilTest.php | 2 +- 12 files changed, 49 insertions(+), 55 deletions(-) diff --git a/AbstractTypeExtension.php b/AbstractTypeExtension.php index 9f6da0a336..b32f3b522f 100644 --- a/AbstractTypeExtension.php +++ b/AbstractTypeExtension.php @@ -18,9 +18,6 @@ */ abstract class AbstractTypeExtension implements FormTypeExtensionInterface { - /** - * @return void - */ public function configureOptions(OptionsResolver $resolver): void { } diff --git a/FormTypeExtensionInterface.php b/FormTypeExtensionInterface.php index 3e2d2d03e4..838406d2af 100644 --- a/FormTypeExtensionInterface.php +++ b/FormTypeExtensionInterface.php @@ -25,9 +25,6 @@ interface FormTypeExtensionInterface */ public static function getExtendedTypes(): iterable; - /** - * @return void - */ public function configureOptions(OptionsResolver $resolver): void; /** diff --git a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index e7bf26d178..f82fdc2f99 100644 --- a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -159,9 +159,9 @@ public function testCreateFromChoicesGroupedTraversable() { $list = $this->factory->createListFromChoices( new \ArrayIterator([ - 'Group 1' => ['A' => $this->obj1, 'B' => $this->obj2], - 'Group 2' => ['C' => $this->obj3, 'D' => $this->obj4], - ]) + 'Group 1' => ['A' => $this->obj1, 'B' => $this->obj2], + 'Group 2' => ['C' => $this->obj3, 'D' => $this->obj4], + ]) ); $this->assertObjectListWithGeneratedValues($list); @@ -941,7 +941,7 @@ private function assertFlatViewWithAttr($view) 'C', ['attr2' => 'value2'] ), - ] + ] ), $view); } @@ -987,7 +987,7 @@ private function assertGroupedView($view) 'Group 2', [2 => new ChoiceView($this->obj3, '2', 'C')] ), - ] + ] ), $view); } diff --git a/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php b/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php index d394196ee1..791a6f006e 100644 --- a/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php +++ b/Tests/ChoiceList/Loader/CallbackChoiceLoaderTest.php @@ -69,8 +69,8 @@ public function testLoadChoicesForValuesLoadsChoiceListOnFirstCall() public function testLoadValuesForChoicesCastsCallbackItemsToString() { $choices = [ - (object) ['id' => 2], - (object) ['id' => 3], + (object) ['id' => 2], + (object) ['id' => 3], ]; $value = fn ($item) => $item->id; diff --git a/Tests/Extension/Core/Type/ChoiceTypeTest.php b/Tests/Extension/Core/Type/ChoiceTypeTest.php index 8e2372d7e1..c4f18734f8 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -1895,8 +1895,8 @@ public function testInitializeWithEmptyChoices() { $this->assertInstanceOf( FormInterface::class, $this->factory->createNamed('name', static::TESTED_TYPE, null, [ - 'choices' => [], - ])); + 'choices' => [], + ])); } public function testInitializeWithDefaultObjectChoice() diff --git a/Tests/Extension/Core/Type/FormTypeTest.php b/Tests/Extension/Core/Type/FormTypeTest.php index be89c559f6..fe838885ed 100644 --- a/Tests/Extension/Core/Type/FormTypeTest.php +++ b/Tests/Extension/Core/Type/FormTypeTest.php @@ -156,24 +156,24 @@ public function testDataClassMayBeNull() { $this->assertInstanceOf( FormBuilderInterface::class, $this->factory->createBuilder(static::TESTED_TYPE, null, [ - 'data_class' => null, - ])); + 'data_class' => null, + ])); } public function testDataClassMayBeAbstractClass() { $this->assertInstanceOf( FormBuilderInterface::class, $this->factory->createBuilder(static::TESTED_TYPE, null, [ - 'data_class' => 'Symfony\Component\Form\Tests\Fixtures\AbstractAuthor', - ])); + 'data_class' => 'Symfony\Component\Form\Tests\Fixtures\AbstractAuthor', + ])); } public function testDataClassMayBeInterface() { $this->assertInstanceOf( FormBuilderInterface::class, $this->factory->createBuilder(static::TESTED_TYPE, null, [ - 'data_class' => 'Symfony\Component\Form\Tests\Fixtures\AuthorInterface', - ])); + 'data_class' => 'Symfony\Component\Form\Tests\Fixtures\AuthorInterface', + ])); } public function testDataClassMustBeValidClassOrInterface() @@ -402,7 +402,7 @@ public function testSubformCallsSettersIfTheObjectChanged() // referenceCopy has a getter that returns a copy 'referenceCopy' => [ 'firstName' => 'Foo', - ], + ], ]); $this->assertEquals('Foo', $author->getReferenceCopy()->firstName); @@ -680,8 +680,8 @@ public function testDataMapperTransformationFailedExceptionInvalidMessageIsUsed( public function testPassZeroLabelToView() { $view = $this->factory->create(static::TESTED_TYPE, null, [ - 'label' => '0', - ]) + 'label' => '0', + ]) ->createView(); $this->assertSame('0', $view->vars['label']); diff --git a/Tests/Extension/DataCollector/FormDataCollectorTest.php b/Tests/Extension/DataCollector/FormDataCollectorTest.php index 798faa0c5e..0517b26c3b 100644 --- a/Tests/Extension/DataCollector/FormDataCollectorTest.php +++ b/Tests/Extension/DataCollector/FormDataCollectorTest.php @@ -71,7 +71,7 @@ public function testBuildPreliminaryFormTree() ], 'errors' => [], 'children' => [], - ]; + ]; $formData = [ 'id' => 'name', @@ -87,11 +87,11 @@ public function testBuildPreliminaryFormTree() 'norm' => null, ], 'errors' => [], - 'has_children_error' => false, - 'children' => [ - 'child' => $childFormData, - ], - ]; + 'has_children_error' => false, + 'children' => [ + 'child' => $childFormData, + ], + ]; $this->assertEquals([ 'forms' => [ @@ -102,7 +102,7 @@ public function testBuildPreliminaryFormTree() spl_object_hash($this->childForm) => $childFormData, ], 'nb_errors' => 0, - ], $this->dataCollector->getData()); + ], $this->dataCollector->getData()); } public function testBuildMultiplePreliminaryFormTrees() diff --git a/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php b/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php index aa6056c137..14595e8cf5 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php @@ -88,9 +88,9 @@ public function testFieldConstraintsInvalidateFormIfFieldIsSubmitted() public function testNonCompositeConstraintValidatedOnce() { $form = $this->formFactory->create(TextType::class, null, [ - 'constraints' => [new NotBlank(['groups' => ['foo', 'bar']])], - 'validation_groups' => ['foo', 'bar'], - ]); + 'constraints' => [new NotBlank(['groups' => ['foo', 'bar']])], + 'validation_groups' => ['foo', 'bar'], + ]); $form->submit(''); $violations = $this->validator->validate($form); diff --git a/Tests/Extension/Validator/Constraints/FormValidatorTest.php b/Tests/Extension/Validator/Constraints/FormValidatorTest.php index 4e1588a9c7..86b53ac3ad 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorTest.php @@ -184,8 +184,8 @@ public function testDontValidateIfNoValidationGroups() $object = new \stdClass(); $form = $this->getBuilder('name', '\stdClass', [ - 'validation_groups' => [], - ]) + 'validation_groups' => [], + ]) ->setData($object) ->setCompound(true) ->setDataMapper(new DataMapper()) @@ -256,12 +256,12 @@ public function testDontValidateIfNotSynchronized() $object = new \stdClass(); $form = $this->getBuilder('name', '\stdClass', [ - 'invalid_message' => 'invalid_message_key', - // Invalid message parameters must be supported, because the - // invalid message can be a translation key - // see https://github.com/symfony/symfony/issues/5144 - 'invalid_message_parameters' => ['{{ foo }}' => 'bar'], - ]) + 'invalid_message' => 'invalid_message_key', + // Invalid message parameters must be supported, because the + // invalid message can be a translation key + // see https://github.com/symfony/symfony/issues/5144 + 'invalid_message_parameters' => ['{{ foo }}' => 'bar'], + ]) ->setData($object) ->addViewTransformer(new CallbackTransformer( static fn ($data) => $data, @@ -292,13 +292,13 @@ public function testAddInvalidErrorEvenIfNoValidationGroups() $object = new \stdClass(); $form = $this->getBuilder('name', '\stdClass', [ - 'invalid_message' => 'invalid_message_key', - // Invalid message parameters must be supported, because the - // invalid message can be a translation key - // see https://github.com/symfony/symfony/issues/5144 - 'invalid_message_parameters' => ['{{ foo }}' => 'bar'], - 'validation_groups' => [], - ]) + 'invalid_message' => 'invalid_message_key', + // Invalid message parameters must be supported, because the + // invalid message can be a translation key + // see https://github.com/symfony/symfony/issues/5144 + 'invalid_message_parameters' => ['{{ foo }}' => 'bar'], + 'validation_groups' => [], + ]) ->setData($object) ->addViewTransformer(new CallbackTransformer( static fn ($data) => $data, diff --git a/Tests/NativeRequestHandlerTest.php b/Tests/NativeRequestHandlerTest.php index 679c3366d8..3770e12199 100644 --- a/Tests/NativeRequestHandlerTest.php +++ b/Tests/NativeRequestHandlerTest.php @@ -172,8 +172,8 @@ public function testMethodOverrideHeaderIgnoredIfNotPost() $form = $this->createForm('param1', 'POST'); $this->setRequestData('GET', [ - 'param1' => 'DATA', - ]); + 'param1' => 'DATA', + ]); $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT'; diff --git a/Tests/SimpleFormTest.php b/Tests/SimpleFormTest.php index 7ded9b8535..d5d3549d2a 100644 --- a/Tests/SimpleFormTest.php +++ b/Tests/SimpleFormTest.php @@ -503,9 +503,9 @@ public function testSetDataConvertsScalarToStringIfOnlyModelTransformer() { $form = $this->getBuilder() ->addModelTransformer(new FixedDataTransformer([ - '' => '', - 1 => 23, - ])) + '' => '', + 1 => 23, + ])) ->getForm(); $form->setData(1); diff --git a/Tests/Util/StringUtilTest.php b/Tests/Util/StringUtilTest.php index 8199d6843e..d51481f6c1 100644 --- a/Tests/Util/StringUtilTest.php +++ b/Tests/Util/StringUtilTest.php @@ -56,7 +56,7 @@ public static function spaceProvider(): array ['0020'], ['00A0'], ['1680'], -// ['180E'], + // ['180E'], ['2000'], ['2001'], ['2002'], From 717223d83e3a1df104d0fe989b6f43c15c8e44b9 Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Tue, 25 Jun 2024 14:58:00 +0200 Subject: [PATCH 167/208] Add more precise types in reusable test cases --- Test/FormIntegrationTestCase.php | 16 ++++++++++++++++ Test/TypeTestCase.php | 10 ++++++++++ .../Core/Type/ChoiceTypeTranslationTest.php | 2 +- Tests/Extension/Core/Type/FileTypeTest.php | 2 +- .../Csrf/Type/FormTypeCsrfExtensionTest.php | 2 +- .../Type/TextTypeHtmlSanitizerExtensionTest.php | 2 +- .../PasswordTypePasswordHasherExtensionTest.php | 2 +- .../Constraints/FormValidatorPerformanceTest.php | 2 +- 8 files changed, 32 insertions(+), 6 deletions(-) diff --git a/Test/FormIntegrationTestCase.php b/Test/FormIntegrationTestCase.php index 5bf37fd48a..8756d99689 100644 --- a/Test/FormIntegrationTestCase.php +++ b/Test/FormIntegrationTestCase.php @@ -12,8 +12,12 @@ namespace Symfony\Component\Form\Test; use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\FormExtensionInterface; use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\Forms; +use Symfony\Component\Form\FormTypeExtensionInterface; +use Symfony\Component\Form\FormTypeGuesserInterface; +use Symfony\Component\Form\FormTypeInterface; /** * @author Bernhard Schussek @@ -32,21 +36,33 @@ protected function setUp(): void ->getFormFactory(); } + /** + * @return FormExtensionInterface[] + */ protected function getExtensions() { return []; } + /** + * @return FormTypeExtensionInterface[] + */ protected function getTypeExtensions() { return []; } + /** + * @return FormTypeInterface[] + */ protected function getTypes() { return []; } + /** + * @return FormTypeGuesserInterface[] + */ protected function getTypeGuessers() { return []; diff --git a/Test/TypeTestCase.php b/Test/TypeTestCase.php index 960b44228b..1bbb66d25d 100644 --- a/Test/TypeTestCase.php +++ b/Test/TypeTestCase.php @@ -13,6 +13,7 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Form\FormBuilder; +use Symfony\Component\Form\FormExtensionInterface; use Symfony\Component\Form\Test\Traits\ValidatorExtensionTrait; abstract class TypeTestCase extends FormIntegrationTestCase @@ -28,6 +29,9 @@ protected function setUp(): void $this->builder = new FormBuilder('', null, $this->dispatcher, $this->factory); } + /** + * @return FormExtensionInterface[] + */ protected function getExtensions() { $extensions = []; @@ -39,11 +43,17 @@ protected function getExtensions() return $extensions; } + /** + * @return void + */ public static function assertDateTimeEquals(\DateTime $expected, \DateTime $actual) { self::assertEquals($expected->format('c'), $actual->format('c')); } + /** + * @return void + */ public static function assertDateIntervalEquals(\DateInterval $expected, \DateInterval $actual) { self::assertEquals($expected->format('%RP%yY%mM%dDT%hH%iM%sS'), $actual->format('%RP%yY%mM%dDT%hH%iM%sS')); diff --git a/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php b/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php index 5d1e77eece..af58e2ecfa 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php @@ -27,7 +27,7 @@ class ChoiceTypeTranslationTest extends TypeTestCase 'Roman' => 'e', ]; - protected function getExtensions() + protected function getExtensions(): array { $translator = $this->createMock(TranslatorInterface::class); $translator->expects($this->any())->method('trans') diff --git a/Tests/Extension/Core/Type/FileTypeTest.php b/Tests/Extension/Core/Type/FileTypeTest.php index b7f3332c1e..9c3a8efd0a 100644 --- a/Tests/Extension/Core/Type/FileTypeTest.php +++ b/Tests/Extension/Core/Type/FileTypeTest.php @@ -23,7 +23,7 @@ class FileTypeTest extends BaseTypeTestCase { public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\FileType'; - protected function getExtensions() + protected function getExtensions(): array { return array_merge(parent::getExtensions(), [new CoreExtension(null, null, new IdentityTranslator())]); } diff --git a/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php b/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php index bfa3025554..d5bce6527b 100644 --- a/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php +++ b/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php @@ -42,7 +42,7 @@ protected function setUp(): void parent::setUp(); } - protected function getExtensions() + protected function getExtensions(): array { return array_merge(parent::getExtensions(), [ new CsrfExtension($this->tokenManager, new IdentityTranslator()), diff --git a/Tests/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtensionTest.php b/Tests/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtensionTest.php index 39b8d03323..6784576b05 100644 --- a/Tests/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtensionTest.php +++ b/Tests/Extension/HtmlSanitizer/Type/TextTypeHtmlSanitizerExtensionTest.php @@ -20,7 +20,7 @@ class TextTypeHtmlSanitizerExtensionTest extends TypeTestCase { - protected function getExtensions() + protected function getExtensions(): array { $fooSanitizer = $this->createMock(HtmlSanitizerInterface::class); $fooSanitizer->expects($this->once()) diff --git a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php index 4ec91c8274..07d1292a3f 100644 --- a/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php +++ b/Tests/Extension/PasswordHasher/Type/PasswordTypePasswordHasherExtensionTest.php @@ -40,7 +40,7 @@ protected function setUp(): void parent::setUp(); } - protected function getExtensions() + protected function getExtensions(): array { return array_merge(parent::getExtensions(), [ new PasswordHasherExtension(new PasswordHasherListener($this->passwordHasher)), diff --git a/Tests/Extension/Validator/Constraints/FormValidatorPerformanceTest.php b/Tests/Extension/Validator/Constraints/FormValidatorPerformanceTest.php index e8bfbc64ae..b0c7d719ae 100644 --- a/Tests/Extension/Validator/Constraints/FormValidatorPerformanceTest.php +++ b/Tests/Extension/Validator/Constraints/FormValidatorPerformanceTest.php @@ -20,7 +20,7 @@ */ class FormValidatorPerformanceTest extends FormPerformanceTestCase { - protected function getExtensions() + protected function getExtensions(): array { return [ new ValidatorExtension(Validation::createValidator(), false), From 8c1030ce9365f4e2885c55149991aae266159347 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 25 Jun 2024 08:08:32 +0200 Subject: [PATCH 168/208] Unify how --format is handle by commands --- Command/DebugCommand.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index 18d208cbe8..91db6f1a91 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -272,6 +272,7 @@ private function completeOptions(string $class, CompletionSuggestions $suggestio $suggestions->suggestValues($resolvedType->getOptionsResolver()->getDefinedOptions()); } + /** @return string[] */ private function getAvailableFormatOptions(): array { return (new DescriptorHelper())->getFormats(); From a1664a2508e19556bf20e2c5a6e0fe8483eec4c9 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sat, 6 Jul 2024 09:57:16 +0200 Subject: [PATCH 169/208] Update .gitattributes --- .gitattributes | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.gitattributes b/.gitattributes index 84c7add058..14c3c35940 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,3 @@ /Tests export-ignore /phpunit.xml.dist export-ignore -/.gitattributes export-ignore -/.gitignore export-ignore +/.git* export-ignore From f63434d11b165831a089e0b90f74582184ec9679 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Thu, 18 Jul 2024 10:20:59 +0200 Subject: [PATCH 170/208] [Validator] Use CPP in `ConstraintViolation` --- Tests/Extension/DataCollector/FormDataExtractorTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/Extension/DataCollector/FormDataExtractorTest.php b/Tests/Extension/DataCollector/FormDataExtractorTest.php index ec01721c70..4aa9cf4d2f 100644 --- a/Tests/Extension/DataCollector/FormDataExtractorTest.php +++ b/Tests/Extension/DataCollector/FormDataExtractorTest.php @@ -314,12 +314,12 @@ public function testExtractSubmittedDataStoresErrorCause() -message: "Foo" -messageTemplate: "Foo" -parameters: [] - -plural: null -root: "Root" -propertyPath: "property.path" -invalidValue: "Invalid!" - -constraint: null + -plural: null -code: null + -constraint: null -cause: Exception {%A} } 1 => Exception {#1} From 67dd6a3fd986cae9a90a8c2c526464c06f525863 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Fri, 19 Jul 2024 10:08:53 +0200 Subject: [PATCH 171/208] fix tests --- .../DataCollector/FormDataExtractorTest.php | 90 +++++++++++++------ 1 file changed, 62 insertions(+), 28 deletions(-) diff --git a/Tests/Extension/DataCollector/FormDataExtractorTest.php b/Tests/Extension/DataCollector/FormDataExtractorTest.php index ec01721c70..b8a1fee374 100644 --- a/Tests/Extension/DataCollector/FormDataExtractorTest.php +++ b/Tests/Extension/DataCollector/FormDataExtractorTest.php @@ -26,6 +26,7 @@ use Symfony\Component\Form\ResolvedFormType; use Symfony\Component\Form\ResolvedFormTypeFactory; use Symfony\Component\Form\Tests\Fixtures\FixedDataTransformer; +use Symfony\Component\Validator\Constraints\WordCount; use Symfony\Component\Validator\ConstraintViolation; use Symfony\Component\VarDumper\Test\VarDumperTestTrait; @@ -300,35 +301,68 @@ public function testExtractSubmittedDataStoresErrorCause() $form->addError(new FormError('Invalid!', null, [], null, $violation)); $origin = spl_object_hash($form); - $this->assertDumpMatchesFormat(<< array:1 [ - "norm" => "Foobar" - ] - "errors" => array:1 [ - 0 => array:3 [ - "message" => "Invalid!" - "origin" => "$origin" - "trace" => array:2 [ - 0 => Symfony\Component\Validator\ConstraintViolation { - -message: "Foo" - -messageTemplate: "Foo" - -parameters: [] - -plural: null - -root: "Root" - -propertyPath: "property.path" - -invalidValue: "Invalid!" - -constraint: null - -code: null - -cause: Exception {%A} + if (class_exists(WordCount::class)) { + $expectedFormat = <<<"EODUMP" + array:3 [ + "submitted_data" => array:1 [ + "norm" => "Foobar" + ] + "errors" => array:1 [ + 0 => array:3 [ + "message" => "Invalid!" + "origin" => "$origin" + "trace" => array:2 [ + 0 => Symfony\Component\Validator\ConstraintViolation { + -message: "Foo" + -messageTemplate: "Foo" + -parameters: [] + -root: "Root" + -propertyPath: "property.path" + -invalidValue: "Invalid!" + -plural: null + -code: null + -constraint: null + -cause: Exception {%A} + } + 1 => Exception {#1} + ] + ] + ] + "synchronized" => true + ] + EODUMP; + } else { + $expectedFormat = <<<"EODUMP" + array:3 [ + "submitted_data" => array:1 [ + "norm" => "Foobar" + ] + "errors" => array:1 [ + 0 => array:3 [ + "message" => "Invalid!" + "origin" => "$origin" + "trace" => array:2 [ + 0 => Symfony\Component\Validator\ConstraintViolation { + -message: "Foo" + -messageTemplate: "Foo" + -parameters: [] + -plural: null + -root: "Root" + -propertyPath: "property.path" + -invalidValue: "Invalid!" + -constraint: null + -code: null + -cause: Exception {%A} + } + 1 => Exception {#1} + ] + ] + ] + "synchronized" => true + ] + EODUMP; } - 1 => Exception {#1} - ] - ] - ] - "synchronized" => true -] -EODUMP + $this->assertDumpMatchesFormat($expectedFormat , $this->dataExtractor->extractSubmittedData($form) ); From 2b2fc826310d853594889c3c4ab9cd619170c932 Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Sat, 13 Apr 2024 14:18:00 +0200 Subject: [PATCH 172/208] [PhpUnitBridge] Add ExpectUserDeprecationMessageTrait --- Tests/Extension/Core/Type/UrlTypeTest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/Extension/Core/Type/UrlTypeTest.php b/Tests/Extension/Core/Type/UrlTypeTest.php index 28e8b9ac74..243d15297c 100644 --- a/Tests/Extension/Core/Type/UrlTypeTest.php +++ b/Tests/Extension/Core/Type/UrlTypeTest.php @@ -11,12 +11,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; -use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; +use Symfony\Bridge\PhpUnit\ExpectUserDeprecationMessageTrait; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class UrlTypeTest extends TextTypeTest { - use ExpectDeprecationTrait; + use ExpectUserDeprecationMessageTrait; public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\UrlType'; @@ -25,7 +25,7 @@ class UrlTypeTest extends TextTypeTest */ public function testSubmitAddsDefaultProtocolIfNoneIsIncluded() { - $this->expectDeprecation('Since symfony/form 7.1: Not configuring the "default_protocol" option when using the UrlType is deprecated. It will default to "null" in 8.0.'); + $this->expectUserDeprecationMessage('Since symfony/form 7.1: Not configuring the "default_protocol" option when using the UrlType is deprecated. It will default to "null" in 8.0.'); $form = $this->factory->create(static::TESTED_TYPE, 'name'); $form->submit('www.domain.com'); From 56575c475e10066cfb3c580a2e911b8d4df92efe Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Mon, 22 Jul 2024 10:27:43 +0200 Subject: [PATCH 173/208] Use CPP where possible --- ChoiceList/Factory/CachingFactoryDecorator.php | 8 +++----- ChoiceList/Factory/PropertyAccessDecorator.php | 8 ++++---- .../DataTransformer/BooleanToStringTransformer.php | 12 ++++-------- Extension/Core/Type/ChoiceType.php | 8 ++++---- 4 files changed, 15 insertions(+), 21 deletions(-) diff --git a/ChoiceList/Factory/CachingFactoryDecorator.php b/ChoiceList/Factory/CachingFactoryDecorator.php index 687fcec1ee..1f373228b5 100644 --- a/ChoiceList/Factory/CachingFactoryDecorator.php +++ b/ChoiceList/Factory/CachingFactoryDecorator.php @@ -27,8 +27,6 @@ */ class CachingFactoryDecorator implements ChoiceListFactoryInterface, ResetInterface { - private ChoiceListFactoryInterface $decoratedFactory; - /** * @var ChoiceListInterface[] */ @@ -64,9 +62,9 @@ public static function generateHash(mixed $value, string $namespace = ''): strin return hash('sha256', $namespace.':'.serialize($value)); } - public function __construct(ChoiceListFactoryInterface $decoratedFactory) - { - $this->decoratedFactory = $decoratedFactory; + public function __construct( + private ChoiceListFactoryInterface $decoratedFactory, + ) { } /** diff --git a/ChoiceList/Factory/PropertyAccessDecorator.php b/ChoiceList/Factory/PropertyAccessDecorator.php index c83ef17e9f..f73a8fc2aa 100644 --- a/ChoiceList/Factory/PropertyAccessDecorator.php +++ b/ChoiceList/Factory/PropertyAccessDecorator.php @@ -38,12 +38,12 @@ */ class PropertyAccessDecorator implements ChoiceListFactoryInterface { - private ChoiceListFactoryInterface $decoratedFactory; private PropertyAccessorInterface $propertyAccessor; - public function __construct(ChoiceListFactoryInterface $decoratedFactory, ?PropertyAccessorInterface $propertyAccessor = null) - { - $this->decoratedFactory = $decoratedFactory; + public function __construct( + private ChoiceListFactoryInterface $decoratedFactory, + ?PropertyAccessorInterface $propertyAccessor = null, + ) { $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor(); } diff --git a/Extension/Core/DataTransformer/BooleanToStringTransformer.php b/Extension/Core/DataTransformer/BooleanToStringTransformer.php index e91bdb4dbf..7ef84bb448 100644 --- a/Extension/Core/DataTransformer/BooleanToStringTransformer.php +++ b/Extension/Core/DataTransformer/BooleanToStringTransformer.php @@ -25,17 +25,13 @@ */ class BooleanToStringTransformer implements DataTransformerInterface { - private string $trueValue; - - private array $falseValues; - /** * @param string $trueValue The value emitted upon transform if the input is true */ - public function __construct(string $trueValue, array $falseValues = [null]) - { - $this->trueValue = $trueValue; - $this->falseValues = $falseValues; + public function __construct( + private string $trueValue, + private array $falseValues = [null], + ) { if (\in_array($this->trueValue, $this->falseValues, true)) { throw new InvalidArgumentException('The specified "true" value is contained in the false-values.'); } diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 36ebe6c840..0042d75805 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -51,16 +51,16 @@ class ChoiceType extends AbstractType { private ChoiceListFactoryInterface $choiceListFactory; - private ?TranslatorInterface $translator; - public function __construct(?ChoiceListFactoryInterface $choiceListFactory = null, ?TranslatorInterface $translator = null) - { + public function __construct( + ?ChoiceListFactoryInterface $choiceListFactory = null, + private ?TranslatorInterface $translator = null, + ) { $this->choiceListFactory = $choiceListFactory ?? new CachingFactoryDecorator( new PropertyAccessDecorator( new DefaultChoiceListFactory() ) ); - $this->translator = $translator; } public function buildForm(FormBuilderInterface $builder, array $options): void From 7b9c1292dbcd0f47e741fc4bb7c6e95a930458d5 Mon Sep 17 00:00:00 2001 From: "Alexander M. Turek" Date: Fri, 26 Jul 2024 13:12:13 +0200 Subject: [PATCH 174/208] [Form] Deprecate VersionAwareTest trait --- CHANGELOG.md | 5 +++++ Tests/Extension/Core/Type/BaseTypeTestCase.php | 16 ---------------- Tests/VersionAwareTest.php | 8 ++++++++ 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0420af3413..631041da40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +7.2 +--- + + * Deprecate the `VersionAwareTest` trait, use feature detection instead + 7.1 --- diff --git a/Tests/Extension/Core/Type/BaseTypeTestCase.php b/Tests/Extension/Core/Type/BaseTypeTestCase.php index 5238e2fd88..14b602a4b4 100644 --- a/Tests/Extension/Core/Type/BaseTypeTestCase.php +++ b/Tests/Extension/Core/Type/BaseTypeTestCase.php @@ -114,8 +114,6 @@ public function testDefaultTranslationDomain() public function testPassLabelTranslationParametersToView() { - $this->requiresFeatureSet(403); - $view = $this->factory->create($this->getTestedType(), null, array_merge($this->getTestOptions(), [ 'label_translation_parameters' => ['%param%' => 'value'], ])) @@ -126,8 +124,6 @@ public function testPassLabelTranslationParametersToView() public function testPassAttrTranslationParametersToView() { - $this->requiresFeatureSet(403); - $view = $this->factory->create($this->getTestedType(), null, array_merge($this->getTestOptions(), [ 'attr_translation_parameters' => ['%param%' => 'value'], ])) @@ -138,8 +134,6 @@ public function testPassAttrTranslationParametersToView() public function testInheritLabelTranslationParametersFromParent() { - $this->requiresFeatureSet(403); - $view = $this->factory ->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE, null, [ 'label_translation_parameters' => ['%param%' => 'value'], @@ -153,8 +147,6 @@ public function testInheritLabelTranslationParametersFromParent() public function testInheritAttrTranslationParametersFromParent() { - $this->requiresFeatureSet(403); - $view = $this->factory ->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE, null, [ 'attr_translation_parameters' => ['%param%' => 'value'], @@ -168,8 +160,6 @@ public function testInheritAttrTranslationParametersFromParent() public function testPreferOwnLabelTranslationParameters() { - $this->requiresFeatureSet(403); - $view = $this->factory ->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE, null, [ 'label_translation_parameters' => ['%parent_param%' => 'parent_value', '%override_param%' => 'parent_override_value'], @@ -185,8 +175,6 @@ public function testPreferOwnLabelTranslationParameters() public function testPreferOwnAttrTranslationParameters() { - $this->requiresFeatureSet(403); - $view = $this->factory ->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE, null, [ 'attr_translation_parameters' => ['%parent_param%' => 'parent_value', '%override_param%' => 'parent_override_value'], @@ -202,8 +190,6 @@ public function testPreferOwnAttrTranslationParameters() public function testDefaultLabelTranslationParameters() { - $this->requiresFeatureSet(403); - $view = $this->factory->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE) ->add('child', $this->getTestedType(), $this->getTestOptions()) ->getForm() @@ -214,8 +200,6 @@ public function testDefaultLabelTranslationParameters() public function testDefaultAttrTranslationParameters() { - $this->requiresFeatureSet(403); - $view = $this->factory->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE) ->add('child', $this->getTestedType(), $this->getTestOptions()) ->getForm() diff --git a/Tests/VersionAwareTest.php b/Tests/VersionAwareTest.php index 90e0d10af6..530c174739 100644 --- a/Tests/VersionAwareTest.php +++ b/Tests/VersionAwareTest.php @@ -11,12 +11,20 @@ namespace Symfony\Component\Form\Tests; +/** + * @deprecated since Symfony 7.2, use feature detection instead. + */ trait VersionAwareTest { protected static int $supportedFeatureSetVersion = 404; + /** + * @deprecated since Symfony 7.2, use feature detection instead. + */ protected function requiresFeatureSet(int $requiredFeatureSetVersion) { + trigger_deprecation('symfony/form', '7.2', 'The "%s" trait is deprecated, use feature detection instead.', VersionAwareTest::class); + if ($requiredFeatureSetVersion > static::$supportedFeatureSetVersion) { $this->markTestSkipped(\sprintf('Test requires features from symfony/form %.2f but only version %.2f is supported.', $requiredFeatureSetVersion / 100, static::$supportedFeatureSetVersion / 100)); } From b2a3f779d67f476600f6e45524fb9d0e03bf5aac Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Wed, 31 Jul 2024 16:13:26 +0200 Subject: [PATCH 175/208] Remove unused code and unnecessary `else` branches --- .../Core/DataTransformer/DateIntervalToArrayTransformer.php | 3 +-- .../DataTransformer/NumberToLocalizedStringTransformer.php | 4 +--- .../DataTransformer/PercentToLocalizedStringTransformer.php | 4 +--- Extension/Core/Type/ChoiceType.php | 4 ++-- 4 files changed, 5 insertions(+), 10 deletions(-) diff --git a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php index 0475b55bfd..18679a9103 100644 --- a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php @@ -93,9 +93,8 @@ public function transform(mixed $dateInterval): array } } $result['invert'] = '-' === $result['invert']; - $result = array_intersect_key($result, array_flip($this->fields)); - return $result; + return array_intersect_key($result, array_flip($this->fields)); } /** diff --git a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index 2a6d146f90..dc108de796 100644 --- a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -64,9 +64,7 @@ public function transform(mixed $value): string } // Convert non-breaking and narrow non-breaking spaces to normal ones - $value = str_replace(["\xc2\xa0", "\xe2\x80\xaf"], ' ', $value); - - return $value; + return str_replace(["\xc2\xa0", "\xe2\x80\xaf"], ' ', $value); } /** diff --git a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php index 8ae5e4c968..3b103b49b3 100644 --- a/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/PercentToLocalizedStringTransformer.php @@ -210,8 +210,6 @@ private function round(int|float $number): int|float \NumberFormatter::ROUND_HALFDOWN => round($number, 0, \PHP_ROUND_HALF_DOWN), }; - $number = 1 === $roundingCoef ? (int) $number : $number / $roundingCoef; - - return $number; + return 1 === $roundingCoef ? (int) $number : $number / $roundingCoef; } } diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 0042d75805..d0a1b6e06f 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -141,9 +141,9 @@ public function buildForm(FormBuilderInterface $builder, array $options): void $knownValues[$child->getName()] = $value; unset($unknownValues[$value]); continue; - } else { - $knownValues[$child->getName()] = null; } + + $knownValues[$child->getName()] = null; } } else { foreach ($choiceList->getChoicesForValues($data) as $key => $choice) { From 669faf533c2e714e769f3c9dfdc175237e5fae6d Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Mon, 5 Aug 2024 09:12:25 +0200 Subject: [PATCH 176/208] Fix multiple CS errors --- Tests/Extension/DataCollector/FormDataExtractorTest.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Tests/Extension/DataCollector/FormDataExtractorTest.php b/Tests/Extension/DataCollector/FormDataExtractorTest.php index b8a1fee374..29f9359df8 100644 --- a/Tests/Extension/DataCollector/FormDataExtractorTest.php +++ b/Tests/Extension/DataCollector/FormDataExtractorTest.php @@ -362,8 +362,7 @@ public function testExtractSubmittedDataStoresErrorCause() ] EODUMP; } - $this->assertDumpMatchesFormat($expectedFormat - , + $this->assertDumpMatchesFormat($expectedFormat, $this->dataExtractor->extractSubmittedData($form) ); } From 1824d39c04d9ea22231c23a5955c95b1c96bd592 Mon Sep 17 00:00:00 2001 From: Roy de Vos Burchart Date: Thu, 1 Aug 2024 17:21:17 +0200 Subject: [PATCH 177/208] Code style change in `@PER-CS2.0` affecting `@Symfony` (parentheses for anonymous classes) --- Tests/AbstractRequestHandlerTestCase.php | 2 +- Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/AbstractRequestHandlerTestCase.php b/Tests/AbstractRequestHandlerTestCase.php index d050edb410..f80efffb71 100644 --- a/Tests/AbstractRequestHandlerTestCase.php +++ b/Tests/AbstractRequestHandlerTestCase.php @@ -39,7 +39,7 @@ abstract class AbstractRequestHandlerTestCase extends TestCase protected function setUp(): void { - $this->serverParams = new class() extends ServerParams { + $this->serverParams = new class extends ServerParams { public ?int $contentLength = null; public string $postMaxSize = ''; diff --git a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index f82fdc2f99..2b1b239e58 100644 --- a/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -728,7 +728,7 @@ public function testPassTranslatableMessageAsLabelDoesntCastItToString() public function testPassTranslatableInterfaceAsLabelDoesntCastItToString() { - $message = new class() implements TranslatableInterface { + $message = new class implements TranslatableInterface { public function trans(TranslatorInterface $translator, ?string $locale = null): string { return 'my_message'; From 6a4471250f8899f86b6202a11fb4a3eb1cce9949 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Mon, 29 Jul 2024 09:33:48 +0200 Subject: [PATCH 178/208] Remove useless code --- Extension/Core/Type/TimeType.php | 1 - 1 file changed, 1 deletion(-) diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index ad559760d1..d799210665 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -60,7 +60,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void if ('single_text' === $options['widget']) { $builder->addEventListener(FormEvents::PRE_SUBMIT, static function (FormEvent $e) use ($options) { - /** @var PreSubmitEvent $event */ $data = $e->getData(); if ($data && preg_match('/^(?P\d{2}):(?P\d{2})(?::(?P\d{2})(?:\.\d+)?)?$/', $data, $matches)) { if ($options['with_seconds']) { From e6f725489b96dde6b8d51702574186aa6152cacf Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Fri, 9 Aug 2024 10:02:21 +0200 Subject: [PATCH 179/208] [Form] Replace class-string by `::class` for `BaseTypeTestCase::TESTED_TYPE` --- Tests/Extension/Core/Type/BirthdayTypeTest.php | 3 ++- Tests/Extension/Core/Type/ButtonTypeTest.php | 3 ++- Tests/Extension/Core/Type/CheckboxTypeTest.php | 3 ++- Tests/Extension/Core/Type/ChoiceTypeTest.php | 3 ++- Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php | 3 ++- Tests/Extension/Core/Type/CollectionTypeTest.php | 3 ++- Tests/Extension/Core/Type/CountryTypeTest.php | 3 ++- Tests/Extension/Core/Type/CurrencyTypeTest.php | 3 ++- Tests/Extension/Core/Type/DateTimeTypeTest.php | 3 ++- Tests/Extension/Core/Type/DateTypeTest.php | 3 ++- Tests/Extension/Core/Type/FileTypeTest.php | 3 ++- Tests/Extension/Core/Type/FormTypeTest.php | 2 +- Tests/Extension/Core/Type/IntegerTypeTest.php | 3 ++- Tests/Extension/Core/Type/LanguageTypeTest.php | 3 ++- Tests/Extension/Core/Type/LocaleTypeTest.php | 3 ++- Tests/Extension/Core/Type/MoneyTypeTest.php | 3 ++- Tests/Extension/Core/Type/NumberTypeTest.php | 3 ++- Tests/Extension/Core/Type/PasswordTypeTest.php | 4 +++- Tests/Extension/Core/Type/RepeatedTypeTest.php | 3 ++- Tests/Extension/Core/Type/SubmitTypeTest.php | 3 ++- Tests/Extension/Core/Type/TextTypeTest.php | 4 +++- Tests/Extension/Core/Type/TimeTypeTest.php | 3 ++- Tests/Extension/Core/Type/TimezoneTypeTest.php | 3 ++- Tests/Extension/Core/Type/UrlTypeTest.php | 3 ++- Tests/Extension/Core/Type/WeekTypeTest.php | 3 ++- 25 files changed, 51 insertions(+), 25 deletions(-) diff --git a/Tests/Extension/Core/Type/BirthdayTypeTest.php b/Tests/Extension/Core/Type/BirthdayTypeTest.php index 0484571411..53e5c959ce 100644 --- a/Tests/Extension/Core/Type/BirthdayTypeTest.php +++ b/Tests/Extension/Core/Type/BirthdayTypeTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Extension\Core\Type\BirthdayType; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; /** @@ -18,7 +19,7 @@ */ class BirthdayTypeTest extends DateTypeTest { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\BirthdayType'; + public const TESTED_TYPE = BirthdayType::class; public function testSetInvalidYearsOption() { diff --git a/Tests/Extension/Core/Type/ButtonTypeTest.php b/Tests/Extension/Core/Type/ButtonTypeTest.php index 0125631c58..4825015d27 100644 --- a/Tests/Extension/Core/Type/ButtonTypeTest.php +++ b/Tests/Extension/Core/Type/ButtonTypeTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Form\Button; use Symfony\Component\Form\Exception\BadMethodCallException; use Symfony\Component\Form\Exception\LogicException; +use Symfony\Component\Form\Extension\Core\Type\ButtonType; use Symfony\Component\Form\Extension\Core\Type\FormType; /** @@ -21,7 +22,7 @@ */ class ButtonTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\ButtonType'; + public const TESTED_TYPE = ButtonType::class; public function testCreateButtonInstances() { diff --git a/Tests/Extension/Core/Type/CheckboxTypeTest.php b/Tests/Extension/Core/Type/CheckboxTypeTest.php index 62312e28dc..69fd0fd601 100644 --- a/Tests/Extension/Core/Type/CheckboxTypeTest.php +++ b/Tests/Extension/Core/Type/CheckboxTypeTest.php @@ -12,11 +12,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\CallbackTransformer; +use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class CheckboxTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\CheckboxType'; + public const TESTED_TYPE = CheckboxType::class; public function testDataIsFalseByDefault() { diff --git a/Tests/Extension/Core/Type/ChoiceTypeTest.php b/Tests/Extension/Core/Type/ChoiceTypeTest.php index c4f18734f8..948d682fc9 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -15,12 +15,13 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView; use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\Exception\TransformationFailedException; +use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\FormInterface; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class ChoiceTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\ChoiceType'; + public const TESTED_TYPE = ChoiceType::class; private array $choices = [ 'Bernhard' => 'a', diff --git a/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php b/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php index af58e2ecfa..f60c6664c6 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTranslationTest.php @@ -12,12 +12,13 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\Extension\Core\CoreExtension; +use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Test\TypeTestCase; use Symfony\Contracts\Translation\TranslatorInterface; class ChoiceTypeTranslationTest extends TypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\ChoiceType'; + public const TESTED_TYPE = ChoiceType::class; private array $choices = [ 'Bernhard' => 'a', diff --git a/Tests/Extension/Core/Type/CollectionTypeTest.php b/Tests/Extension/Core/Type/CollectionTypeTest.php index 79134db993..95e1d9ca70 100644 --- a/Tests/Extension/Core/Type/CollectionTypeTest.php +++ b/Tests/Extension/Core/Type/CollectionTypeTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; +use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\Form; use Symfony\Component\Form\Tests\Fixtures\Author; use Symfony\Component\Form\Tests\Fixtures\AuthorType; @@ -20,7 +21,7 @@ class CollectionTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\CollectionType'; + public const TESTED_TYPE = CollectionType::class; public function testContainsNoChildByDefault() { diff --git a/Tests/Extension/Core/Type/CountryTypeTest.php b/Tests/Extension/Core/Type/CountryTypeTest.php index 57146e1ecf..44073ef7b9 100644 --- a/Tests/Extension/Core/Type/CountryTypeTest.php +++ b/Tests/Extension/Core/Type/CountryTypeTest.php @@ -12,11 +12,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\ChoiceList\View\ChoiceView; +use Symfony\Component\Form\Extension\Core\Type\CountryType; use Symfony\Component\Intl\Util\IntlTestHelper; class CountryTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\CountryType'; + public const TESTED_TYPE = CountryType::class; protected function setUp(): void { diff --git a/Tests/Extension/Core/Type/CurrencyTypeTest.php b/Tests/Extension/Core/Type/CurrencyTypeTest.php index 51aaf6b372..3e8a53dfb2 100644 --- a/Tests/Extension/Core/Type/CurrencyTypeTest.php +++ b/Tests/Extension/Core/Type/CurrencyTypeTest.php @@ -12,11 +12,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\ChoiceList\View\ChoiceView; +use Symfony\Component\Form\Extension\Core\Type\CurrencyType; use Symfony\Component\Intl\Util\IntlTestHelper; class CurrencyTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\CurrencyType'; + public const TESTED_TYPE = CurrencyType::class; protected function setUp(): void { diff --git a/Tests/Extension/Core/Type/DateTimeTypeTest.php b/Tests/Extension/Core/Type/DateTimeTypeTest.php index a402a70f9f..5067bb05e7 100644 --- a/Tests/Extension/Core/Type/DateTimeTypeTest.php +++ b/Tests/Extension/Core/Type/DateTimeTypeTest.php @@ -12,12 +12,13 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\Exception\LogicException; +use Symfony\Component\Form\Extension\Core\Type\DateTimeType; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; class DateTimeTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\DateTimeType'; + public const TESTED_TYPE = DateTimeType::class; private string $defaultLocale; diff --git a/Tests/Extension/Core/Type/DateTypeTest.php b/Tests/Extension/Core/Type/DateTypeTest.php index dfbae93309..4b6a302f35 100644 --- a/Tests/Extension/Core/Type/DateTypeTest.php +++ b/Tests/Extension/Core/Type/DateTypeTest.php @@ -13,6 +13,7 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\Exception\LogicException; +use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; use Symfony\Component\Intl\Intl; @@ -21,7 +22,7 @@ class DateTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\DateType'; + public const TESTED_TYPE = DateType::class; private string $defaultTimezone; private string $defaultLocale; diff --git a/Tests/Extension/Core/Type/FileTypeTest.php b/Tests/Extension/Core/Type/FileTypeTest.php index 9c3a8efd0a..85907b6959 100644 --- a/Tests/Extension/Core/Type/FileTypeTest.php +++ b/Tests/Extension/Core/Type/FileTypeTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\Extension\Core\CoreExtension; +use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler; use Symfony\Component\Form\NativeRequestHandler; use Symfony\Component\Form\RequestHandlerInterface; @@ -21,7 +22,7 @@ class FileTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\FileType'; + public const TESTED_TYPE = FileType::class; protected function getExtensions(): array { diff --git a/Tests/Extension/Core/Type/FormTypeTest.php b/Tests/Extension/Core/Type/FormTypeTest.php index fe838885ed..fe19f3b120 100644 --- a/Tests/Extension/Core/Type/FormTypeTest.php +++ b/Tests/Extension/Core/Type/FormTypeTest.php @@ -64,7 +64,7 @@ public function setReferenceCopy($reference) class FormTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\FormType'; + public const TESTED_TYPE = FormType::class; public function testCreateFormInstances() { diff --git a/Tests/Extension/Core/Type/IntegerTypeTest.php b/Tests/Extension/Core/Type/IntegerTypeTest.php index 1e143b342f..ff33c17c63 100644 --- a/Tests/Extension/Core/Type/IntegerTypeTest.php +++ b/Tests/Extension/Core/Type/IntegerTypeTest.php @@ -11,11 +11,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Intl\Util\IntlTestHelper; class IntegerTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\IntegerType'; + public const TESTED_TYPE = IntegerType::class; private string $previousLocale; diff --git a/Tests/Extension/Core/Type/LanguageTypeTest.php b/Tests/Extension/Core/Type/LanguageTypeTest.php index e214e0afd4..8eb085112f 100644 --- a/Tests/Extension/Core/Type/LanguageTypeTest.php +++ b/Tests/Extension/Core/Type/LanguageTypeTest.php @@ -13,11 +13,12 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\Exception\LogicException; +use Symfony\Component\Form\Extension\Core\Type\LanguageType; use Symfony\Component\Intl\Util\IntlTestHelper; class LanguageTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\LanguageType'; + public const TESTED_TYPE = LanguageType::class; protected function setUp(): void { diff --git a/Tests/Extension/Core/Type/LocaleTypeTest.php b/Tests/Extension/Core/Type/LocaleTypeTest.php index 8486b6656b..a2a820b390 100644 --- a/Tests/Extension/Core/Type/LocaleTypeTest.php +++ b/Tests/Extension/Core/Type/LocaleTypeTest.php @@ -12,11 +12,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\ChoiceList\View\ChoiceView; +use Symfony\Component\Form\Extension\Core\Type\LocaleType; use Symfony\Component\Intl\Util\IntlTestHelper; class LocaleTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\LocaleType'; + public const TESTED_TYPE = LocaleType::class; protected function setUp(): void { diff --git a/Tests/Extension/Core/Type/MoneyTypeTest.php b/Tests/Extension/Core/Type/MoneyTypeTest.php index 58e33af19b..302f09c22a 100644 --- a/Tests/Extension/Core/Type/MoneyTypeTest.php +++ b/Tests/Extension/Core/Type/MoneyTypeTest.php @@ -11,11 +11,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Extension\Core\Type\MoneyType; use Symfony\Component\Intl\Util\IntlTestHelper; class MoneyTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\MoneyType'; + public const TESTED_TYPE = MoneyType::class; private string $defaultLocale; diff --git a/Tests/Extension/Core/Type/NumberTypeTest.php b/Tests/Extension/Core/Type/NumberTypeTest.php index 9efe052219..e744563d1a 100644 --- a/Tests/Extension/Core/Type/NumberTypeTest.php +++ b/Tests/Extension/Core/Type/NumberTypeTest.php @@ -13,11 +13,12 @@ use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Form\Exception\TransformationFailedException; +use Symfony\Component\Form\Extension\Core\Type\NumberType; use Symfony\Component\Intl\Util\IntlTestHelper; class NumberTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\NumberType'; + public const TESTED_TYPE = NumberType::class; private string $defaultLocale; diff --git a/Tests/Extension/Core/Type/PasswordTypeTest.php b/Tests/Extension/Core/Type/PasswordTypeTest.php index 8d428a26a5..945437bcbd 100644 --- a/Tests/Extension/Core/Type/PasswordTypeTest.php +++ b/Tests/Extension/Core/Type/PasswordTypeTest.php @@ -11,9 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Extension\Core\Type\PasswordType; + class PasswordTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\PasswordType'; + public const TESTED_TYPE = PasswordType::class; public function testEmptyIfNotSubmitted() { diff --git a/Tests/Extension/Core/Type/RepeatedTypeTest.php b/Tests/Extension/Core/Type/RepeatedTypeTest.php index 06b9151fbe..62d1019009 100644 --- a/Tests/Extension/Core/Type/RepeatedTypeTest.php +++ b/Tests/Extension/Core/Type/RepeatedTypeTest.php @@ -11,13 +11,14 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Extension\Core\Type\RepeatedType; use Symfony\Component\Form\Form; use Symfony\Component\Form\Tests\Fixtures\NotMappedType; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class RepeatedTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\RepeatedType'; + public const TESTED_TYPE = RepeatedType::class; protected Form $form; diff --git a/Tests/Extension/Core/Type/SubmitTypeTest.php b/Tests/Extension/Core/Type/SubmitTypeTest.php index 8a16175d76..af5ab8400b 100644 --- a/Tests/Extension/Core/Type/SubmitTypeTest.php +++ b/Tests/Extension/Core/Type/SubmitTypeTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\SubmitButton; /** @@ -18,7 +19,7 @@ */ class SubmitTypeTest extends ButtonTypeTest { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\SubmitType'; + public const TESTED_TYPE = SubmitType::class; public function testCreateSubmitButtonInstances() { diff --git a/Tests/Extension/Core/Type/TextTypeTest.php b/Tests/Extension/Core/Type/TextTypeTest.php index a28dfa9afa..4832151684 100644 --- a/Tests/Extension/Core/Type/TextTypeTest.php +++ b/Tests/Extension/Core/Type/TextTypeTest.php @@ -11,9 +11,11 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Extension\Core\Type\TextType; + class TextTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\TextType'; + public const TESTED_TYPE = TextType::class; public function testSubmitNull($expected = null, $norm = null, $view = null) { diff --git a/Tests/Extension/Core/Type/TimeTypeTest.php b/Tests/Extension/Core/Type/TimeTypeTest.php index 155657038f..8a2baf1b4c 100644 --- a/Tests/Extension/Core/Type/TimeTypeTest.php +++ b/Tests/Extension/Core/Type/TimeTypeTest.php @@ -14,13 +14,14 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\Exception\InvalidConfigurationException; use Symfony\Component\Form\Exception\LogicException; +use Symfony\Component\Form\Extension\Core\Type\TimeType; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormInterface; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class TimeTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\TimeType'; + public const TESTED_TYPE = TimeType::class; public function testSubmitDateTime() { diff --git a/Tests/Extension/Core/Type/TimezoneTypeTest.php b/Tests/Extension/Core/Type/TimezoneTypeTest.php index 9966b40438..4f23439746 100644 --- a/Tests/Extension/Core/Type/TimezoneTypeTest.php +++ b/Tests/Extension/Core/Type/TimezoneTypeTest.php @@ -13,11 +13,12 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\Exception\LogicException; +use Symfony\Component\Form\Extension\Core\Type\TimezoneType; use Symfony\Component\Intl\Util\IntlTestHelper; class TimezoneTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\TimezoneType'; + public const TESTED_TYPE = TimezoneType::class; public function testTimezonesAreSelectable() { diff --git a/Tests/Extension/Core/Type/UrlTypeTest.php b/Tests/Extension/Core/Type/UrlTypeTest.php index 243d15297c..a0d335647d 100644 --- a/Tests/Extension/Core/Type/UrlTypeTest.php +++ b/Tests/Extension/Core/Type/UrlTypeTest.php @@ -12,13 +12,14 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Bridge\PhpUnit\ExpectUserDeprecationMessageTrait; +use Symfony\Component\Form\Extension\Core\Type\UrlType; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; class UrlTypeTest extends TextTypeTest { use ExpectUserDeprecationMessageTrait; - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\UrlType'; + public const TESTED_TYPE = UrlType::class; /** * @group legacy diff --git a/Tests/Extension/Core/Type/WeekTypeTest.php b/Tests/Extension/Core/Type/WeekTypeTest.php index a69b96a38a..b4d58fd95c 100644 --- a/Tests/Extension/Core/Type/WeekTypeTest.php +++ b/Tests/Extension/Core/Type/WeekTypeTest.php @@ -11,11 +11,12 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; +use Symfony\Component\Form\Extension\Core\Type\WeekType; use Symfony\Component\Form\FormError; class WeekTypeTest extends BaseTypeTestCase { - public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\WeekType'; + public const TESTED_TYPE = WeekType::class; public function testSubmitArray() { From ad5e8613911580583e554c3b1a79a63e1cefebfc Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Fri, 9 Aug 2024 09:46:47 +0200 Subject: [PATCH 180/208] [Form] Add support for the `calendar` option in `DateType` --- CHANGELOG.md | 1 + .../DateTimeToLocalizedStringTransformer.php | 14 ++--- Extension/Core/Type/DateType.php | 6 ++- ...teTimeToLocalizedStringTransformerTest.php | 54 +++++++++++++++++++ Tests/Extension/Core/Type/DateTypeTest.php | 34 ++++++++++++ 5 files changed, 101 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 631041da40..6ad9ab93f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ CHANGELOG --- * Deprecate the `VersionAwareTest` trait, use feature detection instead + * Add support for the `calendar` option in `DateType` 7.1 --- diff --git a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php index a93803cd8b..5e93d289d2 100644 --- a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php @@ -30,12 +30,12 @@ class DateTimeToLocalizedStringTransformer extends BaseDateTimeTransformer /** * @see BaseDateTimeTransformer::formats for available format options * - * @param string|null $inputTimezone The name of the input timezone - * @param string|null $outputTimezone The name of the output timezone - * @param int|null $dateFormat The date format - * @param int|null $timeFormat The time format - * @param int $calendar One of the \IntlDateFormatter calendar constants - * @param string|null $pattern A pattern to pass to \IntlDateFormatter + * @param string|null $inputTimezone The name of the input timezone + * @param string|null $outputTimezone The name of the output timezone + * @param int|null $dateFormat The date format + * @param int|null $timeFormat The time format + * @param int|\IntlCalendar $calendar One of the \IntlDateFormatter calendar constants or an \IntlCalendar instance + * @param string|null $pattern A pattern to pass to \IntlDateFormatter * * @throws UnexpectedTypeException If a format is not supported or if a timezone is not a string */ @@ -44,7 +44,7 @@ public function __construct( ?string $outputTimezone = null, ?int $dateFormat = null, ?int $timeFormat = null, - private int $calendar = \IntlDateFormatter::GREGORIAN, + private int|\IntlCalendar $calendar = \IntlDateFormatter::GREGORIAN, private ?string $pattern = null, ) { parent::__construct($inputTimezone, $outputTimezone); diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index 773a51cbdd..d30946d7c9 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -49,7 +49,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void { $dateFormat = \is_int($options['format']) ? $options['format'] : self::DEFAULT_FORMAT; $timeFormat = \IntlDateFormatter::NONE; - $calendar = \IntlDateFormatter::GREGORIAN; + $calendar = $options['calendar'] ?? \IntlDateFormatter::GREGORIAN; $pattern = \is_string($options['format']) ? $options['format'] : ''; if (!\in_array($dateFormat, self::ACCEPTED_FORMATS, true)) { @@ -281,6 +281,7 @@ public function configureOptions(OptionsResolver $resolver): void 'format' => $format, 'model_timezone' => null, 'view_timezone' => null, + 'calendar' => null, 'placeholder' => $placeholderDefault, 'html5' => true, // Don't modify \DateTime classes by reference, we treat @@ -320,6 +321,9 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('months', 'array'); $resolver->setAllowedTypes('days', 'array'); $resolver->setAllowedTypes('input_format', 'string'); + $resolver->setAllowedTypes('calendar', ['null', \IntlCalendar::class]); + + $resolver->setInfo('calendar', 'The calendar to use for formatting and parsing the date. The value should be one of the \IntlDateFormatter calendar constants or an instance of the \IntlCalendar to use.'); $resolver->setNormalizer('html5', static function (Options $options, $html5) { if ($html5 && 'single_text' === $options['widget'] && self::HTML5_FORMAT !== $options['format']) { diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php index c7918ae8b1..0cf8b22f6c 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php @@ -392,6 +392,60 @@ public function testReverseTransformWrapsIntlErrorsWithExceptionsAndErrorLevel() } } + public function testTransformDateTimeWithCustomCalendar() + { + $dateTime = new \DateTimeImmutable('2024-03-31'); + + $weekBeginsOnSunday = \IntlCalendar::createInstance(); + $weekBeginsOnSunday->setFirstDayOfWeek(\IntlCalendar::DOW_SUNDAY); + + $this->assertSame( + '2024-03-31 2024w14', + (new DateTimeToLocalizedStringTransformer(calendar: $weekBeginsOnSunday, pattern: "y-MM-dd y'w'w"))->transform($dateTime), + ); + + $weekBeginsOnMonday = \IntlCalendar::createInstance(); + $weekBeginsOnMonday->setFirstDayOfWeek(\IntlCalendar::DOW_MONDAY); + + $this->assertSame( + '2024-03-31 2024w13', + (new DateTimeToLocalizedStringTransformer(calendar: $weekBeginsOnMonday, pattern: "y-MM-dd y'w'w"))->transform($dateTime), + ); + } + + public function testReverseTransformDateTimeWithCustomCalendar() + { + $weekBeginsOnSunday = \IntlCalendar::createInstance(); + $weekBeginsOnSunday->setFirstDayOfWeek(\IntlCalendar::DOW_SUNDAY); + + $this->assertSame( + '2024-03-31', + (new DateTimeToLocalizedStringTransformer(calendar: $weekBeginsOnSunday, pattern: "y-MM-dd y'w'w")) + ->reverseTransform('2024-03-31 2024w14') + ->format('Y-m-d'), + ); + + $weekBeginsOnMonday = \IntlCalendar::createInstance(); + $weekBeginsOnMonday->setFirstDayOfWeek(\IntlCalendar::DOW_MONDAY); + + $this->assertSame( + '2024-03-31', + (new DateTimeToLocalizedStringTransformer(calendar: $weekBeginsOnMonday, pattern: "y-MM-dd y'w'w")) + ->reverseTransform('2024-03-31 2024w13') + ->format('Y-m-d'), + ); + } + + public function testDefaultCalendarIsGregorian() + { + $now = new \DateTimeImmutable(); + + $this->assertSame( + (new DateTimeToLocalizedStringTransformer(calendar: \IntlDateFormatter::GREGORIAN, pattern: "y-MM-dd y'w'w"))->transform($now), + (new DateTimeToLocalizedStringTransformer(pattern: "y-MM-dd y'w'w"))->transform($now), + ); + } + protected function createDateTimeTransformer(?string $inputTimezone = null, ?string $outputTimezone = null): BaseDateTimeTransformer { return new DateTimeToLocalizedStringTransformer($inputTimezone, $outputTimezone); diff --git a/Tests/Extension/Core/Type/DateTypeTest.php b/Tests/Extension/Core/Type/DateTypeTest.php index dfbae93309..61787512ae 100644 --- a/Tests/Extension/Core/Type/DateTypeTest.php +++ b/Tests/Extension/Core/Type/DateTypeTest.php @@ -1156,6 +1156,40 @@ public function testDateTimeImmutableInputTimezoneNotMatchingModelTimezone() ]); } + public function testSubmitWithCustomCalendarOption() + { + // Creates a new form using the "roc" (Republic Of China) calendar. This calendar starts in 1912, the year 2024 in + // the Gregorian calendar is the year 113 in the "roc" calendar. + $form = $this->factory->create(static::TESTED_TYPE, options: [ + 'format' => 'y-MM-dd', + 'html5' => false, + 'input' => 'array', + 'calendar' => \IntlCalendar::createInstance(locale: 'zh_TW@calendar=roc'), + ]); + $form->submit('113-03-31'); + + $this->assertSame('2024', $form->getData()['year'], 'The year should be converted to the default locale (en)'); + $this->assertSame('31', $form->getData()['day']); + $this->assertSame('3', $form->getData()['month']); + + $this->assertSame('113-03-31', $form->getViewData()); + } + + public function testSetDataWithCustomCalendarOption() + { + // Creates a new form using the "roc" (Republic Of China) calendar. This calendar starts in 1912, the year 2024 in + // the Gregorian calendar is the year 113 in the "roc" calendar. + $form = $this->factory->create(static::TESTED_TYPE, options: [ + 'format' => 'y-MM-dd', + 'html5' => false, + 'input' => 'array', + 'calendar' => \IntlCalendar::createInstance(locale: 'zh_TW@calendar=roc'), + ]); + $form->setData(['year' => '2024', 'month' => '3', 'day' => '31']); + + $this->assertSame('113-03-31', $form->getViewData()); + } + protected function getTestOptions(): array { return ['widget' => 'choice']; From a3ffc5a7d21538b4ac371d45d2a7a6a0761c1f7b Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Thu, 22 Aug 2024 09:26:39 +0200 Subject: [PATCH 181/208] [Form] Fix info for the `calendar` option of the `DateType` form type --- Extension/Core/Type/DateType.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index d30946d7c9..41dcf570c0 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -323,7 +323,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('input_format', 'string'); $resolver->setAllowedTypes('calendar', ['null', \IntlCalendar::class]); - $resolver->setInfo('calendar', 'The calendar to use for formatting and parsing the date. The value should be one of the \IntlDateFormatter calendar constants or an instance of the \IntlCalendar to use.'); + $resolver->setInfo('calendar', 'The calendar to use for formatting and parsing the date. The value should be an instance of \IntlCalendar. By default, the Gregorian calendar with the default locale is used.'); $resolver->setNormalizer('html5', static function (Options $options, $html5) { if ($html5 && 'single_text' === $options['widget'] && self::HTML5_FORMAT !== $options['format']) { From 7168ea22c680b88305c22183a5278cb07039b786 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Thu, 22 Aug 2024 10:42:25 +0200 Subject: [PATCH 182/208] [Form] Remove stalled PHP bug mentions --- .../DateTimeToLocalizedStringTransformer.php | 13 +++++-------- Extension/Core/Type/DateType.php | 8 +------- .../DateTimeToLocalizedStringTransformerTest.php | 9 +++++++++ 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php index 5e93d289d2..426c4bf89d 100644 --- a/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformer.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Extension\Core\DataTransformer; +use Symfony\Component\Form\Exception\InvalidArgumentException; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Exception\UnexpectedTypeException; @@ -60,6 +61,10 @@ public function __construct( throw new UnexpectedTypeException($timeFormat, implode('", "', self::$formats)); } + if (\is_int($calendar) && !\in_array($calendar, [\IntlDateFormatter::GREGORIAN, \IntlDateFormatter::TRADITIONAL], true)) { + throw new InvalidArgumentException('The "calendar" option should be either an \IntlDateFormatter constant or an \IntlCalendar instance.'); + } + $this->dateFormat = $dateFormat; $this->timeFormat = $timeFormat; } @@ -157,8 +162,6 @@ public function reverseTransform(mixed $value): ?\DateTime * Returns a preconfigured IntlDateFormatter instance. * * @param bool $ignoreTimezone Use UTC regardless of the configured timezone - * - * @throws TransformationFailedException in case the date formatter cannot be constructed */ protected function getIntlDateFormatter(bool $ignoreTimezone = false): \IntlDateFormatter { @@ -170,12 +173,6 @@ protected function getIntlDateFormatter(bool $ignoreTimezone = false): \IntlDate $pattern = $this->pattern; $intlDateFormatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, $timezone, $calendar, $pattern ?? ''); - - // new \intlDateFormatter may return null instead of false in case of failure, see https://bugs.php.net/66323 - if (!$intlDateFormatter) { - throw new TransformationFailedException(intl_get_error_message(), intl_get_error_code()); - } - $intlDateFormatter->setLenient(false); return $intlDateFormatter; diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index 41dcf570c0..54f24b89a0 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -120,17 +120,11 @@ public function buildForm(FormBuilderInterface $builder, array $options): void \Locale::getDefault(), $dateFormat, $timeFormat, - // see https://bugs.php.net/66323 - class_exists(\IntlTimeZone::class, false) ? \IntlTimeZone::createDefault() : null, + null, $calendar, $pattern ); - // new \IntlDateFormatter may return null instead of false in case of failure, see https://bugs.php.net/66323 - if (!$formatter) { - throw new InvalidOptionsException(intl_get_error_message(), intl_get_error_code()); - } - $formatter->setLenient(false); if ('choice' === $options['widget']) { diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php index 0cf8b22f6c..a14e4a44eb 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer; +use Symfony\Component\Form\Exception\InvalidArgumentException; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToLocalizedStringTransformer; @@ -446,6 +447,14 @@ public function testDefaultCalendarIsGregorian() ); } + public function testInvalidCalendar() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The "calendar" option should be either an \IntlDateFormatter constant or an \IntlCalendar instance.'); + + new DateTimeToLocalizedStringTransformer(calendar: 123456); + } + protected function createDateTimeTransformer(?string $inputTimezone = null, ?string $outputTimezone = null): BaseDateTimeTransformer { return new DateTimeToLocalizedStringTransformer($inputTimezone, $outputTimezone); From 964d2ea563193b98618310b18d3a0374a20d7698 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Thu, 22 Aug 2024 13:58:26 +0200 Subject: [PATCH 183/208] skip tests requiring the intl extension if it's not installed --- Tests/Extension/Core/Type/DateTypeTest.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Tests/Extension/Core/Type/DateTypeTest.php b/Tests/Extension/Core/Type/DateTypeTest.php index f7f7d925c7..5f4f896b5d 100644 --- a/Tests/Extension/Core/Type/DateTypeTest.php +++ b/Tests/Extension/Core/Type/DateTypeTest.php @@ -1159,6 +1159,8 @@ public function testDateTimeImmutableInputTimezoneNotMatchingModelTimezone() public function testSubmitWithCustomCalendarOption() { + IntlTestHelper::requireFullIntl($this); + // Creates a new form using the "roc" (Republic Of China) calendar. This calendar starts in 1912, the year 2024 in // the Gregorian calendar is the year 113 in the "roc" calendar. $form = $this->factory->create(static::TESTED_TYPE, options: [ @@ -1178,6 +1180,8 @@ public function testSubmitWithCustomCalendarOption() public function testSetDataWithCustomCalendarOption() { + IntlTestHelper::requireFullIntl($this); + // Creates a new form using the "roc" (Republic Of China) calendar. This calendar starts in 1912, the year 2024 in // the Gregorian calendar is the year 113 in the "roc" calendar. $form = $this->factory->create(static::TESTED_TYPE, options: [ From 64b30ef5a6bb466d7bcc9e4b31d4e7f26b9b8432 Mon Sep 17 00:00:00 2001 From: Yonel Ceruto Date: Wed, 18 Oct 2023 17:16:44 -0400 Subject: [PATCH 184/208] add LazyChoiceLoader and choice_lazy option --- CHANGELOG.md | 1 + ChoiceList/Loader/LazyChoiceLoader.php | 54 +++++++++ Extension/Core/Type/ChoiceType.php | 19 +++ .../Loader/LazyChoiceLoaderTest.php | 50 ++++++++ Tests/Extension/Core/Type/ChoiceTypeTest.php | 108 ++++++++++++++++++ .../Descriptor/resolved_form_type_1.json | 1 + .../Descriptor/resolved_form_type_1.txt | 32 +++--- 7 files changed, 249 insertions(+), 16 deletions(-) create mode 100644 ChoiceList/Loader/LazyChoiceLoader.php create mode 100644 Tests/ChoiceList/Loader/LazyChoiceLoaderTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ad9ab93f1..1cef486963 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ CHANGELOG * Deprecate the `VersionAwareTest` trait, use feature detection instead * Add support for the `calendar` option in `DateType` + * Add `LazyChoiceLoader` and `choice_lazy` option in `ChoiceType` for loading and rendering choices on demand 7.1 --- diff --git a/ChoiceList/Loader/LazyChoiceLoader.php b/ChoiceList/Loader/LazyChoiceLoader.php new file mode 100644 index 0000000000..03451be365 --- /dev/null +++ b/ChoiceList/Loader/LazyChoiceLoader.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\ChoiceList\Loader; + +use Symfony\Component\Form\ChoiceList\ArrayChoiceList; +use Symfony\Component\Form\ChoiceList\ChoiceListInterface; + +/** + * A choice loader that loads its choices and values lazily, only when necessary. + * + * @author Yonel Ceruto + */ +class LazyChoiceLoader implements ChoiceLoaderInterface +{ + private ?ChoiceListInterface $choiceList = null; + + public function __construct( + private readonly ChoiceLoaderInterface $loader, + ) { + } + + public function loadChoiceList(?callable $value = null): ChoiceListInterface + { + return $this->choiceList ??= new ArrayChoiceList([], $value); + } + + public function loadChoicesForValues(array $values, ?callable $value = null): array + { + $choices = $this->loader->loadChoicesForValues($values, $value); + $this->choiceList = new ArrayChoiceList($choices, $value); + + return $choices; + } + + public function loadValuesForChoices(array $choices, ?callable $value = null): array + { + $values = $this->loader->loadValuesForChoices($choices, $value); + + if ($this->choiceList?->getValuesForChoices($choices) !== $values) { + $this->loadChoicesForValues($values, $value); + } + + return $values; + } +} diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index d0a1b6e06f..35a3175924 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -27,10 +27,12 @@ use Symfony\Component\Form\ChoiceList\Factory\DefaultChoiceListFactory; use Symfony\Component\Form\ChoiceList\Factory\PropertyAccessDecorator; use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface; +use Symfony\Component\Form\ChoiceList\Loader\LazyChoiceLoader; use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView; use Symfony\Component\Form\ChoiceList\View\ChoiceListView; use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\Event\PreSubmitEvent; +use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataMapper\CheckboxListMapper; use Symfony\Component\Form\Extension\Core\DataMapper\RadioListMapper; @@ -333,11 +335,24 @@ public function configureOptions(OptionsResolver $resolver): void return $choiceTranslationDomain; }; + $choiceLoaderNormalizer = static function (Options $options, ?ChoiceLoaderInterface $choiceLoader) { + if (!$options['choice_lazy']) { + return $choiceLoader; + } + + if (null === $choiceLoader) { + throw new LogicException('The "choice_lazy" option can only be used if the "choice_loader" option is set.'); + } + + return new LazyChoiceLoader($choiceLoader); + }; + $resolver->setDefaults([ 'multiple' => false, 'expanded' => false, 'choices' => [], 'choice_filter' => null, + 'choice_lazy' => false, 'choice_loader' => null, 'choice_label' => null, 'choice_name' => null, @@ -365,9 +380,11 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setNormalizer('placeholder', $placeholderNormalizer); $resolver->setNormalizer('choice_translation_domain', $choiceTranslationDomainNormalizer); + $resolver->setNormalizer('choice_loader', $choiceLoaderNormalizer); $resolver->setAllowedTypes('choices', ['null', 'array', \Traversable::class]); $resolver->setAllowedTypes('choice_translation_domain', ['null', 'bool', 'string']); + $resolver->setAllowedTypes('choice_lazy', 'bool'); $resolver->setAllowedTypes('choice_loader', ['null', ChoiceLoaderInterface::class, ChoiceLoader::class]); $resolver->setAllowedTypes('choice_filter', ['null', 'callable', 'string', PropertyPath::class, ChoiceFilter::class]); $resolver->setAllowedTypes('choice_label', ['null', 'bool', 'callable', 'string', PropertyPath::class, ChoiceLabel::class]); @@ -381,6 +398,8 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('separator_html', ['bool']); $resolver->setAllowedTypes('duplicate_preferred_choices', 'bool'); $resolver->setAllowedTypes('group_by', ['null', 'callable', 'string', PropertyPath::class, GroupBy::class]); + + $resolver->setInfo('choice_lazy', 'Load choices on demand. When set to true, only the selected choices are loaded and rendered.'); } public function getBlockPrefix(): string diff --git a/Tests/ChoiceList/Loader/LazyChoiceLoaderTest.php b/Tests/ChoiceList/Loader/LazyChoiceLoaderTest.php new file mode 100644 index 0000000000..0c1bcf3c22 --- /dev/null +++ b/Tests/ChoiceList/Loader/LazyChoiceLoaderTest.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Form\Tests\ChoiceList\Loader; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\Form\ChoiceList\Loader\LazyChoiceLoader; +use Symfony\Component\Form\Tests\Fixtures\ArrayChoiceLoader; + +class LazyChoiceLoaderTest extends TestCase +{ + private LazyChoiceLoader $loader; + + protected function setUp(): void + { + $this->loader = new LazyChoiceLoader(new ArrayChoiceLoader(['A', 'B', 'C'])); + } + + public function testInitialEmptyChoiceListLoading() + { + $this->assertSame([], $this->loader->loadChoiceList()->getChoices()); + } + + public function testOnDemandChoiceListAfterLoadingValuesForChoices() + { + $this->loader->loadValuesForChoices(['A']); + $this->assertSame(['A' => 'A'], $this->loader->loadChoiceList()->getChoices()); + } + + public function testOnDemandChoiceListAfterLoadingChoicesForValues() + { + $this->loader->loadChoicesForValues(['B']); + $this->assertSame(['B' => 'B'], $this->loader->loadChoiceList()->getChoices()); + } + + public function testOnDemandChoiceList() + { + $this->loader->loadValuesForChoices(['A']); + $this->loader->loadChoicesForValues(['B']); + $this->assertSame(['B' => 'B'], $this->loader->loadChoiceList()->getChoices()); + } +} diff --git a/Tests/Extension/Core/Type/ChoiceTypeTest.php b/Tests/Extension/Core/Type/ChoiceTypeTest.php index 948d682fc9..28810bbc7e 100644 --- a/Tests/Extension/Core/Type/ChoiceTypeTest.php +++ b/Tests/Extension/Core/Type/ChoiceTypeTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Form\ChoiceList\Loader\CallbackChoiceLoader; use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView; use Symfony\Component\Form\ChoiceList\View\ChoiceView; +use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\FormInterface; @@ -2277,4 +2278,111 @@ public function testWithSameLoaderAndDifferentChoiceValueCallbacks() $this->assertSame('20', $view['choice_two']->vars['choices'][1]->value); $this->assertSame('30', $view['choice_two']->vars['choices'][2]->value); } + + public function testChoiceLazyThrowsWhenChoiceLoaderIsNotSet() + { + $this->expectException(LogicException::class); + $this->expectExceptionMessage('The "choice_lazy" option can only be used if the "choice_loader" option is set.'); + + $this->factory->create(static::TESTED_TYPE, null, [ + 'choice_lazy' => true, + ]); + } + + public function testChoiceLazyLoadsAndRendersNothingWhenNoDataSet() + { + $form = $this->factory->create(static::TESTED_TYPE, null, [ + 'choice_loader' => new CallbackChoiceLoader(fn () => ['a' => 'A', 'b' => 'B']), + 'choice_lazy' => true, + ]); + + $this->assertNull($form->getData()); + + $view = $form->createView(); + $this->assertArrayHasKey('choices', $view->vars); + $this->assertSame([], $view->vars['choices']); + } + + public function testChoiceLazyLoadsAndRendersOnlyDataSetViaDefault() + { + $form = $this->factory->create(static::TESTED_TYPE, 'A', [ + 'choice_loader' => new CallbackChoiceLoader(fn () => ['a' => 'A', 'b' => 'B']), + 'choice_lazy' => true, + ]); + + $this->assertSame('A', $form->getData()); + + $view = $form->createView(); + $this->assertArrayHasKey('choices', $view->vars); + $this->assertCount(1, $view->vars['choices']); + $this->assertSame('A', $view->vars['choices'][0]->value); + } + + public function testChoiceLazyLoadsAndRendersOnlyDataSetViaSubmit() + { + $form = $this->factory->create(static::TESTED_TYPE, null, [ + 'choice_loader' => new CallbackChoiceLoader(fn () => ['a' => 'A', 'b' => 'B']), + 'choice_lazy' => true, + ]); + + $form->submit('B'); + $this->assertSame('B', $form->getData()); + + $view = $form->createView(); + $this->assertArrayHasKey('choices', $view->vars); + $this->assertCount(1, $view->vars['choices']); + $this->assertSame('B', $view->vars['choices'][0]->value); + } + + public function testChoiceLazyErrorWhenInvalidSubmitData() + { + $form = $this->factory->create(static::TESTED_TYPE, null, [ + 'choice_loader' => new CallbackChoiceLoader(fn () => ['a' => 'A', 'b' => 'B']), + 'choice_lazy' => true, + ]); + + $form->submit('invalid'); + $this->assertNull($form->getData()); + + $view = $form->createView(); + $this->assertArrayHasKey('choices', $view->vars); + $this->assertCount(0, $view->vars['choices']); + $this->assertCount(1, $form->getErrors()); + $this->assertSame('ERROR: The selected choice is invalid.', trim((string) $form->getErrors())); + } + + public function testChoiceLazyMultipleWithDefaultData() + { + $form = $this->factory->create(static::TESTED_TYPE, ['A', 'B'], [ + 'choice_loader' => new CallbackChoiceLoader(fn () => ['a' => 'A', 'b' => 'B', 'c' => 'C']), + 'choice_lazy' => true, + 'multiple' => true, + ]); + + $this->assertSame(['A', 'B'], $form->getData()); + + $view = $form->createView(); + $this->assertArrayHasKey('choices', $view->vars); + $this->assertCount(2, $view->vars['choices']); + $this->assertSame('A', $view->vars['choices'][0]->value); + $this->assertSame('B', $view->vars['choices'][1]->value); + } + + public function testChoiceLazyMultipleWithSubmittedData() + { + $form = $this->factory->create(static::TESTED_TYPE, null, [ + 'choice_loader' => new CallbackChoiceLoader(fn () => ['a' => 'A', 'b' => 'B', 'c' => 'C']), + 'choice_lazy' => true, + 'multiple' => true, + ]); + + $form->submit(['B', 'C']); + $this->assertSame(['B', 'C'], $form->getData()); + + $view = $form->createView(); + $this->assertArrayHasKey('choices', $view->vars); + $this->assertCount(2, $view->vars['choices']); + $this->assertSame('B', $view->vars['choices'][0]->value); + $this->assertSame('C', $view->vars['choices'][1]->value); + } } diff --git a/Tests/Fixtures/Descriptor/resolved_form_type_1.json b/Tests/Fixtures/Descriptor/resolved_form_type_1.json index e071ec712f..5590018c09 100644 --- a/Tests/Fixtures/Descriptor/resolved_form_type_1.json +++ b/Tests/Fixtures/Descriptor/resolved_form_type_1.json @@ -6,6 +6,7 @@ "choice_attr", "choice_filter", "choice_label", + "choice_lazy", "choice_loader", "choice_name", "choice_translation_domain", diff --git a/Tests/Fixtures/Descriptor/resolved_form_type_1.txt b/Tests/Fixtures/Descriptor/resolved_form_type_1.txt index 005bfd3e96..93c6b66d98 100644 --- a/Tests/Fixtures/Descriptor/resolved_form_type_1.txt +++ b/Tests/Fixtures/Descriptor/resolved_form_type_1.txt @@ -8,22 +8,22 @@ Symfony\Component\Form\Extension\Core\Type\ChoiceType (Block prefix: "choice") choice_attr FormType FormType FormTypeCsrfExtension choice_filter -------------------- ------------------------------ ----------------------- choice_label compound action csrf_field_name - choice_loader data_class allow_file_upload csrf_message - choice_name empty_data attr csrf_protection - choice_translation_domain error_bubbling attr_translation_parameters csrf_token_id - choice_translation_parameters invalid_message auto_initialize csrf_token_manager - choice_value trim block_name - choices block_prefix - duplicate_preferred_choices by_reference - expanded data - group_by disabled - multiple form_attr - placeholder getter - placeholder_attr help - preferred_choices help_attr - separator help_html - separator_html help_translation_parameters - inherit_data + choice_lazy data_class allow_file_upload csrf_message + choice_loader empty_data attr csrf_protection + choice_name error_bubbling attr_translation_parameters csrf_token_id + choice_translation_domain invalid_message auto_initialize csrf_token_manager + choice_translation_parameters trim block_name + choice_value block_prefix + choices by_reference + duplicate_preferred_choices data + expanded disabled + group_by form_attr + multiple getter + placeholder help + placeholder_attr help_attr + preferred_choices help_html + separator help_translation_parameters + separator_html inherit_data invalid_message_parameters is_empty_callback label From afc4cf934134f84769a08d68ed319fbfb76422a1 Mon Sep 17 00:00:00 2001 From: Dariusz Ruminski Date: Sat, 31 Aug 2024 00:31:12 +0200 Subject: [PATCH 185/208] CS: re-apply `trailing_comma_in_multiline` --- Tests/Extension/Core/Type/RepeatedTypeTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Extension/Core/Type/RepeatedTypeTest.php b/Tests/Extension/Core/Type/RepeatedTypeTest.php index b6b74f1aa1..2d19a0613d 100644 --- a/Tests/Extension/Core/Type/RepeatedTypeTest.php +++ b/Tests/Extension/Core/Type/RepeatedTypeTest.php @@ -199,7 +199,7 @@ public function testSubmitNullForTextTypeWithEmptyDataOptionSetToEmptyString($em 'type' => TextType::class, 'options' => [ 'empty_data' => $emptyData, - ] + ], ]); $form->submit($submittedData); From 81c5c3281ae822a13f1271d261954ef28feee6cd Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Mon, 23 Sep 2024 12:51:56 +0200 Subject: [PATCH 186/208] do not use the Test suffix for non test classes --- Test/FormPerformanceTestCase.php | 4 ++-- Tests/Extension/Core/Type/BaseTypeTestCase.php | 4 ++-- Tests/{VersionAwareTest.php => VersionAwareTestTrait.php} | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) rename Tests/{VersionAwareTest.php => VersionAwareTestTrait.php} (95%) diff --git a/Test/FormPerformanceTestCase.php b/Test/FormPerformanceTestCase.php index 1d631a2fde..12217e44b1 100644 --- a/Test/FormPerformanceTestCase.php +++ b/Test/FormPerformanceTestCase.php @@ -11,7 +11,7 @@ namespace Symfony\Component\Form\Test; -use Symfony\Component\Form\Tests\VersionAwareTest; +use Symfony\Component\Form\Tests\VersionAwareTestTrait; /** * Base class for performance tests. @@ -23,7 +23,7 @@ */ abstract class FormPerformanceTestCase extends FormIntegrationTestCase { - use VersionAwareTest; + use VersionAwareTestTrait; protected int $maxRunningTime = 0; diff --git a/Tests/Extension/Core/Type/BaseTypeTestCase.php b/Tests/Extension/Core/Type/BaseTypeTestCase.php index 14b602a4b4..6ba9c68588 100644 --- a/Tests/Extension/Core/Type/BaseTypeTestCase.php +++ b/Tests/Extension/Core/Type/BaseTypeTestCase.php @@ -12,14 +12,14 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\Test\TypeTestCase; -use Symfony\Component\Form\Tests\VersionAwareTest; +use Symfony\Component\Form\Tests\VersionAwareTestTrait; /** * @author Bernhard Schussek */ abstract class BaseTypeTestCase extends TypeTestCase { - use VersionAwareTest; + use VersionAwareTestTrait; public const TESTED_TYPE = ''; diff --git a/Tests/VersionAwareTest.php b/Tests/VersionAwareTestTrait.php similarity index 95% rename from Tests/VersionAwareTest.php rename to Tests/VersionAwareTestTrait.php index 530c174739..62e98934e3 100644 --- a/Tests/VersionAwareTest.php +++ b/Tests/VersionAwareTestTrait.php @@ -14,7 +14,7 @@ /** * @deprecated since Symfony 7.2, use feature detection instead. */ -trait VersionAwareTest +trait VersionAwareTestTrait { protected static int $supportedFeatureSetVersion = 404; @@ -23,7 +23,7 @@ trait VersionAwareTest */ protected function requiresFeatureSet(int $requiredFeatureSetVersion) { - trigger_deprecation('symfony/form', '7.2', 'The "%s" trait is deprecated, use feature detection instead.', VersionAwareTest::class); + trigger_deprecation('symfony/form', '7.2', 'The "%s" trait is deprecated, use feature detection instead.', VersionAwareTestTrait::class); if ($requiredFeatureSetVersion > static::$supportedFeatureSetVersion) { $this->markTestSkipped(\sprintf('Test requires features from symfony/form %.2f but only version %.2f is supported.', $requiredFeatureSetVersion / 100, static::$supportedFeatureSetVersion / 100)); From c85e835399b759bd42991fd59f8afb8dc9775982 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Mon, 23 Sep 2024 11:18:25 +0200 Subject: [PATCH 187/208] do not override the final runTest() method --- Test/FormPerformanceTestCase.php | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Test/FormPerformanceTestCase.php b/Test/FormPerformanceTestCase.php index 1d631a2fde..eafdf6c5f7 100644 --- a/Test/FormPerformanceTestCase.php +++ b/Test/FormPerformanceTestCase.php @@ -25,19 +25,25 @@ abstract class FormPerformanceTestCase extends FormIntegrationTestCase { use VersionAwareTest; + private float $startTime; protected int $maxRunningTime = 0; - protected function runTest(): mixed + protected function setUp(): void { - $s = microtime(true); - $result = parent::runTest(); - $time = microtime(true) - $s; + parent::setUp(); + + $this->startTime = microtime(true); + } + + protected function assertPostConditions(): void + { + parent::assertPostConditions(); + + $time = microtime(true) - $this->startTime; if (0 != $this->maxRunningTime && $time > $this->maxRunningTime) { $this->fail(\sprintf('expected running time: <= %s but was: %s', $this->maxRunningTime, $time)); } - - return $result; } /** From 9c44ae8084df0ed829f0de020b7a4d8bdc80afa4 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Tue, 24 Sep 2024 13:28:07 +0200 Subject: [PATCH 188/208] Remove useless parent method calls in tests --- Tests/ChoiceList/AbstractChoiceListTestCase.php | 2 -- .../DateTimeToLocalizedStringTransformerTest.php | 2 -- .../Core/DataTransformer/DateTimeToRfc3339TransformerTest.php | 2 -- Tests/Extension/Core/Type/MoneyTypeTest.php | 2 -- Tests/Extension/Core/Type/NumberTypeTest.php | 2 -- Tests/Extension/Core/Type/PercentTypeTest.php | 2 -- Tests/NativeRequestHandlerTest.php | 2 -- 7 files changed, 14 deletions(-) diff --git a/Tests/ChoiceList/AbstractChoiceListTestCase.php b/Tests/ChoiceList/AbstractChoiceListTestCase.php index 0b0cb8e79f..5ddae56141 100644 --- a/Tests/ChoiceList/AbstractChoiceListTestCase.php +++ b/Tests/ChoiceList/AbstractChoiceListTestCase.php @@ -39,8 +39,6 @@ abstract class AbstractChoiceListTestCase extends TestCase protected function setUp(): void { - parent::setUp(); - $this->list = $this->createChoiceList(); $choices = $this->getChoices(); diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php index a14e4a44eb..e8527b2201 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php @@ -31,8 +31,6 @@ class DateTimeToLocalizedStringTransformerTest extends BaseDateTimeTransformerTe protected function setUp(): void { - parent::setUp(); - // Normalize intl. configuration settings. if (\extension_loaded('intl')) { $this->initialTestCaseUseException = ini_set('intl.use_exceptions', 0); diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php index 6a4d77039f..c69ba31be9 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.php @@ -25,8 +25,6 @@ class DateTimeToRfc3339TransformerTest extends BaseDateTimeTransformerTestCase protected function setUp(): void { - parent::setUp(); - $this->dateTime = new \DateTime('2010-02-03 04:05:06 UTC'); $this->dateTimeWithoutSeconds = new \DateTime('2010-02-03 04:05:00 UTC'); } diff --git a/Tests/Extension/Core/Type/MoneyTypeTest.php b/Tests/Extension/Core/Type/MoneyTypeTest.php index 302f09c22a..f9112ffcac 100644 --- a/Tests/Extension/Core/Type/MoneyTypeTest.php +++ b/Tests/Extension/Core/Type/MoneyTypeTest.php @@ -33,8 +33,6 @@ protected function setUp(): void protected function tearDown(): void { - parent::tearDown(); - \Locale::setDefault($this->defaultLocale); } diff --git a/Tests/Extension/Core/Type/NumberTypeTest.php b/Tests/Extension/Core/Type/NumberTypeTest.php index e744563d1a..95ccdfea9f 100644 --- a/Tests/Extension/Core/Type/NumberTypeTest.php +++ b/Tests/Extension/Core/Type/NumberTypeTest.php @@ -35,8 +35,6 @@ protected function setUp(): void protected function tearDown(): void { - parent::tearDown(); - \Locale::setDefault($this->defaultLocale); } diff --git a/Tests/Extension/Core/Type/PercentTypeTest.php b/Tests/Extension/Core/Type/PercentTypeTest.php index 76595d79be..120aab2f31 100644 --- a/Tests/Extension/Core/Type/PercentTypeTest.php +++ b/Tests/Extension/Core/Type/PercentTypeTest.php @@ -34,8 +34,6 @@ protected function setUp(): void protected function tearDown(): void { - parent::tearDown(); - \Locale::setDefault($this->defaultLocale); } diff --git a/Tests/NativeRequestHandlerTest.php b/Tests/NativeRequestHandlerTest.php index 3770e12199..6ff64bc657 100644 --- a/Tests/NativeRequestHandlerTest.php +++ b/Tests/NativeRequestHandlerTest.php @@ -41,8 +41,6 @@ protected function setUp(): void protected function tearDown(): void { - parent::tearDown(); - $_GET = []; $_POST = []; $_FILES = []; From bdf4a90b78d7a40f2fc077e435174f7d6f1ce128 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Thu, 26 Sep 2024 10:09:09 +0200 Subject: [PATCH 189/208] Remove unused imports --- Extension/Core/Type/TimeType.php | 1 - Tests/Extension/DataCollector/FormDataCollectorTest.php | 1 - 2 files changed, 2 deletions(-) diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index d799210665..35549b0419 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; -use Symfony\Component\Form\Event\PreSubmitEvent; use Symfony\Component\Form\Exception\InvalidConfigurationException; use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeImmutableToDateTimeTransformer; diff --git a/Tests/Extension/DataCollector/FormDataCollectorTest.php b/Tests/Extension/DataCollector/FormDataCollectorTest.php index 0517b26c3b..4090fc97bf 100644 --- a/Tests/Extension/DataCollector/FormDataCollectorTest.php +++ b/Tests/Extension/DataCollector/FormDataCollectorTest.php @@ -18,7 +18,6 @@ use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\DataCollector\FormDataCollector; use Symfony\Component\Form\Extension\DataCollector\FormDataExtractor; -use Symfony\Component\Form\Form; use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormFactory; use Symfony\Component\Form\FormInterface; From 5818e1437bfd9efc084c0a9bd4117c3ebf29149d Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Sat, 28 Sep 2024 13:16:28 +0200 Subject: [PATCH 190/208] [TwigBridge] Remove `VersionAwareTest` from `AbstractLayoutTestCase` --- Test/FormPerformanceTestCase.php | 1 - Tests/Extension/Core/Type/BaseTypeTestCase.php | 18 ------------------ 2 files changed, 19 deletions(-) diff --git a/Test/FormPerformanceTestCase.php b/Test/FormPerformanceTestCase.php index 3c6ba1145a..702f37b7a4 100644 --- a/Test/FormPerformanceTestCase.php +++ b/Test/FormPerformanceTestCase.php @@ -25,7 +25,6 @@ abstract class FormPerformanceTestCase extends FormIntegrationTestCase { use RunTestTrait; - use VersionAwareTest; /** * @var int diff --git a/Tests/Extension/Core/Type/BaseTypeTestCase.php b/Tests/Extension/Core/Type/BaseTypeTestCase.php index 5238e2fd88..32ab611168 100644 --- a/Tests/Extension/Core/Type/BaseTypeTestCase.php +++ b/Tests/Extension/Core/Type/BaseTypeTestCase.php @@ -19,8 +19,6 @@ */ abstract class BaseTypeTestCase extends TypeTestCase { - use VersionAwareTest; - public const TESTED_TYPE = ''; public function testPassDisabledAsOption() @@ -114,8 +112,6 @@ public function testDefaultTranslationDomain() public function testPassLabelTranslationParametersToView() { - $this->requiresFeatureSet(403); - $view = $this->factory->create($this->getTestedType(), null, array_merge($this->getTestOptions(), [ 'label_translation_parameters' => ['%param%' => 'value'], ])) @@ -126,8 +122,6 @@ public function testPassLabelTranslationParametersToView() public function testPassAttrTranslationParametersToView() { - $this->requiresFeatureSet(403); - $view = $this->factory->create($this->getTestedType(), null, array_merge($this->getTestOptions(), [ 'attr_translation_parameters' => ['%param%' => 'value'], ])) @@ -138,8 +132,6 @@ public function testPassAttrTranslationParametersToView() public function testInheritLabelTranslationParametersFromParent() { - $this->requiresFeatureSet(403); - $view = $this->factory ->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE, null, [ 'label_translation_parameters' => ['%param%' => 'value'], @@ -153,8 +145,6 @@ public function testInheritLabelTranslationParametersFromParent() public function testInheritAttrTranslationParametersFromParent() { - $this->requiresFeatureSet(403); - $view = $this->factory ->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE, null, [ 'attr_translation_parameters' => ['%param%' => 'value'], @@ -168,8 +158,6 @@ public function testInheritAttrTranslationParametersFromParent() public function testPreferOwnLabelTranslationParameters() { - $this->requiresFeatureSet(403); - $view = $this->factory ->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE, null, [ 'label_translation_parameters' => ['%parent_param%' => 'parent_value', '%override_param%' => 'parent_override_value'], @@ -185,8 +173,6 @@ public function testPreferOwnLabelTranslationParameters() public function testPreferOwnAttrTranslationParameters() { - $this->requiresFeatureSet(403); - $view = $this->factory ->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE, null, [ 'attr_translation_parameters' => ['%parent_param%' => 'parent_value', '%override_param%' => 'parent_override_value'], @@ -202,8 +188,6 @@ public function testPreferOwnAttrTranslationParameters() public function testDefaultLabelTranslationParameters() { - $this->requiresFeatureSet(403); - $view = $this->factory->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE) ->add('child', $this->getTestedType(), $this->getTestOptions()) ->getForm() @@ -214,8 +198,6 @@ public function testDefaultLabelTranslationParameters() public function testDefaultAttrTranslationParameters() { - $this->requiresFeatureSet(403); - $view = $this->factory->createNamedBuilder('parent', FormTypeTest::TESTED_TYPE) ->add('child', $this->getTestedType(), $this->getTestOptions()) ->getForm() From 0df8534ea695de4db1ba76b6a0a060b66d75e25f Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Wed, 2 Oct 2024 10:47:28 +0200 Subject: [PATCH 191/208] Make `@var` occurrences consistent --- Extension/Validator/ValidatorExtension.php | 2 +- FormBuilder.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Extension/Validator/ValidatorExtension.php b/Extension/Validator/ValidatorExtension.php index 522a769629..2c534481cd 100644 --- a/Extension/Validator/ValidatorExtension.php +++ b/Extension/Validator/ValidatorExtension.php @@ -40,7 +40,7 @@ public function __construct( // the DIC, where the XML file is loaded automatically. Thus the following // code must be kept synchronized with validation.xml - /* @var $metadata ClassMetadata */ + /* @var ClassMetadata $metadata */ $metadata->addConstraint(new Form()); $metadata->addConstraint(new Traverse(false)); } diff --git a/FormBuilder.php b/FormBuilder.php index 2bfd92a688..f34c2f76eb 100644 --- a/FormBuilder.php +++ b/FormBuilder.php @@ -142,7 +142,7 @@ public function count(): int public function getFormConfig(): FormConfigInterface { - /** @var $config self */ + /** @var self $config */ $config = parent::getFormConfig(); $config->children = []; From 64116e00ea52c0e7f82d91ae55edf2b8fdbfb997 Mon Sep 17 00:00:00 2001 From: Dariusz Ruminski Date: Sun, 6 Oct 2024 18:45:39 +0200 Subject: [PATCH 192/208] CS: clean some whitespaces/indentation --- .../Core/DataTransformer/NumberToLocalizedStringTransformer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php index 127688e249..7911b47bd1 100644 --- a/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php +++ b/Extension/Core/DataTransformer/NumberToLocalizedStringTransformer.php @@ -102,7 +102,7 @@ public function reverseTransform(mixed $value): int|float|null $value = str_replace(',', $decSep, $value); } - //If the value is in exponential notation with a negative exponent, we end up with a float value too + // If the value is in exponential notation with a negative exponent, we end up with a float value too if (str_contains($value, $decSep) || false !== stripos($value, 'e-')) { $type = \NumberFormatter::TYPE_DOUBLE; } else { From d4cb9a2447b46f16256bb2b327434d80a35b10b6 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Tue, 8 Oct 2024 14:54:29 +0200 Subject: [PATCH 193/208] [Form] Remove unnecessary imports --- Test/FormPerformanceTestCase.php | 1 - Tests/Extension/Core/Type/BaseTypeTestCase.php | 1 - 2 files changed, 2 deletions(-) diff --git a/Test/FormPerformanceTestCase.php b/Test/FormPerformanceTestCase.php index 702f37b7a4..21e6ed7da8 100644 --- a/Test/FormPerformanceTestCase.php +++ b/Test/FormPerformanceTestCase.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Form\Test; use Symfony\Component\Form\Test\Traits\RunTestTrait; -use Symfony\Component\Form\Tests\VersionAwareTest; /** * Base class for performance tests. diff --git a/Tests/Extension/Core/Type/BaseTypeTestCase.php b/Tests/Extension/Core/Type/BaseTypeTestCase.php index 32ab611168..8293ec31bd 100644 --- a/Tests/Extension/Core/Type/BaseTypeTestCase.php +++ b/Tests/Extension/Core/Type/BaseTypeTestCase.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Form\Tests\Extension\Core\Type; use Symfony\Component\Form\Test\TypeTestCase; -use Symfony\Component\Form\Tests\VersionAwareTest; /** * @author Bernhard Schussek From 6a49eed7c6fc1ab8b4f8916c500468ac1b5046c3 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 26 Aug 2024 16:50:35 +0200 Subject: [PATCH 194/208] [Security] Implement stateless headers/cookies-based CSRF protection --- Extension/Csrf/Type/FormTypeCsrfExtension.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Extension/Csrf/Type/FormTypeCsrfExtension.php b/Extension/Csrf/Type/FormTypeCsrfExtension.php index 0ad4daeb3c..10367ae5ff 100644 --- a/Extension/Csrf/Type/FormTypeCsrfExtension.php +++ b/Extension/Csrf/Type/FormTypeCsrfExtension.php @@ -19,6 +19,7 @@ use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; use Symfony\Component\Form\Util\ServerParams; +use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Symfony\Contracts\Translation\TranslatorInterface; @@ -35,6 +36,8 @@ public function __construct( private ?TranslatorInterface $translator = null, private ?string $translationDomain = null, private ?ServerParams $serverParams = null, + private array $fieldAttr = [], + private ?string $defaultTokenId = null, ) { } @@ -73,6 +76,7 @@ public function finishView(FormView $view, FormInterface $form, array $options): $csrfForm = $factory->createNamed($options['csrf_field_name'], HiddenType::class, $data, [ 'block_prefix' => 'csrf_token', 'mapped' => false, + 'attr' => $this->fieldAttr + ['autocomplete' => 'off'], ]); $view->children[$options['csrf_field_name']] = $csrfForm->createView($view); @@ -81,13 +85,24 @@ public function finishView(FormView $view, FormInterface $form, array $options): public function configureOptions(OptionsResolver $resolver): void { + if ($defaultTokenId = $this->defaultTokenId) { + $defaultTokenManager = $this->defaultTokenManager; + $defaultTokenId = static fn (Options $options) => $options['csrf_token_manager'] === $defaultTokenManager ? $defaultTokenId : null; + } + $resolver->setDefaults([ 'csrf_protection' => $this->defaultEnabled, 'csrf_field_name' => $this->defaultFieldName, 'csrf_message' => 'The CSRF token is invalid. Please try to resubmit the form.', 'csrf_token_manager' => $this->defaultTokenManager, - 'csrf_token_id' => null, + 'csrf_token_id' => $defaultTokenId, ]); + + $resolver->setAllowedTypes('csrf_protection', 'bool'); + $resolver->setAllowedTypes('csrf_field_name', 'string'); + $resolver->setAllowedTypes('csrf_message', 'string'); + $resolver->setAllowedTypes('csrf_token_manager', CsrfTokenManagerInterface::class); + $resolver->setAllowedTypes('csrf_token_id', ['null', 'string']); } public static function getExtendedTypes(): iterable From 896c5f267eeb0cee02dd5ce196c6581c7b07575c Mon Sep 17 00:00:00 2001 From: Jules Pietri Date: Thu, 20 Jul 2023 12:22:19 +0200 Subject: [PATCH 195/208] [Form] Use `form.post_set_data` in `ResizeFormListener` --- CHANGELOG.md | 2 + .../Core/EventListener/ResizeFormListener.php | 48 ++- .../EventListener/DataCollectorListener.php | 4 +- .../EventListener/ResizeFormListenerTest.php | 293 +++++++++++------- 4 files changed, 233 insertions(+), 114 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cef486963..3b1fabfd17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ CHANGELOG * Deprecate the `VersionAwareTest` trait, use feature detection instead * Add support for the `calendar` option in `DateType` * Add `LazyChoiceLoader` and `choice_lazy` option in `ChoiceType` for loading and rendering choices on demand + * Use `form.post_set_data` instead of `form.pre_set_data` in `ResizeFormListener` + * Change the priority of `DataCollectorListener` from 255 to -255 7.1 --- diff --git a/Extension/Core/EventListener/ResizeFormListener.php b/Extension/Core/EventListener/ResizeFormListener.php index d67efab31e..299f919373 100644 --- a/Extension/Core/EventListener/ResizeFormListener.php +++ b/Extension/Core/EventListener/ResizeFormListener.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Form\Extension\Core\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\Form\Event\PostSetDataEvent; use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; @@ -27,6 +28,9 @@ class ResizeFormListener implements EventSubscriberInterface protected array $prototypeOptions; private \Closure|bool $deleteEmpty; + // BC, to be removed in 8.0 + private bool $overridden = true; + private bool $usePreSetData = false; public function __construct( private string $type, @@ -44,15 +48,57 @@ public function __construct( public static function getSubscribedEvents(): array { return [ - FormEvents::PRE_SET_DATA => 'preSetData', + FormEvents::PRE_SET_DATA => 'preSetData', // deprecated + FormEvents::POST_SET_DATA => ['postSetData', 255], // as early as possible FormEvents::PRE_SUBMIT => 'preSubmit', // (MergeCollectionListener, MergeDoctrineCollectionListener) FormEvents::SUBMIT => ['onSubmit', 50], ]; } + /** + * @deprecated Since Symfony 7.2, use {@see postSetData()} instead. + */ public function preSetData(FormEvent $event): void { + if (__CLASS__ === static::class + || __CLASS__ === (new \ReflectionClass($this))->getMethod('preSetData')->getDeclaringClass()->name + ) { + // not a child class, or child class does not overload PRE_SET_DATA + return; + } + + trigger_deprecation('symfony/form', '7.2', 'Calling "%s()" is deprecated, use "%s::postSetData()" instead.', __METHOD__, __CLASS__); + // parent::preSetData() has been called + $this->overridden = false; + try { + $this->postSetData($event); + } finally { + $this->usePreSetData = true; + } + } + + /** + * Remove FormEvent type hint in 8.0. + * + * @final since Symfony 7.2 + */ + public function postSetData(FormEvent|PostSetDataEvent $event): void + { + if (__CLASS__ !== static::class) { + if ($this->overridden) { + trigger_deprecation('symfony/form', '7.2', 'Calling "%s::preSetData()" is deprecated, use "%s::postSetData()" instead.', static::class, __CLASS__); + // parent::preSetData() has not been called, noop + + return; + } + + if ($this->usePreSetData) { + // nothing else to do + return; + } + } + $form = $event->getForm(); $data = $event->getData() ?? []; diff --git a/Extension/DataCollector/EventListener/DataCollectorListener.php b/Extension/DataCollector/EventListener/DataCollectorListener.php index 02cffbeffe..c541efec25 100644 --- a/Extension/DataCollector/EventListener/DataCollectorListener.php +++ b/Extension/DataCollector/EventListener/DataCollectorListener.php @@ -32,8 +32,8 @@ public function __construct( public static function getSubscribedEvents(): array { return [ - // High priority in order to be called as soon as possible - FormEvents::POST_SET_DATA => ['postSetData', 255], + // Low priority in order to be called as late as possible + FormEvents::POST_SET_DATA => ['postSetData', -255], // Low priority in order to be called as late as possible FormEvents::POST_SUBMIT => ['postSubmit', -255], ]; diff --git a/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php b/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php index f63a5c1548..934460c8f9 100644 --- a/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php +++ b/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php @@ -14,28 +14,28 @@ use Doctrine\Common\Collections\ArrayCollection; use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\Form\Extension\Core\DataMapper\DataMapper; use Symfony\Component\Form\Extension\Core\EventListener\ResizeFormListener; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilder; +use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormFactoryBuilder; use Symfony\Component\Form\FormFactoryInterface; -use Symfony\Component\Form\FormInterface; class ResizeFormListenerTest extends TestCase { private FormFactoryInterface $factory; - private FormInterface $form; + private FormBuilderInterface $builder; protected function setUp(): void { $this->factory = (new FormFactoryBuilder())->getFormFactory(); - $this->form = $this->getBuilder() + $this->builder = $this->getBuilder() ->setCompound(true) - ->setDataMapper(new DataMapper()) - ->getForm(); + ->setDataMapper(new DataMapper()); } protected function getBuilder($name = 'name') @@ -43,142 +43,221 @@ protected function getBuilder($name = 'name') return new FormBuilder($name, null, new EventDispatcher(), $this->factory); } - protected function getForm($name = 'name') + /** + * @group legacy + */ + public function testPreSetDataResizesForm() { - return $this->getBuilder($name)->getForm(); + $this->builder->add($this->getBuilder('0')); + $this->builder->add($this->getBuilder('1')); + $this->builder->addEventSubscriber(new class(TextType::class, ['attr' => ['maxlength' => 10]], false, false) extends ResizeFormListener { + public function preSetData(FormEvent $event): void + { + parent::preSetData($event); + } + }); + + $form = $this->builder->getForm(); + + $this->assertTrue($form->has('0')); + + // initialize the form + $form->setData([1 => 'string', 2 => 'string']); + + $this->assertFalse($form->has('0')); + $this->assertTrue($form->has('1')); + $this->assertTrue($form->has('2')); + + $this->assertSame('string', $form->get('1')->getData()); + $this->assertSame('string', $form->get('2')->getData()); } - public function testPreSetDataResizesForm() + public function testPostSetDataResizesForm() { - $this->form->add($this->getForm('0')); - $this->form->add($this->getForm('1')); + $this->builder->add($this->getBuilder('0')); + $this->builder->add($this->getBuilder('1')); + $this->builder->addEventSubscriber(new ResizeFormListener(TextType::class, ['attr' => ['maxlength' => 10]], false, false)); - $data = [1 => 'string', 2 => 'string']; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener(TextType::class, ['attr' => ['maxlength' => 10]], false, false); - $listener->preSetData($event); + $form = $this->builder->getForm(); + + $this->assertTrue($form->has('0')); - $this->assertFalse($this->form->has('0')); - $this->assertTrue($this->form->has('1')); - $this->assertTrue($this->form->has('2')); + // initialize the form + $form->setData([1 => 'string', 2 => 'string']); + + $this->assertFalse($form->has('0')); + $this->assertTrue($form->has('1')); + $this->assertTrue($form->has('2')); + + $this->assertSame('string', $form->get('1')->getData()); + $this->assertSame('string', $form->get('2')->getData()); } + /** + * @group legacy + */ public function testPreSetDataRequiresArrayOrTraversable() { $this->expectException(UnexpectedTypeException::class); $data = 'no array or traversable'; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, false); + $event = new FormEvent($this->builder->getForm(), $data); + $listener = new class(TextType::class, [], false, false) extends ResizeFormListener { + public function preSetData(FormEvent $event): void + { + parent::preSetData($event); + } + }; $listener->preSetData($event); } + public function testPostSetDataRequiresArrayOrTraversable() + { + $this->expectException(UnexpectedTypeException::class); + $data = 'no array or traversable'; + $event = new FormEvent($this->builder->getForm(), $data); + $listener = new ResizeFormListener(TextType::class, [], false, false); + $listener->postSetData($event); + } + + /** + * @group legacy + */ public function testPreSetDataDealsWithNullData() { $data = null; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener(TextType::class, [], false, false); + $event = new FormEvent($this->builder->getForm(), $data); + $listener = new class(TextType::class, [], false, false) extends ResizeFormListener { + public function preSetData(FormEvent $event): void + { + parent::preSetData($event); + } + }; $listener->preSetData($event); - $this->assertSame(0, $this->form->count()); + $this->assertSame(0, $this->builder->count()); + } + + public function testPostSetDataDealsWithNullData() + { + $data = null; + $event = new FormEvent($this->builder->getForm(), $data); + $listener = new ResizeFormListener(TextType::class, [], false, false); + $listener->postSetData($event); + + $this->assertSame(0, $this->builder->count()); } public function testPreSubmitResizesUpIfAllowAdd() { - $this->form->add($this->getForm('0')); + $this->builder->add($this->getBuilder('0')); + $this->builder->addEventSubscriber(new ResizeFormListener(TextType::class, ['attr' => ['maxlength' => 10]], true, false)); - $data = [0 => 'string', 1 => 'string']; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener(TextType::class, ['attr' => ['maxlength' => 10]], true, false); - $listener->preSubmit($event); + $form = $this->builder->getForm(); + + $this->assertTrue($form->has('0')); + $this->assertFalse($form->has('1')); - $this->assertTrue($this->form->has('0')); - $this->assertTrue($this->form->has('1')); + $form->submit([0 => 'string', 1 => 'string']); + + $this->assertTrue($form->has('0')); + $this->assertTrue($form->has('1')); } public function testPreSubmitResizesDownIfAllowDelete() { - $this->form->add($this->getForm('0')); - $this->form->add($this->getForm('1')); + $this->builder->add($this->getBuilder('0')); + $this->builder->add($this->getBuilder('1')); + $this->builder->addEventSubscriber(new ResizeFormListener(TextType::class, [], false, true)); - $data = [0 => 'string']; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, true); - $listener->preSubmit($event); + $form = $this->builder->getForm(); + // initialize the form + $form->setData([0 => 'string', 1 => 'string']); + + $this->assertTrue($form->has('0')); + $this->assertTrue($form->has('1')); - $this->assertTrue($this->form->has('0')); - $this->assertFalse($this->form->has('1')); + $form->submit([0 => 'string']); + + $this->assertTrue($form->has('0')); + $this->assertFalse($form->has('1')); } // fix for https://github.com/symfony/symfony/pull/493 public function testPreSubmitRemovesZeroKeys() { - $this->form->add($this->getForm('0')); + $this->builder->add($this->getBuilder('0')); $data = []; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, true); + $form = $this->builder->getForm(); + $event = new FormEvent($form, $data); + $listener = new ResizeFormListener(TextType::class, [], false, true); $listener->preSubmit($event); - $this->assertFalse($this->form->has('0')); + $this->assertFalse($form->has('0')); } public function testPreSubmitDoesNothingIfNotAllowAddNorAllowDelete() { - $this->form->add($this->getForm('0')); - $this->form->add($this->getForm('1')); + $this->builder->add($this->getBuilder('0')); + $this->builder->add($this->getBuilder('1')); $data = [0 => 'string', 2 => 'string']; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, false); + $form = $this->builder->getForm(); + $event = new FormEvent($form, $data); + $listener = new ResizeFormListener(TextType::class, [], false, false); $listener->preSubmit($event); - $this->assertTrue($this->form->has('0')); - $this->assertTrue($this->form->has('1')); - $this->assertFalse($this->form->has('2')); + $this->assertTrue($form->has('0')); + $this->assertTrue($form->has('1')); + $this->assertFalse($form->has('2')); } public function testPreSubmitDealsWithNoArrayOrTraversable() { $data = 'no array or traversable'; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, false); + $form = $this->builder->getForm(); + $event = new FormEvent($form, $data); + $listener = new ResizeFormListener(TextType::class, [], false, false); $listener->preSubmit($event); - $this->assertFalse($this->form->has('1')); + $this->assertFalse($form->has('1')); } public function testPreSubmitDealsWithNullData() { - $this->form->add($this->getForm('1')); + $this->builder->add($this->getBuilder('1')); $data = null; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, true); + $form = $this->builder->getForm(); + $event = new FormEvent($form, $data); + $listener = new ResizeFormListener(TextType::class, [], false, true); $listener->preSubmit($event); - $this->assertFalse($this->form->has('1')); + $this->assertFalse($form->has('1')); } // fixes https://github.com/symfony/symfony/pull/40 public function testPreSubmitDealsWithEmptyData() { - $this->form->add($this->getForm('1')); + $this->builder->add($this->getBuilder('1')); $data = ''; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, true); + $form = $this->builder->getForm(); + $event = new FormEvent($form, $data); + $listener = new ResizeFormListener(TextType::class, [], false, true); $listener->preSubmit($event); - $this->assertFalse($this->form->has('1')); + $this->assertFalse($form->has('1')); } public function testOnSubmitNormDataRemovesEntriesMissingInTheFormIfAllowDelete() { - $this->form->add($this->getForm('1')); + $this->builder->add($this->getBuilder('1')); $data = [0 => 'first', 1 => 'second', 2 => 'third']; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, true); + $form = $this->builder->getForm(); + $event = new FormEvent($form, $data); + $listener = new ResizeFormListener(TextType::class, [], false, true); $listener->onSubmit($event); $this->assertEquals([1 => 'second'], $event->getData()); @@ -186,11 +265,12 @@ public function testOnSubmitNormDataRemovesEntriesMissingInTheFormIfAllowDelete( public function testOnSubmitNormDataDoesNothingIfNotAllowDelete() { - $this->form->add($this->getForm('1')); + $this->builder->add($this->getBuilder('1')); $data = [0 => 'first', 1 => 'second', 2 => 'third']; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, false); + $form = $this->builder->getForm(); + $event = new FormEvent($form, $data); + $listener = new ResizeFormListener(TextType::class, [], false, false); $listener->onSubmit($event); $this->assertEquals($data, $event->getData()); @@ -200,18 +280,18 @@ public function testOnSubmitNormDataRequiresArrayOrTraversable() { $this->expectException(UnexpectedTypeException::class); $data = 'no array or traversable'; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, false); + $event = new FormEvent($this->builder->getForm(), $data); + $listener = new ResizeFormListener(TextType::class, [], false, false); $listener->onSubmit($event); } public function testOnSubmitNormDataDealsWithNullData() { - $this->form->add($this->getForm('1')); + $this->builder->add($this->getBuilder('1')); $data = null; - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, true); + $event = new FormEvent($this->builder->getForm(), $data); + $listener = new ResizeFormListener(TextType::class, [], false, true); $listener->onSubmit($event); $this->assertEquals([], $event->getData()); @@ -219,11 +299,11 @@ public function testOnSubmitNormDataDealsWithNullData() public function testOnSubmitDealsWithObjectBackedIteratorAggregate() { - $this->form->add($this->getForm('1')); + $this->builder->add($this->getBuilder('1')); $data = new \ArrayObject([0 => 'first', 1 => 'second', 2 => 'third']); - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, true); + $event = new FormEvent($this->builder->getForm(), $data); + $listener = new ResizeFormListener(TextType::class, [], false, true); $listener->onSubmit($event); $this->assertArrayNotHasKey(0, $event->getData()); @@ -232,11 +312,11 @@ public function testOnSubmitDealsWithObjectBackedIteratorAggregate() public function testOnSubmitDealsWithArrayBackedIteratorAggregate() { - $this->form->add($this->getForm('1')); + $this->builder->add($this->getBuilder('1')); $data = new ArrayCollection([0 => 'first', 1 => 'second', 2 => 'third']); - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, true); + $event = new FormEvent($this->builder->getForm(), $data); + $listener = new ResizeFormListener(TextType::class, [], false, true); $listener->onSubmit($event); $this->assertArrayNotHasKey(0, $event->getData()); @@ -245,46 +325,37 @@ public function testOnSubmitDealsWithArrayBackedIteratorAggregate() public function testOnSubmitDeleteEmptyNotCompoundEntriesIfAllowDelete() { - $this->form->setData(['0' => 'first', '1' => 'second']); - $this->form->add($this->getForm('0')); - $this->form->add($this->getForm('1')); - - $data = [0 => 'first', 1 => '']; - foreach ($data as $child => $dat) { - $this->form->get($child)->submit($dat); - } - $event = new FormEvent($this->form, $data); - $listener = new ResizeFormListener('text', [], false, true, true); - $listener->onSubmit($event); + $this->builder->setData(['0' => 'first', '1' => 'second']); + $this->builder->add($this->getBuilder('0')); + $this->builder->add($this->getBuilder('1')); + $this->builder->addEventSubscriber(new ResizeFormListener(TextType::class, [], false, true, true)); - $this->assertEquals([0 => 'first'], $event->getData()); + $form = $this->builder->getForm(); + + $form->submit([0 => 'first', 1 => '']); + + $this->assertEquals([0 => 'first'], $form->getData()); } public function testOnSubmitDeleteEmptyCompoundEntriesIfAllowDelete() { - $this->form->setData(['0' => ['name' => 'John'], '1' => ['name' => 'Jane']]); - $form1 = $this->getBuilder('0') - ->setCompound(true) - ->setDataMapper(new DataMapper()) - ->getForm(); - $form1->add($this->getForm('name')); - $form2 = $this->getBuilder('1') - ->setCompound(true) - ->setDataMapper(new DataMapper()) - ->getForm(); - $form2->add($this->getForm('name')); - $this->form->add($form1); - $this->form->add($form2); - - $data = ['0' => ['name' => 'John'], '1' => ['name' => '']]; - foreach ($data as $child => $dat) { - $this->form->get($child)->submit($dat); - } - $event = new FormEvent($this->form, $data); - $callback = fn ($data) => null === $data['name']; - $listener = new ResizeFormListener('text', [], false, true, $callback); - $listener->onSubmit($event); + $this->builder->setData(['0' => ['name' => 'John'], '1' => ['name' => 'Jane']]); + $this->builder->add('0', NestedType::class); + $this->builder->add('1', NestedType::class); + $callback = fn ($data) => empty($data['name']); + $this->builder->addEventSubscriber(new ResizeFormListener(NestedType::class, [], false, true, $callback)); + + $form = $this->builder->getForm(); + $form->submit(['0' => ['name' => 'John'], '1' => ['name' => '']]); - $this->assertEquals(['0' => ['name' => 'John']], $event->getData()); + $this->assertEquals(['0' => ['name' => 'John']], $form->getData()); + } +} + +class NestedType extends AbstractType +{ + public function buildForm(FormBuilderInterface $builder, array $options): void + { + $builder->add('name'); } } From 04cf304af17de3da89851040b6dc6386e4cade86 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Mon, 14 Oct 2024 20:03:05 +0200 Subject: [PATCH 196/208] Reduce common control flows --- Extension/DataCollector/FormDataExtractor.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Extension/DataCollector/FormDataExtractor.php b/Extension/DataCollector/FormDataExtractor.php index 158cf32109..f56fe911fa 100644 --- a/Extension/DataCollector/FormDataExtractor.php +++ b/Extension/DataCollector/FormDataExtractor.php @@ -103,15 +103,13 @@ public function extractSubmittedData(FormInterface $form): array continue; } + $errorData['trace'][] = $cause; if ($cause instanceof \Exception) { - $errorData['trace'][] = $cause; $cause = $cause->getPrevious(); continue; } - $errorData['trace'][] = $cause; - break; } From 73c00ef4ced12b43647a37c184f05650c636a539 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Fri, 18 Oct 2024 16:04:52 +0200 Subject: [PATCH 197/208] Remove always true/false occurrences --- .../Core/DataTransformer/DateIntervalToArrayTransformer.php | 2 +- Extension/Core/Type/DateType.php | 4 +--- Extension/Core/Type/TimeType.php | 4 +--- Extension/Core/Type/WeekType.php | 4 +--- Extension/Validator/Constraints/FormValidator.php | 2 +- 5 files changed, 5 insertions(+), 11 deletions(-) diff --git a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php index 18679a9103..8591db1910 100644 --- a/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php +++ b/Extension/Core/DataTransformer/DateIntervalToArrayTransformer.php @@ -139,7 +139,7 @@ public function reverseTransform(mixed $value): ?\DateInterval 'P%sY%sM%sWT%sH%sM%sS', empty($value['years']) ? '0' : $value['years'], empty($value['months']) ? '0' : $value['months'], - empty($value['weeks']) ? '0' : $value['weeks'], + $value['weeks'], empty($value['hours']) ? '0' : $value['hours'], empty($value['minutes']) ? '0' : $value['minutes'], empty($value['seconds']) ? '0' : $value['seconds'] diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index 54f24b89a0..e4aee6e8de 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -249,10 +249,8 @@ public function configureOptions(OptionsResolver $resolver): void $choiceTranslationDomainNormalizer = static function (Options $options, $choiceTranslationDomain) { if (\is_array($choiceTranslationDomain)) { - $default = false; - return array_replace( - ['year' => $default, 'month' => $default, 'day' => $default], + ['year' => false, 'month' => false, 'day' => false], $choiceTranslationDomain ); } diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 35549b0419..92cf42d963 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -274,10 +274,8 @@ public function configureOptions(OptionsResolver $resolver): void $choiceTranslationDomainNormalizer = static function (Options $options, $choiceTranslationDomain) { if (\is_array($choiceTranslationDomain)) { - $default = false; - return array_replace( - ['hour' => $default, 'minute' => $default, 'second' => $default], + ['hour' => false, 'minute' => false, 'second' => false], $choiceTranslationDomain ); } diff --git a/Extension/Core/Type/WeekType.php b/Extension/Core/Type/WeekType.php index ec5cc93037..aea4a6c564 100644 --- a/Extension/Core/Type/WeekType.php +++ b/Extension/Core/Type/WeekType.php @@ -113,10 +113,8 @@ public function configureOptions(OptionsResolver $resolver): void $choiceTranslationDomainNormalizer = static function (Options $options, $choiceTranslationDomain) { if (\is_array($choiceTranslationDomain)) { - $default = false; - return array_replace( - ['year' => $default, 'week' => $default], + ['year' => false, 'week' => false], $choiceTranslationDomain ); } diff --git a/Extension/Validator/Constraints/FormValidator.php b/Extension/Validator/Constraints/FormValidator.php index 703bac1484..8f4ec60f24 100644 --- a/Extension/Validator/Constraints/FormValidator.php +++ b/Extension/Validator/Constraints/FormValidator.php @@ -56,7 +56,7 @@ public function validate(mixed $form, Constraint $formConstraint): void // Validate the data against its own constraints $validateDataGraph = $form->isRoot() && (\is_object($data) || \is_array($data)) - && (($groups && \is_array($groups)) || ($groups instanceof GroupSequence && $groups->groups)) + && (\is_array($groups) || ($groups instanceof GroupSequence && $groups->groups)) ; // Validate the data against the constraints defined in the form From 264cff30f52f12149aff92bbc23e78160a45c2f3 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Wed, 27 Nov 2024 12:55:00 +0100 Subject: [PATCH 198/208] [Form] Allow integer for the `calendar` option of `DateType` --- Extension/Core/Type/DateType.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Extension/Core/Type/DateType.php b/Extension/Core/Type/DateType.php index e4aee6e8de..36b430e144 100644 --- a/Extension/Core/Type/DateType.php +++ b/Extension/Core/Type/DateType.php @@ -313,7 +313,7 @@ public function configureOptions(OptionsResolver $resolver): void $resolver->setAllowedTypes('months', 'array'); $resolver->setAllowedTypes('days', 'array'); $resolver->setAllowedTypes('input_format', 'string'); - $resolver->setAllowedTypes('calendar', ['null', \IntlCalendar::class]); + $resolver->setAllowedTypes('calendar', ['null', 'int', \IntlCalendar::class]); $resolver->setInfo('calendar', 'The calendar to use for formatting and parsing the date. The value should be an instance of \IntlCalendar. By default, the Gregorian calendar with the default locale is used.'); From 092a89345db25f8e4fc1804a4d3f184766e36e69 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Tue, 24 Dec 2024 13:01:45 +0100 Subject: [PATCH 199/208] do not render hidden CSRF token forms with autocomplete set to off --- Extension/Csrf/Type/FormTypeCsrfExtension.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Extension/Csrf/Type/FormTypeCsrfExtension.php b/Extension/Csrf/Type/FormTypeCsrfExtension.php index 10367ae5ff..1cb2b03426 100644 --- a/Extension/Csrf/Type/FormTypeCsrfExtension.php +++ b/Extension/Csrf/Type/FormTypeCsrfExtension.php @@ -76,7 +76,7 @@ public function finishView(FormView $view, FormInterface $form, array $options): $csrfForm = $factory->createNamed($options['csrf_field_name'], HiddenType::class, $data, [ 'block_prefix' => 'csrf_token', 'mapped' => false, - 'attr' => $this->fieldAttr + ['autocomplete' => 'off'], + 'attr' => $this->fieldAttr, ]); $view->children[$options['csrf_field_name']] = $csrfForm->createView($view); From 7209804c018b88cc2b0beabe38eef91b83f1d69a Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 7 Feb 2025 19:13:17 +0100 Subject: [PATCH 200/208] [Form][FrameworkBundle] Use auto-configuration to make the default CSRF token id apply only to the app; not to bundles --- DependencyInjection/FormPass.php | 13 ++++++++++++ Extension/Csrf/Type/FormTypeCsrfExtension.php | 16 +++++++++++---- Tests/DependencyInjection/FormPassTest.php | 20 +++++++++++++++++++ 3 files changed, 45 insertions(+), 4 deletions(-) diff --git a/DependencyInjection/FormPass.php b/DependencyInjection/FormPass.php index 1d2b2a87e5..bec1782d40 100644 --- a/DependencyInjection/FormPass.php +++ b/DependencyInjection/FormPass.php @@ -47,6 +47,7 @@ private function processFormTypes(ContainerBuilder $container): Reference // Get service locator argument $servicesMap = []; $namespaces = ['Symfony\Component\Form\Extension\Core\Type' => true]; + $csrfTokenIds = []; // Builds an array with fully-qualified type class names as keys and service IDs as values foreach ($container->findTaggedServiceIds('form.type', true) as $serviceId => $tag) { @@ -54,6 +55,10 @@ private function processFormTypes(ContainerBuilder $container): Reference $serviceDefinition = $container->getDefinition($serviceId); $servicesMap[$formType = $serviceDefinition->getClass()] = new Reference($serviceId); $namespaces[substr($formType, 0, strrpos($formType, '\\'))] = true; + + if (isset($tag[0]['csrf_token_id'])) { + $csrfTokenIds[$formType] = $tag[0]['csrf_token_id']; + } } if ($container->hasDefinition('console.command.form_debug')) { @@ -62,6 +67,14 @@ private function processFormTypes(ContainerBuilder $container): Reference $commandDefinition->setArgument(2, array_keys($servicesMap)); } + if ($csrfTokenIds && $container->hasDefinition('form.type_extension.csrf')) { + $csrfExtension = $container->getDefinition('form.type_extension.csrf'); + + if (8 <= \count($csrfExtension->getArguments())) { + $csrfExtension->replaceArgument(7, $csrfTokenIds); + } + } + return ServiceLocatorTagPass::register($container, $servicesMap); } diff --git a/Extension/Csrf/Type/FormTypeCsrfExtension.php b/Extension/Csrf/Type/FormTypeCsrfExtension.php index 1cb2b03426..a12b9a41ee 100644 --- a/Extension/Csrf/Type/FormTypeCsrfExtension.php +++ b/Extension/Csrf/Type/FormTypeCsrfExtension.php @@ -37,7 +37,7 @@ public function __construct( private ?string $translationDomain = null, private ?ServerParams $serverParams = null, private array $fieldAttr = [], - private ?string $defaultTokenId = null, + private string|array|null $defaultTokenId = null, ) { } @@ -50,11 +50,17 @@ public function buildForm(FormBuilderInterface $builder, array $options): void return; } + $csrfTokenId = $options['csrf_token_id'] + ?: $this->defaultTokenId[$builder->getType()->getInnerType()::class] + ?? $builder->getName() + ?: $builder->getType()->getInnerType()::class; + $builder->setAttribute('csrf_token_id', $csrfTokenId); + $builder ->addEventSubscriber(new CsrfValidationListener( $options['csrf_field_name'], $options['csrf_token_manager'], - $options['csrf_token_id'] ?: ($builder->getName() ?: $builder->getType()->getInnerType()::class), + $csrfTokenId, $options['csrf_message'], $this->translator, $this->translationDomain, @@ -70,7 +76,7 @@ public function finishView(FormView $view, FormInterface $form, array $options): { if ($options['csrf_protection'] && !$view->parent && $options['compound']) { $factory = $form->getConfig()->getFormFactory(); - $tokenId = $options['csrf_token_id'] ?: ($form->getName() ?: $form->getConfig()->getType()->getInnerType()::class); + $tokenId = $form->getConfig()->getAttribute('csrf_token_id'); $data = (string) $options['csrf_token_manager']->getToken($tokenId); $csrfForm = $factory->createNamed($options['csrf_field_name'], HiddenType::class, $data, [ @@ -85,9 +91,11 @@ public function finishView(FormView $view, FormInterface $form, array $options): public function configureOptions(OptionsResolver $resolver): void { - if ($defaultTokenId = $this->defaultTokenId) { + if (\is_string($defaultTokenId = $this->defaultTokenId) && $defaultTokenId) { $defaultTokenManager = $this->defaultTokenManager; $defaultTokenId = static fn (Options $options) => $options['csrf_token_manager'] === $defaultTokenManager ? $defaultTokenId : null; + } else { + $defaultTokenId = null; } $resolver->setDefaults([ diff --git a/Tests/DependencyInjection/FormPassTest.php b/Tests/DependencyInjection/FormPassTest.php index e9a7b50346..f0ccd3f095 100644 --- a/Tests/DependencyInjection/FormPassTest.php +++ b/Tests/DependencyInjection/FormPassTest.php @@ -21,6 +21,7 @@ use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Command\DebugCommand; use Symfony\Component\Form\DependencyInjection\FormPass; +use Symfony\Component\Form\Extension\Csrf\Type\FormTypeCsrfExtension; use Symfony\Component\Form\FormRegistry; /** @@ -95,6 +96,25 @@ public function testAddTaggedTypesToDebugCommand() ); } + public function testAddTaggedTypesToCsrfTypeExtension() + { + $container = $this->createContainerBuilder(); + + $container->register('form.registry', FormRegistry::class); + $container->register('form.type_extension.csrf', FormTypeCsrfExtension::class) + ->setArguments([null, true, '_token', null, 'validator.translation_domain', null, [], null]) + ->setPublic(true); + + $container->setDefinition('form.extension', $this->createExtensionDefinition()); + $container->register('my.type1', __CLASS__.'_Type1')->addTag('form.type', ['csrf_token_id' => 'the_token_id']); + $container->register('my.type2', __CLASS__.'_Type2')->addTag('form.type'); + + $container->compile(); + + $csrfDefinition = $container->getDefinition('form.type_extension.csrf'); + $this->assertSame([__CLASS__.'_Type1' => 'the_token_id'], $csrfDefinition->getArgument(7)); + } + /** * @dataProvider addTaggedTypeExtensionsDataProvider */ From e982e148bdaa5e0d70087237ef059528cd8be6d9 Mon Sep 17 00:00:00 2001 From: Santiago San Martin Date: Mon, 17 Mar 2025 01:07:55 -0300 Subject: [PATCH 201/208] fix translation in spanish --- Resources/translations/validators.es.xlf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Resources/translations/validators.es.xlf b/Resources/translations/validators.es.xlf index 301e2b33f7..a9989737c3 100644 --- a/Resources/translations/validators.es.xlf +++ b/Resources/translations/validators.es.xlf @@ -52,7 +52,7 @@ Please enter a valid date. - Por favor, ingrese una fecha valida. + Por favor, ingrese una fecha válida. Please select a valid file. From 3929e2a60a828f39df6765fb49d224cc629fa529 Mon Sep 17 00:00:00 2001 From: Alexander Hofbauer Date: Wed, 26 Mar 2025 17:02:02 +0100 Subject: [PATCH 202/208] [Form] Use duplicate_preferred_choices to set value of ChoiceType When the preferred choices are not duplicated an option has to be selected in the group of preferred choices. Closes #58561 --- Extension/Core/Type/ChoiceType.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Extension/Core/Type/ChoiceType.php b/Extension/Core/Type/ChoiceType.php index 35dcf1b1b9..32bc677667 100644 --- a/Extension/Core/Type/ChoiceType.php +++ b/Extension/Core/Type/ChoiceType.php @@ -281,6 +281,8 @@ public function buildView(FormView $view, FormInterface $form, array $options) */ public function finishView(FormView $view, FormInterface $form, array $options) { + $view->vars['duplicate_preferred_choices'] = $options['duplicate_preferred_choices']; + if ($options['expanded']) { // Radio buttons should have the same name as the parent $childName = $view->vars['full_name']; From 58471f52a058d64b5d128c26695191039b6199b5 Mon Sep 17 00:00:00 2001 From: Tom Hart <1374434+TomHart@users.noreply.github.com> Date: Fri, 4 Apr 2025 10:13:44 +0100 Subject: [PATCH 203/208] Update validators.pt.xlf --- Resources/translations/validators.pt.xlf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Resources/translations/validators.pt.xlf b/Resources/translations/validators.pt.xlf index 755108f357..673e79f420 100644 --- a/Resources/translations/validators.pt.xlf +++ b/Resources/translations/validators.pt.xlf @@ -24,7 +24,7 @@ The selected choice is invalid. - A escolha seleccionada é inválida. + A escolha selecionada é inválida. The collection is invalid. From c87b96dcb7e22673c389f5d06a8a2bb916cc26c4 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Tue, 8 Apr 2025 16:34:28 +0200 Subject: [PATCH 204/208] skip test if the installed ICU version is too modern --- .../DateTimeToLocalizedStringTransformerTest.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php index 189c409f4d..91b3cf213b 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php @@ -15,6 +15,7 @@ use Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToLocalizedStringTransformer; use Symfony\Component\Form\Tests\Extension\Core\DataTransformer\Traits\DateTimeEqualsTrait; +use Symfony\Component\Intl\Intl; use Symfony\Component\Intl\Util\IntlTestHelper; class DateTimeToLocalizedStringTransformerTest extends BaseDateTimeTransformerTestCase @@ -236,6 +237,10 @@ public function testReverseTransformFullTime() public function testReverseTransformFromDifferentLocale() { + if (version_compare(Intl::getIcuVersion(), '71.1', '>')) { + $this->markTestSkipped('ICU version 71.1 or lower is required.'); + }; + \Locale::setDefault('en_US'); $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC'); From 48c8d9bb1f891a84904f1e7f53e876697776fdfc Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sun, 27 Apr 2025 15:26:02 +0200 Subject: [PATCH 205/208] Remove unneeded use statements --- Extension/Core/Type/TimeType.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Extension/Core/Type/TimeType.php b/Extension/Core/Type/TimeType.php index 512a830bb2..4bd1a9433c 100644 --- a/Extension/Core/Type/TimeType.php +++ b/Extension/Core/Type/TimeType.php @@ -12,13 +12,13 @@ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; +use Symfony\Component\Form\Event\PreSubmitEvent; use Symfony\Component\Form\Exception\InvalidConfigurationException; use Symfony\Component\Form\Exception\LogicException; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeImmutableToDateTimeTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToArrayTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer; use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToTimestampTransformer; -use Symfony\Component\Form\Event\PreSubmitEvent; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; From de5c3d7dbb5538aba1476ed34f0197e501c06a39 Mon Sep 17 00:00:00 2001 From: wkania Date: Sun, 27 Apr 2025 15:58:34 +0200 Subject: [PATCH 206/208] Unnecessary cast, return, semicolon and comma --- .../DateTimeToLocalizedStringTransformerTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php index 91b3cf213b..6cbf6b9377 100644 --- a/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php +++ b/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php @@ -239,7 +239,7 @@ public function testReverseTransformFromDifferentLocale() { if (version_compare(Intl::getIcuVersion(), '71.1', '>')) { $this->markTestSkipped('ICU version 71.1 or lower is required.'); - }; + } \Locale::setDefault('en_US'); From 02275ed54317b830fc54f7be68bb2f1172cdfc43 Mon Sep 17 00:00:00 2001 From: wkania Date: Sun, 27 Apr 2025 16:24:15 +0200 Subject: [PATCH 207/208] Fix overwriting an array element --- Extension/Core/Type/WeekType.php | 1 - 1 file changed, 1 deletion(-) diff --git a/Extension/Core/Type/WeekType.php b/Extension/Core/Type/WeekType.php index 8027a41a99..778cc2aeb0 100644 --- a/Extension/Core/Type/WeekType.php +++ b/Extension/Core/Type/WeekType.php @@ -42,7 +42,6 @@ public function buildForm(FormBuilderInterface $builder, array $options) } else { $yearOptions = $weekOptions = [ 'error_bubbling' => true, - 'empty_data' => '', ]; // when the form is compound the entries of the array are ignored in favor of children data // so we need to handle the cascade setting here From aed57cbb5ffe9fe169cf48c7fdcb2d482670ae5e Mon Sep 17 00:00:00 2001 From: wkania Date: Sun, 27 Apr 2025 18:08:38 +0200 Subject: [PATCH 208/208] Fix return type is non-nullable --- Tests/Fixtures/TestExtension.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/Fixtures/TestExtension.php b/Tests/Fixtures/TestExtension.php index 44725a69c7..2704ee5303 100644 --- a/Tests/Fixtures/TestExtension.php +++ b/Tests/Fixtures/TestExtension.php @@ -34,7 +34,7 @@ public function addType(FormTypeInterface $type) public function getType($name): FormTypeInterface { - return $this->types[$name] ?? null; + return $this->types[$name]; } public function hasType($name): bool