Combine constraints and data transformers

后端 未结 1 1616
暖寄归人
暖寄归人 2020-12-06 11:26

I would like to do something looking like what is done in How to use Data Transformers tutorial. But I would like to add a process and I can\'t find any example.

In

相关标签:
1条回答
  • 2020-12-06 11:30

    This is like a workaround, however I suggest writing the class that represents "an invalid issue" to personalize error.

    class InvalidIssue extends Issue
    {
        public $message = 'This issue is invalid';
    
        public function __construct($message = null)
        {
            if (null !== $message) {
                $this->message = $message;
            }
        }
    }
    

    and in the transformer, if given value is invalid, return InvalidIssue object instead of throwing an exception.

    public function reverseTransform($id)
    {
        if (!$number) {
            return null;
        }
    
        $issue = $this->dm
            ->getRepository('AcmeTaskBundle:Issue')
            ->find(new \MongoId($id))
        ;
    
        if (null === $issue) {
            return new InvalidIssue(sprintf(
                'An issue with number "%s" does not exist!',
                $number
            ));
        }
    
        return $issue;
    }
    

    then, add validator onto your model.

    /** Assert\Callback("callback"="validateIssueIsValid") */
    class YourModel
    {
        protected $issue;
    
        public function setIssue(Issue $issue)
        {
            $this->issue = $issue;
        }
    
        public function validateIssueIsValid(ExecutionContextInterface $context)
        {
            if ($this->issue instanceof InvalidIssue) {
                $context->addViolationAt('issue', $this->issue->message, array());
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题