RequestExceptionListener.php (2522B)
1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: felicitus 5 * Date: 10/25/17 6 * Time: 11:01 PM. 7 */ 8 9 namespace PartKeepr\CoreBundle\EventListener; 10 11 use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException; 12 use Dunglas\ApiBundle\Action\ActionUtilTrait; 13 use Dunglas\ApiBundle\Api\IriConverter; 14 use Dunglas\ApiBundle\JsonLd\Response; 15 use Dunglas\ApiBundle\Model\DataProviderInterface; 16 use PartKeepr\DoctrineReflectionBundle\Exception\EntityInUseException; 17 use PartKeepr\DoctrineReflectionBundle\Services\DeletionService; 18 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; 19 use Symfony\Component\Serializer\Normalizer\NormalizerInterface; 20 21 /** 22 * Handle referential integrity errors. 23 */ 24 class RequestExceptionListener extends \Dunglas\ApiBundle\Hydra\EventListener\RequestExceptionListener 25 { 26 use ActionUtilTrait; 27 28 const FORMAT = 'jsonld'; 29 30 /** 31 * @var DataProviderInterface 32 */ 33 private $dataProvider; 34 35 /** 36 * @var IriConverter 37 */ 38 private $iriConverter; 39 40 /** 41 * @var DeletionService 42 */ 43 private $deletionService; 44 45 public function __construct( 46 NormalizerInterface $normalizer, 47 DataProviderInterface $dataProvider, 48 IriConverter $iriConverter, 49 DeletionService $deletionService 50 ) { 51 $this->dataProvider = $dataProvider; 52 $this->iriConverter = $iriConverter; 53 $this->deletionService = $deletionService; 54 parent::__construct($normalizer); 55 } 56 57 /** 58 * @param GetResponseForExceptionEvent $event 59 */ 60 public function onKernelException(GetResponseForExceptionEvent $event) 61 { 62 $request = $event->getRequest(); 63 if (!$request->attributes->has('_resource_type') || self::FORMAT !== $request->attributes->get('_api_format')) { 64 return; 65 } 66 67 $exception = $event->getException(); 68 $headers = []; 69 70 if ($exception instanceof ForeignKeyConstraintViolationException) { 71 $item = $this->iriConverter->getItemFromIri($request->getRequestUri()); 72 73 $usedIn = $this->deletionService->findUndeletableUsages($item); 74 75 $data = new EntityInUseException((string) $item, $usedIn); 76 77 $status = Response::HTTP_FAILED_DEPENDENCY; 78 79 $event->setResponse(new \Symfony\Component\HttpFoundation\Response( 80 json_encode($data), 81 $status, 82 $headers 83 )); 84 } else { 85 parent::onKernelException($event); 86 } 87 } 88 }