ResponderSubscriber::getSubscribedEvents()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Kamyshev\ResponderBundle\Responder;
4
5
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
6
use Symfony\Component\HttpKernel\KernelEvents;
7
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
8
9
class ResponderSubscriber implements EventSubscriberInterface
10
{
11
    /** @var ResponderInterface[] $responders */
12
    private $responders;
13
14
    public function __construct(iterable $responders)
15
    {
16
        $this->responders = (function (ResponderInterface ...$responders): iterable {
17
            return $responders;
18
        })(...$responders);
19
    }
20
21
    public function onKernelView(GetResponseForControllerResultEvent $event): void
22
    {
23
        $result = $event->getControllerResult();
24
        $meta = new ResultMetadata(get_class($result));
25
26
        $specificResponder = array_find(
27
            $this->responders,
28
            function (ResponderInterface $responder) use ($meta, $result): bool {
29
                return $responder->supports($result, $meta);
30
            }
31
        );
32
33
        if ($specificResponder) {
34
            $response = $specificResponder->make($result, $meta);
35
            $event->setResponse($response);
36
        }
37
    }
38
39
    public static function getSubscribedEvents()
40
    {
41
        return [
42
            KernelEvents::VIEW => 'onKernelView',
43
        ];
44
    }
45
}
46