Passed
Pull Request — main (#152)
by Daniel
04:48
created

AddMercureTokenListener::onKernelResponse()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 52
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 8
eloc 28
c 1
b 1
f 0
nc 8
nop 1
dl 0
loc 52
ccs 0
cts 28
cp 0
crap 72
rs 8.4444

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentsBundle\EventListener\Mercure;
15
16
use ApiPlatform\Exception\OperationNotFoundException;
17
use ApiPlatform\Metadata\HttpOperation;
18
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
19
use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
20
use ApiPlatform\Util\CorsTrait;
21
use Silverback\ApiComponentsBundle\Annotation\Publishable;
22
use Silverback\ApiComponentsBundle\Helper\Publishable\PublishableStatusChecker;
23
use Symfony\Component\HttpFoundation\Cookie;
24
use Symfony\Component\HttpKernel\Event\ResponseEvent;
25
use Symfony\Component\Mercure\Jwt\TokenFactoryInterface;
26
use Symfony\Component\Routing\RequestContext;
27
28
class AddMercureTokenListener
29
{
30
    use CorsTrait;
0 ignored issues
show
Bug introduced by
The trait ApiPlatform\Util\CorsTrait requires the property $headers which is not provided by Silverback\ApiComponents...AddMercureTokenListener.
Loading history...
31
32
    public function __construct(private TokenFactoryInterface $tokenFactory, private ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, private ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, private PublishableStatusChecker $publishableStatusChecker, private RequestContext $requestContext)
33
    {
34
    }
35
36
    /**
37
     * Sends the Mercure header on each response.
38
     * Probably lock this on the "/me" route.
39
     */
40
    public function onKernelResponse(ResponseEvent $event): void
41
    {
42
        $request = $event->getRequest();
43
        // Prevent issues with NelmioCorsBundle
44
        if ($this->isPreflightRequest($request)) {
45
            return;
46
        }
47
48
        $subscribeIris = [];
49
        $response = $event->getResponse();
50
51
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
52
            $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($resourceClass);
53
54
            try {
55
                $operation = $resourceMetadataCollection->getOperation(forceCollection: false, httpOperation: true);
56
            } catch (OperationNotFoundException $e) {
57
                continue;
58
            }
59
60
            if (!$operation instanceof HttpOperation) {
61
                continue;
62
            }
63
64
            $mercure = $operation->getMercure();
65
66
            if (!$mercure) {
67
                continue;
68
            }
69
70
            $refl = new \ReflectionClass($operation->getClass());
71
            $isPublishable = \count($refl->getAttributes(Publishable::class));
72
73
            // TODO: the str_replace thing should be fixed inside API Platform (will be available in next patch)
74
            $uriTemplate = $this->buildAbsoluteUriTemplate() . $operation->getRoutePrefix() . str_replace('.{_format}', '{._format}', $operation->getUriTemplate());
75
76
            if (!$isPublishable) {
77
                $subscribeIris[] = $uriTemplate;
78
                continue;
79
            }
80
81
            // Note that `?draft=1` is also hard coded into the PublishableIriConverter, probably make this configurable somewhere
82
            if ($this->publishableStatusChecker->isGranted($operation->getClass())) {
83
                $subscribeIris[] = $uriTemplate . '?draft=1';
84
                $subscribeIris[] = $uriTemplate;
85
                continue;
86
            }
87
88
            $subscribeIris[] = $uriTemplate;
89
        }
90
91
        $response->headers->setCookie(Cookie::create('mercureAuthorization', $this->tokenFactory->create($subscribeIris, [])));
92
    }
93
94
    /**
95
     * Mercure subscribe iris should be absolute
96
     * this code can also be found in Symfony's URL Generator
97
     * but as we work without a symfony route here (and we would not want to do this as its not spec-compliant)
98
     * we do it by hand.
99
     */
100
    private function buildAbsoluteUriTemplate(): string
101
    {
102
        $scheme = $this->requestContext->getScheme();
103
        $host = $this->requestContext->getHost();
104
        $port = $this->requestContext->isSecure() ? $this->requestContext->getHttpsPort() : $this->requestContext->getHttpPort();
105
106
        if (80 !== $port || 443 !== $port) {
107
            return sprintf('%s://%s:%d', $scheme, $host, $port);
108
        }
109
110
        return sprintf('%s://%s', $scheme, $host);
111
    }
112
}
113