src/EventSubscriber/Vendor/VendorPostSerializeSubscriber.php line 40

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: sebastiantovar
  5.  * Date: 2019-04-04
  6.  * Time: 15:24
  7.  */
  8. namespace App\EventSubscriber\Vendor;
  9. use Symfony\Component\HttpKernel\Event\ViewEvent;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use ApiPlatform\Core\EventListener\EventPriorities;
  12. use Symfony\Component\HttpKernel\KernelEvents;
  13. use App\Exception\VendorException;
  14. use App\Services\VendorService;
  15. class VendorPostSerializeSubscriber implements EventSubscriberInterface
  16. {
  17.     private $vendorService;
  18.     public function __construct(VendorService $vendorService)
  19.     {
  20.         $this->vendorService $vendorService;
  21.     }
  22.     /**
  23.      * {@inheritdoc}
  24.      */
  25.     public static function getSubscribedEvents() {
  26.         return [
  27.             KernelEvents::VIEW => ['onKernelView'EventPriorities::POST_SERIALIZE]
  28.         ];
  29.     }
  30.     /**
  31.      * @param ViewEvent $event
  32.      * @throws VendorException
  33.      */
  34.     public function onKernelView(ViewEvent $event) {
  35.         $request $event->getRequest();
  36.         $vendorResult $event->getControllerResult();
  37.         $route $request->attributes->get('_route');
  38.         $routes = array(
  39.             'api_vendors_get_collection',
  40.             'api_vendors_post_collection',
  41.             'api_vendors_get_item',
  42.             'api_vendors_put_item'
  43.         );
  44.         if (!in_array($route$routes))
  45.             return;
  46.         $vendorResult json_decode($vendorResulttrue);
  47.         
  48.         if ('api_vendors_get_collection' === $route) {
  49.             foreach ($vendorResult as &$vendor) {
  50.                 $vendor $this->vendorService->formatNormalize($vendor);
  51.             }
  52.             $vendorResult json_encode($vendorResult);
  53.         } else {
  54.             $vendorResult $this->vendorService->formatNormalize($vendorResult);
  55.             $vendorResult json_encode($vendorResult);
  56.         }
  57.         $event->setControllerResult($vendorResult);
  58.     }
  59. }