n7/symfony-http-bundle

安装量: 157,738

依赖者: 0

建议者: 0

安全: 0

星级: 3

关注者: 2

分支: 3

开放问题: 0

类型:symfony-bundle

v1.0.25 2024-09-15 14:48 UTC

README

此软件包仍在开发中。

请求注入

如何工作

  • 您创建请求类,使用 JMS 序列化注解和 Symfony 验证注解描述其结构。
  • 您将请求注入到您的控制器动作中。
  • 包根据您的请求类验证请求,如果请求无效,则抛出自定义验证异常。
  • 如果请求有效,则将其反序列化为您的请求类。

重要提示:HTTP 请求字段始终作为字符串出现,为了正确验证它们,它们会根据请求类中的类型注解进行软类型转换。

您可以注册监听器,将 N7\SymfonyHttpBundle\EventListener\RequestPayloadExceptionListener 异常转换为 json 响应。

# (config/services.yaml)

services:
    # ...
    
    N7\SymfonyHttpBundle\EventListener\RequestPayloadExceptionListener:
        tags:
            - { name: kernel.event_listener, event: kernel.exception }

示例

请求类

use N7\SymfonyHttpBundle\Interfaces\RequestPayloadInterface;

final class CreateUserRequest implements RequestPayloadInterface
{
    /**
     * @Constraints\NotBlank
     * @Constraints\Type(type="string")
     */
    private string $username;

    /**
     * @Constraints\NotBlank
     * @Constraints\Type(type="integer")
     */
    private int $age;
    
    /**
     * @Constraints\NotBlank
     * @Constraints\Type(type="bool")
     */
    private bool $terms;
}

控制器动作

/**
 * @Route("/api/endpoint")
 */
public function create(CreateUserRequest $request): Response
{
    dd($request);
}

无参数请求的响应

{
  "code": 422,
  "message": "Validation error occurred",
  "errors": {
    "[username]": "This field is missing.",
    "[age]": "This field is missing.",
    "[terms]": "This field is missing."
  }
}

嵌套对象和对象数组

嵌套对象和对象数组由 n7/symfony-validators-bundle 包处理。

示例

final class Request implements RequestPayloadInterface
{
    /**
     * @Constraints\NotBlank
     * @NestedObject(NestedObject::class)
     */
    private NestedObject $select2;

    /**
     * @Constraints\NotBlank
     * @NestedObjects(NestedObject::class)
     *
     * @Serializer\Type("array<NestedObject>")
     */
    private array $list;
}

数组

关于数组的一个注意事项:整数/浮点/布尔数组必须具有 @var 注解来描述其内部元素的标量类型。这在验证之前进行软类型转换时是必需的。可用值:int[]float[]boolean[]string[]

示例

final class Request implements RequestPayloadInterface
{
    /**
     * @Constraints\NotBlank
     *
     * @Serializer\Type("array")
     * @var float[]
     */
    private array $amounts;
}

AllowExtraFields 和 AllowMissingFields

验证器 allowExtraFieldsallowMissingFields 参数可以通过注解进行重写。

use N7\SymfonyValidatorsBundle\Options\AllowExtraFields;
use N7\SymfonyValidatorsBundle\Options\AllowMissingFields;

/**
 * @AllowExtraFields
 * @AllowMissingFields
 */
final class Request implements RequestPayloadInterface
{

}

🥔