[Form] Fix typed property initialization in ValidatorExtension

The early return in the constructor prevented typed properties from
being initialized when a Form constraint already existed, causing
PHP errors when the extension was used (PHP 8.0+ typed property
requirement).

This fix moves property initialization before the early return check,
ensuring typed properties are always initialized while preserving
the duplicate constraint prevention functionality.

Includes a test case to verify the fix works correctly when the
early return condition is met.
This commit is contained in:
Severin Glöckle
2026-03-13 15:59:02 +01:00
parent 3e6a53ddcc
commit 77676c8cc9
2 changed files with 23 additions and 4 deletions

View File

@@ -39,6 +39,10 @@ class ValidatorExtension extends AbstractExtension
/** @var ClassMetadata $metadata */
$metadata = $validator->getMetadataFor(\Symfony\Component\Form\Form::class);
$this->validator = $validator;
$this->formRenderer = $formRenderer;
$this->translator = $translator;
// Register the form constraints in the validator programmatically.
// This functionality is required when using the Form component without
// the DIC, where the XML file is loaded automatically. Thus the following
@@ -52,10 +56,6 @@ class ValidatorExtension extends AbstractExtension
$metadata->addConstraint(new Form());
$metadata->addConstraint(new Traverse(false));
$this->validator = $validator;
$this->formRenderer = $formRenderer;
$this->translator = $translator;
}
public function loadTypeGuesser(): ?FormTypeGuesserInterface

View File

@@ -64,4 +64,23 @@ class ValidatorExtensionTest extends TestCase
$this->assertCount(1, $metadata->getConstraints());
$this->assertInstanceOf(FormConstraint::class, $metadata->getConstraints()[0]);
}
public function testPropertiesInitializedWithEarlyReturn()
{
$metadata = new ClassMetadata(Form::class);
$metadata->addConstraint(new FormConstraint());
$metadataFactory = new FakeMetadataFactory();
$metadataFactory->addMetadata($metadata);
$validator = Validation::createValidatorBuilder()
->setMetadataFactory($metadataFactory)
->getValidator();
// create with an early return condition
$extension = new ValidatorExtension($validator, false);
// verify the extension is functional after an early return
$this->assertInstanceOf(ValidatorTypeGuesser::class, $extension->loadTypeGuesser());
}
}