predaddy/predaddy-symfony-validator

predaddy 的 Symfony 验证组件

dev-master 2014-11-09 09:54 UTC

This package is not auto-updated.

Last update: 2024-09-10 03:19:14 UTC


README

Latest Stable Version Scrutinizer Code Quality SensioLabsInsight Gitter chat

此库提供的 ValidationInterceptor 帮助验证发送到 predaddy MessageBus 的消息。它基于 Symfony Validator 组件。

使用方法

$bus = SimpleMessageBus::builder()
    ->withInterceptors([new ValidatorInterceptor()])
    ->build();
class CreateUser
{
    /**
     * @Assert\Length(min = 3)
     * @Assert\NotBlank
     */
    private $name;

    /**
     * @Assert\Email
     * @Assert\NotBlank
     */
    private $email;

    public function __construct($name, $email)
    {
        $this->name = $name;
        $this->email = $email;
    }

    /**
     * @Assert\True(message = "The user should have a Google Mail account")
     */
    public function isGmailUser()
    {
        return false !== strpos($this->email, '@gmail.com');
    }

    public function __toString()
    {
        return Objects::toStringHelper($this)
            ->add('name', $this->name)
            ->add('email', $this->email)
            ->toString();
    }
}
try {
    $bus->post(new CreateUser('John Doe', 'john@example.com'));
} catch (ValidationException $e) {
    $e->getViolationList();
}

如果您使用注解约束,请务必注册其命名空间

AnnotationRegistry::registerAutoloadNamespace('Symfony\Component\Validator\Constraint', 'path/to/symfony/library/validator');