comparison core/modules/serialization/src/EventSubscriber/DefaultExceptionSubscriber.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 1fec387a4317
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\serialization\EventSubscriber;
4
5 use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
6 use Symfony\Component\HttpFoundation\Response;
7 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
8 use Symfony\Component\Serializer\SerializerInterface;
9
10 /**
11 * Handles default error responses in serialization formats.
12 */
13 class DefaultExceptionSubscriber extends HttpExceptionSubscriberBase {
14
15 /**
16 * The serializer.
17 *
18 * @var \Symfony\Component\Serializer\Serializer
19 */
20 protected $serializer;
21
22 /**
23 * The available serialization formats.
24 *
25 * @var array
26 */
27 protected $serializerFormats = [];
28
29 /**
30 * DefaultExceptionSubscriber constructor.
31 *
32 * @param \Symfony\Component\Serializer\SerializerInterface $serializer
33 * The serializer service.
34 * @param array $serializer_formats
35 * The available serialization formats.
36 */
37 public function __construct(SerializerInterface $serializer, array $serializer_formats) {
38 $this->serializer = $serializer;
39 $this->serializerFormats = $serializer_formats;
40 }
41
42 /**
43 * {@inheritdoc}
44 */
45 protected function getHandledFormats() {
46 return $this->serializerFormats;
47 }
48
49 /**
50 * {@inheritdoc}
51 */
52 protected static function getPriority() {
53 // This will fire after the most common HTML handler, since HTML requests
54 // are still more common than HTTP requests.
55 return -75;
56 }
57
58 /**
59 * Handles all 4xx errors for all serialization failures.
60 *
61 * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
62 * The event to process.
63 */
64 public function on4xx(GetResponseForExceptionEvent $event) {
65 /** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
66 $exception = $event->getException();
67 $request = $event->getRequest();
68
69 $format = $request->getRequestFormat();
70 $content = ['message' => $event->getException()->getMessage()];
71 $encoded_content = $this->serializer->serialize($content, $format);
72 $headers = $exception->getHeaders();
73
74 // Add the MIME type from the request to send back in the header.
75 $headers['Content-Type'] = $request->getMimeType($format);
76
77 $response = new Response($encoded_content, $exception->getStatusCode(), $headers);
78 $event->setResponse($response);
79 }
80
81 }