-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[Validator][DoctrineBridge][FWBundle] Automatic data validation #27735
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
58 changes: 58 additions & 0 deletions
58
src/Symfony/Bridge/Doctrine/Tests/Fixtures/DoctrineLoaderEntity.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Bridge\Doctrine\Tests\Fixtures; | ||
|
||
use Doctrine\ORM\Mapping as ORM; | ||
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; | ||
use Symfony\Component\Validator\Constraints as Assert; | ||
|
||
/** | ||
* @ORM\Entity | ||
* @UniqueEntity(fields={"alreadyMappedUnique"}) | ||
* | ||
* @author Kévin Dunglas <dunglas@gmail.com> | ||
*/ | ||
class DoctrineLoaderEntity | ||
{ | ||
/** | ||
* @ORM\Id | ||
* @ORM\Column | ||
*/ | ||
public $id; | ||
|
||
/** | ||
* @ORM\Column(length=20) | ||
*/ | ||
public $maxLength; | ||
|
||
/** | ||
* @ORM\Column(length=20) | ||
* @Assert\Length(min=5) | ||
*/ | ||
public $mergedMaxLength; | ||
|
||
/** | ||
* @ORM\Column(length=20) | ||
* @Assert\Length(min=1, max=10) | ||
*/ | ||
public $alreadyMappedMaxLength; | ||
|
||
/** | ||
* @ORM\Column(unique=true) | ||
*/ | ||
public $unique; | ||
|
||
/** | ||
* @ORM\Column(unique=true) | ||
*/ | ||
public $alreadyMappedUnique; | ||
} |
94 changes: 94 additions & 0 deletions
94
src/Symfony/Bridge/Doctrine/Tests/Validator/DoctrineLoaderTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Bridge\Doctrine\Tests\Validator; | ||
|
||
use PHPUnit\Framework\TestCase; | ||
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper; | ||
use Symfony\Bridge\Doctrine\Tests\Fixtures\DoctrineLoaderEntity; | ||
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; | ||
use Symfony\Bridge\Doctrine\Validator\DoctrineLoader; | ||
use Symfony\Component\Validator\Constraints\Length; | ||
use Symfony\Component\Validator\Mapping\ClassMetadata; | ||
use Symfony\Component\Validator\Tests\Fixtures\Entity; | ||
use Symfony\Component\Validator\Validation; | ||
use Symfony\Component\Validator\ValidatorBuilder; | ||
|
||
/** | ||
* @author Kévin Dunglas <dunglas@gmail.com> | ||
*/ | ||
class DoctrineLoaderTest extends TestCase | ||
{ | ||
public function testLoadClassMetadata() | ||
{ | ||
if (!method_exists(ValidatorBuilder::class, 'addLoader')) { | ||
$this->markTestSkipped('Auto-mapping requires symfony/validation 4.2+'); | ||
} | ||
|
||
$validator = Validation::createValidatorBuilder() | ||
->enableAnnotationMapping() | ||
->addLoader(new DoctrineLoader(DoctrineTestHelper::createTestEntityManager())) | ||
->getValidator() | ||
; | ||
|
||
$classMetadata = $validator->getMetadataFor(new DoctrineLoaderEntity()); | ||
|
||
$classConstraints = $classMetadata->getConstraints(); | ||
$this->assertCount(2, $classConstraints); | ||
$this->assertInstanceOf(UniqueEntity::class, $classConstraints[0]); | ||
$this->assertInstanceOf(UniqueEntity::class, $classConstraints[1]); | ||
$this->assertSame(['alreadyMappedUnique'], $classConstraints[0]->fields); | ||
$this->assertSame('unique', $classConstraints[1]->fields); | ||
|
||
$maxLengthMetadata = $classMetadata->getPropertyMetadata('maxLength'); | ||
$this->assertCount(1, $maxLengthMetadata); | ||
$maxLengthConstraints = $maxLengthMetadata[0]->getConstraints(); | ||
$this->assertCount(1, $maxLengthConstraints); | ||
$this->assertInstanceOf(Length::class, $maxLengthConstraints[0]); | ||
$this->assertSame(20, $maxLengthConstraints[0]->max); | ||
|
||
$mergedMaxLengthMetadata = $classMetadata->getPropertyMetadata('mergedMaxLength'); | ||
$this->assertCount(1, $mergedMaxLengthMetadata); | ||
$mergedMaxLengthConstraints = $mergedMaxLengthMetadata[0]->getConstraints(); | ||
$this->assertCount(1, $mergedMaxLengthConstraints); | ||
$this->assertInstanceOf(Length::class, $mergedMaxLengthConstraints[0]); | ||
$this->assertSame(20, $mergedMaxLengthConstraints[0]->max); | ||
$this->assertSame(5, $mergedMaxLengthConstraints[0]->min); | ||
|
||
$alreadyMappedMaxLengthMetadata = $classMetadata->getPropertyMetadata('alreadyMappedMaxLength'); | ||
$this->assertCount(1, $alreadyMappedMaxLengthMetadata); | ||
$alreadyMappedMaxLengthConstraints = $alreadyMappedMaxLengthMetadata[0]->getConstraints(); | ||
$this->assertCount(1, $alreadyMappedMaxLengthConstraints); | ||
$this->assertInstanceOf(Length::class, $alreadyMappedMaxLengthConstraints[0]); | ||
$this->assertSame(10, $alreadyMappedMaxLengthConstraints[0]->max); | ||
$this->assertSame(1, $alreadyMappedMaxLengthConstraints[0]->min); | ||
} | ||
|
||
/** | ||
* @dataProvider regexpProvider | ||
*/ | ||
public function testClassValidator(bool $expected, string $classValidatorRegexp = null) | ||
{ | ||
$doctrineLoader = new DoctrineLoader(DoctrineTestHelper::createTestEntityManager(), $classValidatorRegexp); | ||
|
||
$classMetadata = new ClassMetadata(DoctrineLoaderEntity::class); | ||
$this->assertSame($expected, $doctrineLoader->loadClassMetadata($classMetadata)); | ||
} | ||
|
||
public function regexpProvider() | ||
{ | ||
return [ | ||
[true, null], | ||
[true, '{^'.preg_quote(DoctrineLoaderEntity::class).'$|^'.preg_quote(Entity::class).'$}'], | ||
[false, '{^'.preg_quote(Entity::class).'$}'], | ||
]; | ||
} | ||
} |
121 changes: 121 additions & 0 deletions
121
src/Symfony/Bridge/Doctrine/Validator/DoctrineLoader.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Bridge\Doctrine\Validator; | ||
|
||
use Doctrine\Common\Persistence\Mapping\MappingException; | ||
use Doctrine\ORM\EntityManagerInterface; | ||
use Doctrine\ORM\Mapping\ClassMetadataInfo; | ||
use Doctrine\ORM\Mapping\MappingException as OrmMappingException; | ||
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; | ||
use Symfony\Component\Validator\Constraints\Length; | ||
use Symfony\Component\Validator\Mapping\ClassMetadata; | ||
use Symfony\Component\Validator\Mapping\Loader\LoaderInterface; | ||
|
||
/** | ||
* Guesses and loads the appropriate constraints using Doctrine's metadata. | ||
* | ||
* @author Kévin Dunglas <dunglas@gmail.com> | ||
*/ | ||
final class DoctrineLoader implements LoaderInterface | ||
{ | ||
private $entityManager; | ||
private $classValidatorRegexp; | ||
|
||
public function __construct(EntityManagerInterface $entityManager, string $classValidatorRegexp = null) | ||
{ | ||
$this->entityManager = $entityManager; | ||
$this->classValidatorRegexp = $classValidatorRegexp; | ||
} | ||
|
||
/** | ||
* {@inheritdoc} | ||
*/ | ||
public function loadClassMetadata(ClassMetadata $metadata): bool | ||
{ | ||
$className = $metadata->getClassName(); | ||
if (null !== $this->classValidatorRegexp && !preg_match($this->classValidatorRegexp, $className)) { | ||
return false; | ||
} | ||
|
||
try { | ||
$doctrineMetadata = $this->entityManager->getClassMetadata($className); | ||
} catch (MappingException | OrmMappingException $exception) { | ||
return false; | ||
} | ||
|
||
if (!$doctrineMetadata instanceof ClassMetadataInfo) { | ||
return false; | ||
} | ||
|
||
/* Available keys: | ||
- type | ||
- scale | ||
- length | ||
- unique | ||
- nullable | ||
- precision | ||
*/ | ||
$existingUniqueFields = $this->getExistingUniqueFields($metadata); | ||
|
||
// Type and nullable aren't handled here, use the PropertyInfo Loader instead. | ||
foreach ($doctrineMetadata->fieldMappings as $mapping) { | ||
if (true === $mapping['unique'] && !isset($existingUniqueFields[$mapping['fieldName']])) { | ||
$metadata->addConstraint(new UniqueEntity(['fields' => $mapping['fieldName']])); | ||
} | ||
|
||
if (null === $mapping['length']) { | ||
continue; | ||
} | ||
|
||
$constraint = $this->getLengthConstraint($metadata, $mapping['fieldName']); | ||
if (null === $constraint) { | ||
$metadata->addPropertyConstraint($mapping['fieldName'], new Length(['max' => $mapping['length']])); | ||
} elseif (null === $constraint->max) { | ||
// If a Length constraint exists and no max length has been explicitly defined, set it | ||
$constraint->max = $mapping['length']; | ||
} | ||
} | ||
|
||
return true; | ||
} | ||
|
||
private function getLengthConstraint(ClassMetadata $metadata, string $fieldName): ?Length | ||
{ | ||
foreach ($metadata->getPropertyMetadata($fieldName) as $propertyMetadata) { | ||
foreach ($propertyMetadata->getConstraints() as $constraint) { | ||
if ($constraint instanceof Length) { | ||
return $constraint; | ||
} | ||
} | ||
} | ||
|
||
return null; | ||
} | ||
|
||
private function getExistingUniqueFields(ClassMetadata $metadata): array | ||
{ | ||
$fields = []; | ||
foreach ($metadata->getConstraints() as $constraint) { | ||
if (!$constraint instanceof UniqueEntity) { | ||
continue; | ||
} | ||
|
||
if (\is_string($constraint->fields)) { | ||
$fields[$constraint->fields] = true; | ||
} elseif (\is_array($constraint->fields) && 1 === \count($constraint->fields)) { | ||
$fields[$constraint->fields[0]] = true; | ||
} | ||
} | ||
|
||
return $fields; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.