Explorar el Código

[Doctrine] Add Unique Validator

Benjamin Eberlei hace 14 años
padre
commit
cfc2471109

+ 31 - 0
src/Symfony/Bridge/Doctrine/Validator/UniqueEntity.php

@@ -0,0 +1,31 @@
+<?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 Symfony\Component\Validator\Constraint;
+use Symfony\Component\Validator\ConstraintValidator;
+use Symfony\Component\Validator\Exception\UnexpectedTypeException;
+
+class UniqueEntity extends \Symfony\Component\Validator\Constraint
+{
+    public $message = 'This value is already used.';
+    public $entityManagerName = false;
+    public $fields = array();
+    
+    /**
+     * {@inheritDoc}
+     */
+    public function getTargets()
+    {
+        return self::CLASS_CONSTRAINT;
+    }
+}

+ 48 - 0
src/Symfony/Bridge/Doctrine/Validator/UniqueEntityValidator.php

@@ -0,0 +1,48 @@
+<?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;
+
+class UniqueEntityValidator extends ConstraintValidator
+{
+    /**
+     * @var Registry
+     */
+    private $registry;
+    
+    public function __construct(Registry $registry)
+    {
+        $this->registry = $registry;
+    }
+    
+    public function isValid($entity, Constraint $constraint)
+    {
+        $emName = $constraint->entityManagerName ?: $this->registry->getDefaultConnectionName();
+        $em = $this->registry->getEntityManager($emName);
+        
+        $className = $this->context->getCurrentClass();
+        $class = $em->getClassMetadata($className);
+        
+        $criteria = array();
+        foreach ($contraint->fields AS $fieldName) {
+            $criteria[$fieldName] = $class->reflFields[$fieldName]->getValue($entity);
+        }
+        
+        $repository = $em->getRepository($className);
+        $result = $repository->findBy($criteria);
+        
+        if (count($result) > 0 && $result[0] !== $entity) {
+            $this->setMessage($constraint->message);
+            return false;
+        }
+        return true;
+    }
+}

+ 9 - 0
src/Symfony/Component/Validator/ConstraintValidator.php

@@ -13,8 +13,17 @@ namespace Symfony\Component\Validator;
 
 abstract class ConstraintValidator implements ConstraintValidatorInterface
 {
+    /**
+     * @var ExecutionContext
+     */
     protected $context;
+    /**
+     * @var string
+     */
     private $messageTemplate;
+    /**
+     * @var array
+     */
     private $messageParameters;
 
     /**