Symfony" Type"约束:类型"字符串","数组"的预期参数;给予例外

时间:2017-06-16 17:25:27

标签: php symfony symfony-forms

我有一张表格。例如,它的登录表单:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('phone', TextType::class, [
        'constraints' => [
            new NotBlank(),
            new Type(['type' => 'string']),
            new Length(['max' => 255]),
            new ValueExistsInEntity([
                'entityClass' => User::class,
                'field' => 'phone',
                'message' => 'User not found'
            ])
        ]
    ]);
    $builder->add('password', TextType::class, [
        'constraints' => [
            new NotBlank(),
            new Type(['type' => 'string']),
            new Length(['min' => 8, 'max' => 128])
        ]
    ]);
}

如您所见,它有Length约束。当我将数组发送到表单中的任何字段时,Length约束会抛出Symfony\\Component\\Validator\\Exception\\UnexpectedTypeException和500状态代码并显示消息:

  

类型"字符串","数组"的预期参数给定

有没有办法避免这种情况或将此异常转换为表单验证错误?

2 个答案:

答案 0 :(得分:0)

我发现只有解决方案才能创建事件监听器,只是将异常转换为美容错误(对我来说没关系,因为我只开发API,而不是完整堆栈)。

我的异常事件监听器的简化部分:

namespace AppBundle\EventListener;

use AppBundle\Exceptions\FormValidationException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\Validator\Exception\ValidatorException;

class ApiExceptionListener
{
    /**
     * @var bool
     */
    public $isKernelDebug;

    public function __construct(bool $isKernelDebug)
    {
        $this->isKernelDebug = $isKernelDebug;
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $throwedException = $event->getException();

        $errorBody = [
            'code'    => $throwedException->getCode(),
            'message' => $throwedException->getMessage(),
        ];

        if ($throwedException instanceof ValidatorException) {
            $errorBody['message'] = 'Invalid data has been sent';
        }

        if ($this->isKernelDebug) {
            $errorBody['exception'] = [
                'class'   => get_class($throwedException),
                'message' => $throwedException->getMessage(),
                'code'    => $throwedException->getCode(),
            ];
        }

        $event->setResponse(new JsonResponse(['error' => $errorBody]));
    }
}

服务:

app.event_listener.api_exception:
    class: AppBundle\EventListener\ApiExceptionListener
    arguments: ['%%kernel.debug%%']
    tags:
        - { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 200 }

但我很高兴看到更好的解决方案来处理从Symfony约束中抛出的异常。

答案 1 :(得分:-1)

因为Length仅是字符串的验证器。对于数组,您必须使用Count验证程序。

如果要在同一验证器中同时使用数组和字符串,则应实现自己的Custom validator