mojtaba-gheytasi/request-validator-bundle 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mojtaba-gheytasi/request-validator-bundle

Composer 安装命令:

composer require mojtaba-gheytasi/request-validator-bundle

包简介

Symfony bundle for validating request parameters in a clean structure

README 文档

README

Symfony Request Validator Bundle

Scrutinizer Code Quality Build Status

What does it do? :)

This bundle allows you to validate request parameters based on your constraints and restrictions via request classes that contain validation logic.

Installation

composer require mojtaba-gheytasi/request-validator-bundle

Compatibility

  • PHP v7.4 or above
  • Symfony v4.4 or above

Usage

Suppose you want to validate incoming request parameters as follows:

//Get api/product/search?brand=gucci&price[min]=100&price[max]=1000
[
    'brand' => 'gucci',
    'price' => [
        'min' => 100,
        'max' => 1000,
    ],
];

To start, create a request class by following command:

$ bin/console make:request SearchProduct

NOTE: Creates SearchProductRequest.php in src/Request.

Now add your validation constraints to the constraints method:

<?php

namespace App\Request;

use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Positive;
use MojtabaGheytasi\RequestValidatorBundle\Request\RequestWithValidation;

class SearchProductRequest extends RequestWithValidation
{
    /**
     * Get the validation constraints that apply to the request.
     */
    protected function constraints(): array
    {
        return [
            'brand' => [
                new Length(['min' => 2]),
                new Type('string'),
            ],
            'price'  => new Collection([
                'fields' => [
                    'min' => [
                        new Type('integer'),
                        new Positive(),
                    ],
                    'max' => [
                        new Type('integer'),
                        new Positive(),
                    ],
                ],
            ]),
        ];
    }
}

So, how are the validation constraints evaluated? All you need to do is type-hint the request on your controller method. The incoming request data is validated before the controller method is called, meaning you do not need to clutter your controller with validation logic:

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class ProductController 
{
    public function search(SearchProductRequest $request): Response
    {
        if ($request->hasError()) {
            return new JsonResponse($request->getErrors(), Response::HTTP_BAD_REQUEST);
        }
    
        // The incoming request is valid...
    
        // Retrieve one of the validated input data...
        $brand = $request->validated('brand'); //gucci
    
        // Retrieve all of the validated input data...
        $validated = $request->validated();
    //    [
    //        'brand' => 'gucci',
    //        'price' => [
    //            'min' => 100,
    //            'max' => 1000,
    //        ]
    //    ]
    }
}

If validate incoming request parameters as follows, can see error messages:

    //Get api/product/search?brand=a&price[min]=dummy&price[max]=-10.5
    [
        'brand' => 'a',
        'price' => [
            'min' => 'dummy',
            'max' => -10.5,
        ],
    ];
<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class ProductController 
{
    public function search(SearchProductRequest $request): Response
    {
        $request->hasError(); // true
        
        $request->getErrors(); // returns following array
//        [
//            "brand": [
//                "This value is too short. It should have 2 characters or more."
//            ],
//            "price": [
//                "min": [
//                    "This value should be of type integer.",
//                    "This value should be positive."
//                ],
//                "max": [
//                    "This value should be of type integer.",
//                    "This value should be positive."
//                ]
//            ]
//        ]   
    }
}

Suggestion

It's better to prevent duplicate below code in your controller methods,
if ($request->hasError()) {
    return new JsonResponse($request->getErrors(), Response::HTTP_BAD_REQUEST);
}

RequestValidatorBundle provides a good solution for doing this, first create a class that implements MojtabaGheytasi\RequestValidatorBundle\Contract\FailedValidationInterface and writes your logic in the onFailedValidation method:

<?php

namespace App\Request\CustomValidation;

use MojtabaGheytasi\RequestValidatorBundle\Contract\FailedValidationInterface;

class FailedValidation implements FailedValidationInterface
{
    public function onFailedValidation(array $errors)
    {
        // Recommend throw an custom exception and handle it with symfony listeners (listen on ExceptionEvent)
        // You can find more details on https://symfony.com/doc/4.4/event_dispatcher.html#creating-an-event-listener
    }
}

Now just make a yaml file in config/packages/ directory and define the above class to RequestValidatorBundle like the following:

request_validator:
    failed_validation: 'App\Request\CustomValidation'

After doing these, when the request has an error, RequestValidatorBundle immediately executes the onFailedValidation method, and if you throw an exception or anyway make a response in the onFailedValidation method, the controller method codes don't execute. so you can write controller methods like below:

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class ProductController 
{
    public function search(SearchProductRequest $request): Response
    {
        // The incoming request is valid...
    
        // Retrieve one of the validated input data...
        $brand = $request->validated('brand'); //gucci
    }
}

Contributing raising_hand

If you find an issue, or have a better way to do something, feel free to open an issue or a pull request.

mojtaba-gheytasi/request-validator-bundle 适用场景与选型建议

mojtaba-gheytasi/request-validator-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6 次下载、GitHub Stars 达 2, 最近一次更新时间为 2021 年 08 月 14 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「symfony-validator」 「validator-bundle」 「request-validator」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 mojtaba-gheytasi/request-validator-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mojtaba-gheytasi/request-validator-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 mojtaba-gheytasi/request-validator-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 3
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-08-14