Total Complexity | 5 |
Total Lines | 53 |
Duplicated Lines | 0 % |
Coverage | 0% |
Changes | 0 |
1 | <?php |
||
10 | class ResponseListener extends MediaTypeListener |
||
11 | { |
||
12 | private static $noContentMethods = [ |
||
13 | 'HEAD', |
||
14 | ]; |
||
15 | |||
16 | public function onKernelView(GetResponseForControllerResultEvent $event): void |
||
17 | { |
||
18 | $controllerResult = $event->getControllerResult(); |
||
19 | |||
20 | if ($controllerResult instanceof Response) { |
||
21 | return; |
||
22 | } |
||
23 | |||
24 | if (!$this->isContentAllowed($event->getRequest()->getMethod())) { |
||
25 | $event->setResponse( |
||
26 | $this->createEmptyResponse(Response::HTTP_OK) |
||
27 | ); |
||
28 | |||
29 | return; |
||
30 | } |
||
31 | |||
32 | $serializer = $this->getSerializer($event->getRequest()); |
||
33 | $event->setResponse(new Response( |
||
34 | $serializer->serialize($controllerResult), |
||
35 | Response::HTTP_OK, |
||
36 | ['Content-Type' => $serializer->getContentType()] |
||
37 | )); |
||
38 | } |
||
39 | |||
40 | /** |
||
41 | * Checks if the response should contain any content. |
||
42 | * |
||
43 | * @param string $method |
||
44 | * |
||
45 | * @return bool |
||
46 | */ |
||
47 | private function isContentAllowed(string $method): bool |
||
48 | { |
||
49 | return !in_array($method, self::$noContentMethods); |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * Create a response without any body. |
||
54 | * |
||
55 | * @param int $status |
||
56 | * |
||
57 | * @return Response |
||
58 | */ |
||
59 | private function createEmptyResponse(int $status): Response |
||
63 | ); |
||
64 | } |
||
65 | } |
||
66 |