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

MercureResourcePublisher   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 21
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 21
ccs 0
cts 9
cp 0
rs 10
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A publishResourceUpdate() 0 11 1
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\Mercure;
15
16
use ApiPlatform\Api\IriConverterInterface;
17
use ApiPlatform\Api\UrlGeneratorInterface;
18
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
19
use ApiPlatform\Util\ResourceClassInfoTrait;
20
use Symfony\Component\Mercure\HubInterface;
21
use Symfony\Component\Mercure\Update;
22
use Symfony\Component\Serializer\SerializerAwareInterface;
23
use Symfony\Component\Serializer\SerializerAwareTrait;
24
25
class MercureResourcePublisher implements SerializerAwareInterface
26
{
27
    use ResourceClassInfoTrait;
28
    use SerializerAwareTrait;
29
30
    // Do we want MessageBusInterface instead ? we don't have messenger installed yet, probably just use the default hub for now
31
    public function __construct(private HubInterface $hub, private IriConverterInterface $iriConverter, private ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory)
32
    {
33
    }
34
35
    public function publishResourceUpdate(object $object): void
36
    {
37
        $resourceClass = $this->getObjectClass($object);
38
        $operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
39
        $mercureOptions = $operation->getMercure() ?? [];
40
        $context = $operation->getNormalizationContext() ?? [];
41
42
        $iri = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_URL);
43
        $data = $this->serializer->serialize($object, 'jsonld', $context);
44
45
        $this->hub->publish(new Update(data: $data, topics: [$iri], private: $mercureOptions['private'] ?? false));
46
    }
47
}
48