1

我正在尝试按照本教程添加帖子参数验证:https ://odan.github.io/2020/10/08/slim4-respect-validation.html

我添加了一个库,并使用它:

private function validateProperty(array $data): void
{

    $validator = new v();

    $validator->addRule(v::key('name', v::allOf(
        v::notEmpty()->setTemplate('The property name must not be empty'),
        v::length(3, 150)->setTemplate('Invalid length')
    ))->setTemplate('The key "Name" is required'));
    
    $validator->addRule(v::key('address', v::allOf(
        v::notEmpty()->setTemplate('The address must not be empty'),
        v::length(3, 50)->setTemplate('Invalid length')
    ))->setTemplate('The key "address" is required'));        
    

    $validator->addRule(v::key('original_name', v::allOf(
        v::notEmpty()->setTemplate('The original_name must not be empty'),
        v::length(3, 255)->setTemplate('Invalid length')            
    ), false));

   $validator->assert($data);


}

现在,如果我发送了正确的值,一切正常。例如,当我发送不正确的名称时,抛出错误(500):

Type: Respect\Validation\Exceptions\ValidatorException
Code: 0
Message: These rules must pass for `{ "name": "tx", "address": "street1", "original_name": "Original" }`
File: C:\MAMP\htdocs\api2\vendor\respect\validation\library\Factory.php
Line: 235

在这里我不知道如何获取无效名称的消息,而不是这个一般的消息错误。

好的,在我在 src/middleware/RespectValidationMiddleware.php 上创建中间件之后。

<?php

namespace App\Middleware;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Respect\Validation\Exceptions\NestedValidationException;

final class RespectValidationMiddleware implements MiddlewareInterface
{
    /**
     * @var ResponseFactoryInterface
     */
    private $responseFactory;

    /**
     * The constructor.
     *
     * @param ResponseFactoryInterface $responseFactory The response factory
     */
    public function __construct(ResponseFactoryInterface $responseFactory)
    {
        $this->responseFactory = $responseFactory;
    }

    /**
     * Invoke middleware.
     *
     * @param ServerRequestInterface $request The request
     * @param RequestHandlerInterface $handler The handler
     *
     * @return ResponseInterface The response
     */
    public function process(
        ServerRequestInterface $request, 
        RequestHandlerInterface $handler
    ): ResponseInterface {
        try {
            return $handler->handle($request);
        } catch(NestedValidationException $exception) {
            $messages = [];
            /** @var ValidationException $message */
            foreach($exception->getIterator() as $message) {
                $key = $message->getParam('name');
                if($key === null) {
                    continue;
                }
                $messages[$key] = $message->getMessage();
            }
            
            $response = $this->responseFactory->createResponse();
        
            $result = [
                'error' => [
                    'message' => $exception->getMessage(),
                    'details' => $messages,
                ],
            ];
            $response->getBody()->write(json_encode($result));
            $response->withHeader('Content-Type', 'application/json');

            return $response->withStatus(422);
        }
    }
}

并尝试在错误中间件后添加:

<?php

use Selective\BasePath\BasePathMiddleware;
use Slim\App;
use Slim\Middleware\ErrorMiddleware;
use App\Middleware\RespectValidationMiddleware;

return function (App $app) {
    // Parse json, form data and xml
    $app->addBodyParsingMiddleware();

    // Add the Slim built-in routing middleware
    $app->addRoutingMiddleware();

    $app->add(BasePathMiddleware::class);

    // Catch exceptions and errors
    $app->add(ErrorMiddleware::class);

    $app->add(RespectValidationMiddleware::class); // <-- here

};

RespectValidationMiddleware 行,当我尝试发布数据时导致 500 错误,没有错误消息。

我读到尊重/验证抛出一个 NestedValidationException,但在第一次尝试中我得到了一个 ValidatorException。不知道会不会有问题。。

4

1 回答 1

0

删除中间件并尝试$validator->check($data);.

于 2021-03-22T22:04:27.590 回答