2017-09-13 125 views
1

我想通過靜態回調驗證我的實體。Symfony驗證回調

我能夠使它在Symfony guide之後工作,但有些事情對我而言並不清楚。

public static function validate($object, ExecutionContextInterface $context, $payload) 
{ 
    // somehow you have an array of "fake names" 
    $fakeNames = array(/* ... */); 

    // check if the name is actually a fake name 
    if (in_array($object->getFirstName(), $fakeNames)) { 
     $context->buildViolation('This name sounds totally fake!') 
      ->atPath('firstName') 
      ->addViolation() 
     ; 
    } 
} 

當我填充我$fakeNames數組,但如果我想使其「動態」它工作正常?比方說,我想從參數或數據庫或任何地方選擇該數組。 我該如何從構造函數不工作的時候將東西(比如容器或entityManager)傳遞給這個類,它必須是靜態的?

當然,我的方法可能是完全錯誤的,但我只是使用symfony示例以及在互聯網上發現的幾個其他類似問題,我試圖適應我的情況。

回答

1

感謝這是我最終能找到的解決方案。 它工作順利,我希望它可能對別人有用。

我給自己定的約束我validation.yml

User\UserBundle\Entity\Group: 
    constraints: 
     - User\UserBundle\Validator\Constraints\Roles\RolesConstraint: ~ 

這裏是我RolesConstraint類

namespace User\UserBundle\Validator\Constraints\Roles; 

use Symfony\Component\Validator\Constraint; 

class RolesConstraint extends Constraint 
{ 
    /** @var string $message */ 
    public $message = 'The role "{{ role }}" is not recognised.'; 

    public function getTargets() 
    { 
     return self::CLASS_CONSTRAINT; 
    } 
} 

,這裏是我的RolesConstraintValidator類

<?php 

namespace User\UserBundle\Validator\Constraints\Roles; 

use Symfony\Component\DependencyInjection\ContainerInterface; 
use Symfony\Component\Validator\Constraint; 
use Symfony\Component\Validator\ConstraintValidator; 

class RolesConstraintValidator extends ConstraintValidator 
{ 
    /** @var ContainerInterface */ 
    private $containerInterface; 

    /** 
    * @param ContainerInterface $containerInterface 
    */ 
    public function __construct(ContainerInterface $containerInterface) 
    { 
     $this->containerInterface = $containerInterface; 
    } 

    /** 
    * @param \User\UserBundle\Entity\Group $object 
    * @param Constraint $constraint 
    */ 
    public function validate($object, Constraint $constraint) 
    { 
     if (!in_array($object->getRole(), $this->containerInterface->getParameter('roles'))) { 
      $this->context 
       ->buildViolation($constraint->message) 
       ->setParameter('{{ role }}', $object->getRole()) 
       ->addViolation(); 
     } 
    } 
} 

從本質上講,我成立每當新用戶用戶與角色一起註冊時,約束條件爲t帽子角色必須在參數中設置。如果不是,則會造成違規。