getSubscribedEvents()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4286
cc 1
eloc 3
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Innmind\RestBundle\EventListener;
4
5
use Innmind\Rest\Server\Routing\RouteKeys;
6
use Innmind\Rest\Server\Registry;
7
use Symfony\Component\HttpKernel\KernelEvents;
8
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
9
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
10
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
11
use Symfony\Component\HttpFoundation\Response;
12
13
class CapabilitiesResponseListener implements EventSubscriberInterface
14
{
15
    protected $urlGenerator;
16
    protected $registry;
17
18 6
    public function __construct(
19
        UrlGeneratorInterface $urlGenerator,
20
        Registry $registry
21
    ) {
22 6
        $this->urlGenerator = $urlGenerator;
23 6
        $this->registry = $registry;
24 6
    }
25
26
    /**
27
     * {@inheritdoc}
28
     */
29 18
    public static function getSubscribedEvents()
30
    {
31
        return [
32 18
            KernelEvents::VIEW => 'buildResponse',
33 18
        ];
34
    }
35
36
    /**
37
     * Build the response to expose all routes of the API
38
     *
39
     * @param GetResponseForControllerResultEvent $event
40
     *
41
     * @return void
42
     */
43 4
    public function buildResponse(GetResponseForControllerResultEvent $event)
44
    {
45 4
        $request = $event->getRequest();
46
47
        if (
48 4
            !$request->attributes->has(RouteKeys::ACTION) ||
49 2
            $request->attributes->get(RouteKeys::ACTION) !== 'capabilities'
50 4
        ) {
51 2
            return;
52
        }
53
54 2
        $routes = $event->getControllerResult();
55 2
        $response = new Response;
56 2
        $links = $response->headers->get('Link', null, false);
57
58 2
        foreach ($routes as $name => $route) {
59 2
            $definition = $route->getDefault(RouteKeys::DEFINITION);
60 2
            list($collection, $resource) = explode('::', $definition);
61 2
            $definition = $this
62
                ->registry
63 2
                ->getCollection($collection)
64 2
                ->getResource($resource);
65
66 2
            $links[] = sprintf(
67 2
                '<%s>; rel="endpoint"; name="%s_%s"',
68 2
                $this->urlGenerator->generate($name),
69 2
                $definition->getCollection(),
70
                $definition
71 2
            );
72 2
        }
73
74 2
        $response->headers->add(['Link' => $links]);
75 2
        $event->setResponse($response);
76 2
    }
77
}
78