vangrg/request-mapper-bundle

这个symfony扩展包提供了将请求数据映射到您的模型对象并验证它的工具。非常适合开发RESTful API。

安装: 736

依赖: 0

建议: 0

安全: 0

星标: 2

关注者: 1

分支: 1

开放问题: 0

类型:symfony-bundle

v1.0.4 2019-10-07 09:22 UTC

This package is not auto-updated.

Last update: 2024-10-01 09:03:31 UTC


README

这个小巧的扩展包提供了轻松映射和验证请求数据的工具(而不是使用Symfony表单)。

一个注解允许您处理所有类型的数据(查询参数或请求体参数)并为所有操作构建相同的400响应结构。在控制器中,您将接收到一个有效的对象。

此扩展包使用 symfony serializer 来处理请求。

非常适合开发RESTful API。.

安装

从您的Symfony项目的根目录的终端运行此命令以添加VangrgRequestMapperBundle

composer require vangrg/request-mapper-bundle

如果您使用Flex,扩展包将自动启用,无需进一步操作。否则,要开始使用扩展包,请在您的应用程序的内核类中注册它

// app/AppKernel.php
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            // ...
            new Vangrg\RequestMapperBundle\VangrgRequestMapperBundle(),
            // ...
        ];
    }
}

覆盖默认配置

# config/packages/vangrg_request_mapper.yaml or app/config/config.yml
vangrg_request_mapper:
  validation_response:
    enabled: true # Enable or disable validation error response listener(default: true)
                  # If disabled then ValidationException will be thrown for not valid request data
    format: 'json' # Validation response format (json or xml)

使用方法

@RequestParamMapper注解调用服务以将请求数据映射到对象。该对象作为请求属性存储,并可以注入为控制器方法参数。

所有注解参数

  • class - 映射的类名。
  • deserializationContext - symfony serializer 的反序列化上下文。
  • toExistedObject - 如果您想将数据映射到现有对象,则设置为 true。默认 - false
  • validate - 在数据插入后启用或禁用验证。默认 - true
  • validationGroups - 验证分组
use Vangrg\RequestMapperBundle\Annotation\RequestParamMapper;
use FOS\RestBundle\Controller\Annotations as Rest;

/**
 * @Rest\Get("/products")
 * @RequestParamMapper("filter", class="App\FilterDto")
 */
public function getProducts(FilterDto $filter)
{
}

您可以使用 symfony validator 对象。

use Symfony\Component\Validator\Constraints as Assert;

class FilterDto
{
    // ...

    /**
     * @var string
     *
     * @Assert\NotNull()
     */
    public $name;
    
    /**
     * @Assert\Regex("/^(ASC|DESC)$/i")
     */
    public $sortDirection = 'ASC';  
    
    // ...  
}

请求示例: /products?name=car&sortDirection=DESC

@ParamConverter 结合使用

如果您想更新一个现有对象(PUTPATCH),则可以使用 @ParamConverter 从数据库获取对象,并使用 @RequestParamMapper 将数据映射到该对象。

use Vangrg\RequestMapperBundle\Annotation\RequestParamMapper;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

/**
 * @Rest\Put("/products/{id}")
 *
 * @ParamConverter("product", class="App:Product")
 *
 * @RequestParamMapper(
 *     "product",
 *     class="App\Entity\Product",
 *     toExistedObject=true,
 *     deserializationContext={"groups"={"details"}},
 *     validationGroups={"update_product"}
 * )
 */
public function updateProduct(Product $product)
{
    $this->getDoctrine()->getManager()->flush();
    
    return $product;
}

请求体示例

{
    "name": "Car",
    "description": "",
    "tags": [
      /*-------------*/
    ],
/*-------------------*/
}

事件

以下是您可以监听的事件列表

示例

<?php

namespace App\EventListener;

use Vangrg\RequestMapperBundle\Event\ConfigurationEvent;
use Vangrg\RequestMapperBundle\Event\BeforeNormalizeEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class FooSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            ConfigurationEvent::NAME => [
                ['onReadConfiguration'],
            ],
            BeforeNormalizeEvent::NAME => [
                ['modifyMappedData'],
            ],            
        ];
    }
    public function onReadConfiguration(ConfigurationEvent $event)
    {
        $configuration = $event->getConfiguration();

        // do your something
    }

    public function modifyMappedData(BeforeNormalizeEvent $event)
    {
        $data = $event->getData();
        
        // do something
        // $data['start'] = (integer) $data['start'];
        
        $event->setData($data);
    }
}