Passed
Push — main ( d99856...c81305 )
by Daniel
05:39
created

AddMercureTokenListener::getMercureResourceOperation()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 4
nop 1
dl 0
loc 21
ccs 0
cts 11
cp 0
crap 20
rs 9.9
c 0
b 0
f 0
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\Metadata\HttpOperation;
17
use ApiPlatform\Util\CorsTrait;
18
use Silverback\ApiComponentsBundle\Mercure\MercureAuthorization;
19
use Symfony\Component\HttpKernel\Event\ResponseEvent;
20
21
class AddMercureTokenListener
22
{
23
    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...
24
25
    public function __construct(
26
        private readonly MercureAuthorization $mercureAuthorization
27
    ) {
28
    }
29
30
    /**
31
     * Sends the Mercure header on each response.
32
     * Probably lock this on the "/me" route.
33
     */
34
    public function onKernelResponse(ResponseEvent $event): void
35
    {
36
        $request = $event->getRequest();
37
38
        /** @var ?HttpOperation $operation */
39
        $operation = $request->attributes->get('_api_operation');
40
        // Prevent issues with NelmioCorsBundle
41
        if (!$operation || $this->isPreflightRequest($request) || $operation->getName() !== 'me') {
42
            return;
43
        }
44
        $cookie = $this->mercureAuthorization->createAuthorizationCookie();
45
        $event->getResponse()->headers->setCookie($cookie);
46
    }
47
}
48