symfony - How to validate data in a custom controler
问题描述
I created a Entity with a custom contoller:
// api/src/Entity/UserRegistration.php
namespace App\Entity;
use ...
/**
* UserRegistraion Data
*
* @ApiResource(collectionOperations={},itemOperations={"post"={
* "method"="POST",
* "path"="/register",
* "controller"=CreateUser::class}})
*
*/
class UserRegistration
{
.....
/**
* @var string The E-mail
*
* @Assert\NotBlank
* @Assert\Email(
* message = "The email '{{ value }}' is not a valid email.",
* checkMX = true
* )
*/
public $email;
.....
And a custom Controller:
// api/src/Controller/CreateUser.php
class CreateUser
{
.....
public function __invoke(UserRegistration $data): UserRegistration
{
return $data;
}
}
When I call the controller with wrong data (e.g wrong email-address) I would expect an validation error, but it is not checked.
Is there a way to do this?
解决方案
Api 平台对控制器的结果进行验证,以确保您的数据持久化者将收到正确的信息。因此,您在进入控制器时可能会得到无效数据,如果您的操作需要有效对象,则需要手动执行验证。
最常见的方法是使用提供验证等功能的表单,或者仅使用验证器作为独立组件。在您的情况下,您 - 因为正在使用 ApiPlatform - 后者将是更好的选择,因为您不需要将表单呈现给用户,而是返回错误响应。
首先,您需要将验证器注入您的控制器:
use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class CreateUser
{
private $validator;
public function __construct(ValidatorInterface $validator)
{
$this->validator = $validator;
}
public function __invoke(UserRegistration $data): UserRegistration
{
$errors = $this->validator->validate($data);
if (count($errors) > 0) {
throw new ValidationException($errors);
}
return $data;
}
}
您还可以通过查看ValidateListener来检查 ApiPlatform 是如何做到的。它提供了一些附加功能,例如验证组,此时您似乎不需要这些功能,但以后可能会感兴趣。然后,ApiPlatform 将使用其ValidationExceptionListener对您抛出的异常做出反应并适当地呈现它。