atasciuc/zend-expressive-validation

为zend-expressive提供的PSR-7验证中间件

1.0.1 2016-03-11 15:39 UTC

This package is not auto-updated.

Last update: 2024-09-24 19:29:15 UTC


README

为zend-expressive提供验证库 (http://zend-expressive.readthedocs.org/en/latest)

安装

使用composer!

composer require atasciuc/zend-expressive-validation

用法

1. ----

创建验证器工厂

/**
 * Instantiates the validator
 * Class YourValidatorFactoryClass
 */
class YourValidatorFactoryClass
{
    public function __invoke(ContainerInterface $container)
    {
        /** @var EntityManagerInterface $entityManager */
        $entityManager = $container->get('orm.default'); // = null
        return new Validator(
            $container->get(OptionsExtractor::class),
            $container->get(RouterInterface::class),
            $entityManager
        );
    }
}

注意

entityManager是可选的,仅在您想使用数据库验证类(如EntityExist)时才需要

2. ----

将验证器类添加到项目的dependencies.php

<?php

use ExpressiveValidator\Middleware\ErrorMiddleware;
use ExpressiveValidator\Validator\OptionExtractorFactory;
use ExpressiveValidator\Validator\OptionsExtractor;
use ExpressiveValidator\Validator\ValidationMiddleware;
use ExpressiveValidator\Validator\ValidationMiddlewareFactory;
use ExpressiveValidator\Validator\Validator;

return [
    'dependencies' => [
        'abstract_factories' => [
        ],
        'invokables' => [
            ErrorMiddleware::class => ErrorMiddleware::class,
        ],
        'factories' => [
            Zend\Expressive\Application::class => Zend\Expressive\Container\ApplicationFactory::class,
            OptionsExtractor::class => OptionExtractorFactory::class,
            Validator::class => YourValidatorFactoryClass::class,
            ValidationMiddleware::class => ValidationMiddlewareFactory::class,
        ],
        'shared' => [
        ]
    ]
];

3. ----

编辑您的middleware-pipeline.global并注册验证中间件

<?php   
use ExpressiveValidator\Middleware\ErrorMiddleware;
use ExpressiveValidator\Validator\ValidationMiddleware;

return [
    // This can be used to seed pre- and/or post-routing middleware
    'middleware_pipeline' => [
        // An array of middleware to register prior to registration of the
        // routing middleware
        'pre_routing' => [
            [
                'middleware' => ValidationMiddleware::class,
            ],
            //[
            // Required:
            //    'middleware' => 'Name of middleware service, or a callable',
            // Optional:
            //    'path'  => '/path/to/match',
            //    'error' => true,
            //],
        ],

        // An array of middleware to register after registration of the
        // routing middleware
        'post_routing' => [
            [
                'middleware' => ErrorMiddleware::class,
                'error'      => true
            ],
            //[
            // Required:
            //    'middleware' => 'Name of middleware service, or a callable',
            // Optional:
            //    'path'  => '/path/to/match',
            //    'error' => true,
            //],
        ],
    ],
];

注意

或者,您可以添加自己的ErrorMiddleware并在依赖中注册它,以下提供了一个示例

class ErrorMiddleware
{
    /**
     * @param mixed $error
     * @param Request $request
     * @param Response $response
     * @param callable|null $out
     * @return
     * @throws Exception
     */
    public function __invoke($error, Request $request, Response $response, callable $out = null)
    {
        if (!($error instanceof Exception)) {
            $error = new MethodNotAllowedException();
        }
        switch (true) {
            case $error instanceof MethodNotAllowedException || $error instanceof EntityNotFoundException:
                return $out($request, new JsonExceptionResponse($error->getCode(), $error->getMessage()));
            case ($error instanceof ValidationFailedException):
                $messages = $error->getValidationResult()->getMessages();
                return $out($request, new JsonExceptionResponse(
                    $error->getCode(),
                    count($messages) > 0 ? $messages[0] : 'Something is not right'
                ));
            default:
                throw $error;
        }
    }
}

4. ----

将验证添加到路由中

'routes' => [
        [
            'name' => 'user',
            'path' => '/user/{id}',
            'allowed_methods' => ['GET'],
            'middleware' => UserAction::class,
            'options' => [
                'validation' =>  [
                    'GET' => GetUserValidationRules::class
                ]
            ]
        ]
    ],

验证可以应用于http方法或所有方法

'options' => [
        'validation' =>  [
            '*' => GetUserValidationRules::class
        ]
    ]

验证规则类必须符合以下要求 - ValidationRulesInterface

验证规则的示例

class GetUserValidationRules implements ValidationRulesInterface
{
    use ValidationRulesConstructorTrait;

    /**
     * Return a class mapping
     * of the validations
     * @return \array[] mixed
     */
    public function getValidationRules()
    {
        return [
            'id' => [
                NotEmpty::class => [
                    'locale' => 'en'
                ],
                Regex::class => [
                    'pattern' => $this->idRegex
                ],
                EntityExist::class => [
                    'entity' => User::class,
                    'field' => 'id'
                ]
            ]
        ];
    }

    /**
     * Return the error messages
     * @return array [] mixed
     */
    public function getMessages()
    {
        return [
            'id' => [
                NotEmpty::class => 'Please provide the user',
                Regex::class => 'user id must have the following pattern xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
                EntityExist::class => 'This user does not exist'
            ]
        ];
    }
}

5. ----

现在您可以在操作中提取验证后的数据

 public function __invoke(Request $request, Response $response, callable $next = null)
    {
        $data = $request->getValidationResult()->getData();

        return $next($request, new JsonResponse($data));
    }

就是这样

待办事项

[] - 为验证类添加文档