dimkinthepro/http-bundle

Symfony的请求验证包

安装: 10

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

开放问题: 0

类型:symfony-bundle

1.0.0 2024-09-04 16:26 UTC

This package is auto-updated.

Last update: 2024-09-04 16:27:34 UTC


README

1. 安装

composer require dimkinthepro/http-bundle

2. 检查包配置

# config/bundles.php

return [
#...
    Dimkinthepro\Http\DimkintheproHttpBundle::class => ['all' => true],
];

3. 创建包配置

# config/packages/dimkinthepro_http.yaml

dimkinthepro_http:
    request_validation_enabled: true
    extra_fields_allowed: true
    handle_validation_errors: true
    response_error_format: json

4. 检查验证器配置

# config/packages/validator.yaml

framework:
    #...
    validation:
        #...
        mapping:
            paths:
                #...
                - '%kernel.project_dir%/config/validator/'

5. 创建控制器DTO

# src/App/DTO/RequestDTO.php

namespace App\DTO;

use Dimkinthepro\Http\Domain\DTO\ValidatedDTOInterface;

class RequestDTO implements ValidatedDTOInterface
{
    public string $method;
    public int $parameter;
    public \DateTimeImmutable $date;
    public App\Enum\FooEnum $enum;
}

6. 为DTO创建验证配置

# config/validator/RequestDTO.yaml

App\DTO\RequestDTO:
  properties:
    method:
      - NotBlank: ~
    parameter:
      - NotBlank: ~
      - GreaterThan: 0
      - LessThanOrEqual: 255
    date:
      - NotBlank: ~
    enum:
      - NotBlank: ~

7. 在控制器中使用验证过的DTO

# src/App/Controller/Controller.php

namespace App\Controller;

use App\DTO\RequestDTO;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;

class Controller extends AbstractController
{
    public function __invoke(RequestDTO $DTO): JsonResponse
    {
        return new JsonResponse([
            'method' => $DTO->method,
            'parameter' => $DTO->parameter,
            'date' => $DTO->date,
            'enum' => $DTO->enum->value,
        ]);
    }
}