Issues (332)

Mercure/EventListener/AddLinkHeaderListener.php (1 issue)

1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[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 ApiPlatform\Core\Mercure\EventListener;
15
16
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
17
use ApiPlatform\Core\Util\CorsTrait;
18
use Fig\Link\GenericLinkProvider;
19
use Fig\Link\Link;
20
use Symfony\Component\HttpKernel\Event\ResponseEvent;
21
22
/**
23
 * Adds the HTTP Link header pointing to the Mercure hub for resources having their updates dispatched.
24
 *
25
 * @author Kévin Dunglas <[email protected]>
26
 */
27
final class AddLinkHeaderListener
28
{
29
    use CorsTrait;
0 ignored issues
show
The trait ApiPlatform\Core\Util\CorsTrait requires the property $headers which is not provided by ApiPlatform\Core\Mercure...r\AddLinkHeaderListener.
Loading history...
30
31
    private $resourceMetadataFactory;
32
    private $hub;
33
34
    public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, string $hub)
35
    {
36
        $this->resourceMetadataFactory = $resourceMetadataFactory;
37
        $this->hub = $hub;
38
    }
39
40
    /**
41
     * Sends the Mercure header on each response.
42
     */
43
    public function onKernelResponse(ResponseEvent $event): void
44
    {
45
        $request = $event->getRequest();
46
        // Prevent issues with NelmioCorsBundle
47
        if ($this->isPreflightRequest($request)) {
48
            return;
49
        }
50
51
        $link = new Link('mercure', $this->hub);
52
53
        if (
54
            null === ($resourceClass = $request->attributes->get('_api_resource_class')) ||
55
            false === $this->resourceMetadataFactory->create($resourceClass)->getAttribute('mercure', false)
56
        ) {
57
            return;
58
        }
59
60
        if (null === $linkProvider = $request->attributes->get('_links')) {
61
            $request->attributes->set('_links', new GenericLinkProvider([$link]));
62
63
            return;
64
        }
65
66
        $request->attributes->set('_links', $linkProvider->withLink($link));
67
    }
68
}
69