浏览代码

merged branch blogsh/constraints (PR #1393)

Commits
-------

2f78a44 Changed recognition of constraints in annoations

Discussion
----------

[Validator] Changed recognition of constraints in annotations

I accidently added a constraint to a setter method of an entity:

    /**
     * @Assert\MinLength(2)
     */
    public function setName($name)
    { ... }

The result was that the framework generated the following exception:

     Neither method getTName nor isTName exists in class Blogsh\TestBundle\Entity\User

The problem is that ClassMetadata::addGetterConstraint is called even if the inspected method isn't a getter or an isser.The fix changes the behaviour so that an exception is thrown, saying that it is not valid to add a constraint there. I'm not sure whether this is the right way to handle that problem. It would also be possible to remove the exception and just ignore constraints added to inapplicable methods.
However, the fix prevents the strange error messages from the user.
Fabien Potencier 14 年之前
父节点
当前提交
462070058a
共有 1 个文件被更改,包括 5 次插入4 次删除
  1. 5 4
      src/Symfony/Component/Validator/Mapping/Loader/AnnotationLoader.php

+ 5 - 4
src/Symfony/Component/Validator/Mapping/Loader/AnnotationLoader.php

@@ -60,11 +60,12 @@ class AnnotationLoader implements LoaderInterface
         foreach ($reflClass->getMethods() as $method) {
             if ($method->getDeclaringClass()->getName() ==  $className) {
                 foreach ($this->reader->getMethodAnnotations($method) as $constraint) {
-                    // TODO: clean this up
-                    $name = lcfirst(substr($method->getName(), 0, 3)=='get' ? substr($method->getName(), 3) : substr($method->getName(), 2));
-
                     if ($constraint instanceof Constraint) {
-                        $metadata->addGetterConstraint($name, $constraint);
+                        if (preg_match( '/^(get|is)(.+)$/', $method->getName(), $matches)) {
+                            $metadata->addGetterConstraint(lcfirst($matches[2]), $constraint);
+                        } else {
+                            throw new MappingException( sprintf( 'Cannot add constraint to %s::%s', $className, $method->getName() ) );
+                        }
                     }
 
                     $loaded = true;