src/EventSubscriber/Category/CategoryPostSerializeSubscriber.php line 43

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: sebastiantovar
  5.  * Date: 2019-04-15
  6.  * Time: 18:36
  7.  */
  8. namespace App\EventSubscriber\Category;
  9. use ApiPlatform\Core\EventListener\EventPriorities;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpKernel\Event\ViewEvent;
  12. use Symfony\Component\HttpKernel\KernelEvents;
  13. use App\Services\CategoryService;
  14. use App\Services\UtilsService;
  15. class CategoryPostSerializeSubscriber implements EventSubscriberInterface
  16. {
  17.     private $categoryService;
  18.     private $utilsService;
  19.     public function __construct(
  20.         UtilsService $utilsService,
  21.         CategoryService $categoryService
  22.     ) {
  23.         $this->utilsService $utilsService;
  24.         $this->categoryService $categoryService;
  25.     }
  26.     /**
  27.      * {@inheritdoc}
  28.      */
  29.     public static function getSubscribedEvents() {
  30.         return [
  31.             KernelEvents::VIEW => ['onKernelView'EventPriorities::POST_SERIALIZE]
  32.         ];
  33.     }
  34.     /**
  35.      * @param ViewEvent $event
  36.      */
  37.     public function onKernelView(ViewEvent $event) {
  38.         if ($this->utilsService->isAPublicRequest($event)) {
  39.             return;
  40.         }
  41.         $request $event->getRequest();
  42.         $categoryResult $event->getControllerResult();
  43.         $route $request->attributes->get('_route');
  44.         $routes = array(
  45.             'api_categories_post_collection',
  46.             'api_categories_get_item',
  47.             'api_categories_put_item',
  48.             'api_vendors_categories_get_subresource'
  49.         );
  50.         if (!in_array($route$routes))
  51.             return;
  52.         $categoryResult json_decode($categoryResulttrue);
  53.         if ('api_categories_get_collection' === $route ||
  54.             'api_vendors_categories_get_subresource' === $route) {
  55.             foreach ($categoryResult as &$category) {
  56.                 $category $this->categoryService->formatNormalize($categoryfalse$route);
  57.             }
  58.         } else {
  59.             $categoryResult $this->categoryService->formatNormalize($categoryResult,true$route);
  60.         }
  61.         $categoryResult json_encode($categoryResult);
  62.         $event->setControllerResult($categoryResult);
  63.     }
  64. }