Translator.php
3 years ago
ValidationException.php
2 months ago
ValidatorFactory.php
3 years ago
index.php
3 years ago
ValidatorFactory.php
47 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\Doctrine\Validator; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Doctrine\Annotations\AnnotationReaderProvider; |
| 9 | use MailPoet\Doctrine\PSRMetadataCache; |
| 10 | use MailPoetVendor\Symfony\Component\Validator\Validation; |
| 11 | |
| 12 | class ValidatorFactory { |
| 13 | const METADATA_DIR = __DIR__ . '/../../../generated/validator-metadata'; |
| 14 | |
| 15 | /** @var AnnotationReaderProvider */ |
| 16 | private $annotationReaderProvider; |
| 17 | |
| 18 | public function __construct( |
| 19 | AnnotationReaderProvider $annotationReaderProvider |
| 20 | ) { |
| 21 | $this->annotationReaderProvider = $annotationReaderProvider; |
| 22 | } |
| 23 | |
| 24 | public function createValidator() { |
| 25 | $builder = Validation::createValidatorBuilder(); |
| 26 | // we need to use our own translator here. |
| 27 | // If we let the default translator to be used in the builder it uses an anonymous class and that is a problem |
| 28 | // All integration tests would fail with: [Exception] Serialization of 'class@anonymous' is not allowed |
| 29 | $translator = new Translator(); |
| 30 | $translator->setLocale('en'); |
| 31 | $builder->setTranslator($translator); |
| 32 | |
| 33 | // annotation reader exists only in dev environment, on production cache is pre-generated |
| 34 | $annotationReader = $this->annotationReaderProvider->getAnnotationReader(); |
| 35 | if ($annotationReader) { |
| 36 | $builder->setDoctrineAnnotationReader($annotationReader) |
| 37 | ->enableAnnotationMapping(true); |
| 38 | } |
| 39 | |
| 40 | // metadata cache (for production cache is pre-generated at build time) |
| 41 | $isReadOnly = !$annotationReader; |
| 42 | $builder->setMappingCache(new PSRMetadataCache(self::METADATA_DIR, $isReadOnly)); |
| 43 | |
| 44 | return $builder->getValidator(); |
| 45 | } |
| 46 | } |
| 47 |