lib/boab/cms-bundle/src/Api/EventListener/ApiRequestListener.php line 14

Open in your IDE?
  1. <?php
  2. namespace Boab\CmsBundle\Api\EventListener;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Boab\CmsBundle\Api\Exception\ApiException;
  7. class ApiRequestListener
  8. {
  9.     private $requestFormats = ['json','xml'];
  10.     public function onKernelRequest(RequestEvent $event)
  11.     {
  12.         $request $event->getRequest();
  13.         if(!$request->attributes->has('_api')){
  14.             return;
  15.         }
  16.         //die($request->getContentType());
  17.         $this->setRequestFormat($request);
  18.         if($content $request->getContent()){
  19.             if('POST' === $request->getMethod() && 'form' === $request->getContentType() ){
  20.                 return;
  21.             }
  22.             $data $this->decodeJsonData($content);
  23.             $request->request->replace($data);
  24.         }
  25.     }
  26.     private function decodeJsonData($content)
  27.     {
  28.         $data = @json_decode($contenttrue);
  29.         if($data === null || json_last_error() !== JSON_ERROR_NONE) {
  30.             throw new ApiException(400"Invalid json data sent");
  31.         } 
  32.         return $data;
  33.     }
  34.     private function setRequestFormat($request)
  35.     {
  36.         $format = ($request->attributes->get('format'))?$request->attributes->get('format'):$request->getContentType();
  37.         if(!in_array($format$this->requestFormats)){
  38.             throw new ApiException(400sprintf("The supplied content type format is not supported"$format));
  39.         }
  40.         $request->attributes->set('format',$format);
  41.     }
  42. }