2017-09-13 2 views
1

정적 콜백을 통해 내 엔티티의 유효성을 검사하려고합니다.Symfony 확인 콜백

나는 Symfony guide에 따라 작동하게 만들었지 만 나에게 명확하지 않은 것이 있습니다. 나는 그것이 "동적"만들고 싶어 내 $fakeNames 배열하지만 무엇을 채울 때

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() 
     ; 
    } 
} 

그것은 잘 작동? 매개 변수 나 데이터베이스 또는 어디에서나 배열을 선택하려고한다고 가정 해 봅시다. 생성자가 작동하지 않고 반드시 정적이어야하는 순간부터 어떻게이 클래스에 물건 (예 : 컨테이너 또는 entityManager)을 전달해야합니까?

물론 내 방식이 완전히 잘못되었을 수도 있지만 심포니 예제와 인터넷에서 발견 된 몇 가지 다른 유사한 문제를 사용하여 내 사례에 적응하려고합니다.

답변

3

당신은 제약을 생성하고 검사기 당신이 EntityManager를 주입하거나 당신이 필요로하는 무엇이든, 당신은 여기에 더 많은 읽을 수 있도록 서비스로 등록 할 수 있습니다

https://symfony.com/doc/2.8/validation/custom_constraint.html

을하거나 심포니 3.3에있는 경우가있다 이미 서비스이고 그냥 생성자에 입력하면됩니다. https://symfony.com/doc/current/validation/custom_constraint.html

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 hat 역할은 매개 변수에 설정된 역할 중 하나 여야합니다. 그렇지 않은 경우 위반이됩니다.