basilicom / json-schema-request-validator-bundle
通过 JSON schema 轻松验证 Symfony 请求体,并自动拒绝无效请求
v2.0.1
2021-11-17 16:07 UTC
Requires
- ext-json: *
- justinrainbow/json-schema: ^5.2
- symfony/config: ^5.3
- symfony/dependency-injection: ^5.3
- symfony/http-foundation: ^5.3
- symfony/http-kernel: ^5.3
This package is auto-updated.
Last update: 2024-09-17 22:42:01 UTC
README
通过 JSON schema 轻松验证 Symfony 请求体,并自动拒绝无效请求
版本
安装
通过 composer
composer require basilicom/json-schema-request-validator-bundle
添加到 \App\Kernel
$collection->addBundle(new JsonSchemaRequestValidatorBundle());
使用方法
控制器需要实现 JsonSchemaRequestValidationControllerInterface
接口。其所有动作的请求体将通过接口方法 setJsonSchemaFilePathsInFilePathProvider(FilePathProvider $filePathProvider)
设置的 JSON schema 文件进行验证。
此控制器的所有动作都必须有一个 JSON schema 文件,必须通过路由名称进行映射。
系统会自动拒绝无效的请求,并返回状态码 "400 Bad Request"。如果找不到 JSON schema 文件,将返回 "500 内部服务器错误"。
示例 Symfony 控制器
<?php namespace AppBundle\Controller; use Basilicom\JsonSchemaRequestValidator\Controller\JsonSchemaRequestValidationControllerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; class TestingEndpointsController extends AbstractController implements JsonSchemaRequestValidationControllerInterface { /** * @Route("/testing", methods={"POST"}, name="testing_post") * * @param Request $request * * @return JsonResponse */ public function testingPost(Request $request): JsonResponse { return new JsonResponse(['success']); } /** * @Route("/testing", methods={"GET"}, name="testing_get") * * @param Request $request * * @return JsonResponse */ public function testingGet(Request $request): JsonResponse { return new JsonResponse(['success']); } public function setJsonSchemaFilePathsInFilePathProvider(FilePathProvider $filePathProvider) { $filePathProvider->setIgnoreRouteName('testing_get', true); $filePathProvider->setJsonSchemaFilePathForRouteName('testing_post', __DIR__ . '/../Resources/jsonschemas/test.json'); } }