PHP code example of vangrg / request-mapper-bundle

1. Go to this page and download the library: Download vangrg/request-mapper-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

vangrg / request-mapper-bundle example snippets


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

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)
{
}

use Symfony\Component\Validator\Constraints as Assert;

class FilterDto
{
    // ...

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

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;
}



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);
    }
}