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

それが正常に動作しますか?その配列をパラメータから、またはデータベースから、またはどこからでも選択したいとしましょう。 コンストラクタが動作せず、静的でなければならない時から、このクラスに物(コンテナやエンティティなど)を渡す方法を教えてください。

私のアプローチは完全に間違っているかもしれませんが、私はちょうどsymfonyの例と私の場合に適応しようとしているインターネット上のいくつかの同様の問題を使用しています。

答えて

3

あなたはEntityManagerのか、あなたが必要なものを注入することができますので、あなたはここで多くを読むことができ制約とバリデータを作成し、それをサービスとして登録することができます

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

か、symfonyの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の役割は、パラメータに設定されているものの中になければなりません。そうでなければ、それは違反を作ります。