Cannot read annotation when using Symfony Validator as standalone

I get this error:

Message: "[Semantical Error] The annotation "@Symfony\Component\Validator\Constraints\Length" in property 

User :: $ name does not exist or cannot be automatically loaded.

This is the code on Github https://github.com/symfony/Validator

 use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Constraints as Assert; class User { /** * @Assert\Length(min = 3) * @Assert\NotBlank */ private $name; /** * @Assert\Email * @Assert\NotBlank */ private $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } /** * @Assert\True(message = "The user should have a Google Mail account") */ public function isGmailUser() { return false !== strpos($this->email, '@gmail.com'); } } $validator = Validation::createValidatorBuilder() ->enableAnnotationMapping() ->getValidator(); $user = new User('John Doe', ' john@example.com '); $violations = $validator->validate($user); 

How can I fix this problem?

+4
source share
6 answers

Doctrine does not use autoload PHP, you must register with autoloadRegistry:

 AnnotationRegistry::registerAutoloadNamespace("Symfony\Component\Validator\Constraint", "path/to/symfony/library/validator"); 
+5
source

use Symfony \ Component \ Validator \ Constraints as Assert;

  /** * @var float $weight * * @ORM\Column(name="weight", type="decimal",precision=3,scale=2, nullable=true) * * @Assert\Range( * min = "90", * max = "350", * minMessage = "You must weight at least 90", * maxMessage = "You cannot weight more than 300" * ) * @Assert\NotBlank(groups={"group one","goup 2"}) * @Assert\Regex(pattern= "/[0-9]/",message="Require number only") */ private $weight=0; 
+4
source

A length limit has been added in Symfony 2.1, so you won’t be able to use it if you use Symfony 2.0.

See documentation for length limits .

0
source

There is a bug in PHP and Doctrine, and sometimes it gets confused with use . You must add a PHPDoc comment to the class declaration, and this error will disappear.

0
source

If you use Symfony / validator as standalone, you must manually register the validator namespace

 $loader = require 'vendor/autoload.php'; AnnotationRegistry::registerLoader([$loader, 'loadClass']); 
0
source

Using composer, instead of manually registering the validator namespace, you can simply do

composer require validator

0
source

Source: https://habr.com/ru/post/1434572/


All Articles