Passed
Pull Request — master (#2398)
by Kévin
07:11 queued 02:48
created

MessengerDataPersister   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 10
dl 0
loc 37
c 0
b 0
f 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A persist() 0 5 1
A remove() 0 3 1
A supports() 0 3 1
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\DataPersister;
15
16
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
17
use ApiPlatform\Core\Util\ClassInfoTrait;
18
use Symfony\Component\Messenger\Envelope;
19
use Symfony\Component\Messenger\MessageBusInterface;
20
21
/**
22
 * Dispatches the given resource using the message bus of Symfony Messenger.
23
 *
24
 * @experimental
25
 *
26
 * @author Kévin Dunglas <[email protected]>
27
 */
28
final class MessengerDataPersister implements DataPersisterInterface
29
{
30
    use ClassInfoTrait;
31
32
    private $resourceMetadataFactory;
33
    private $messageBus;
34
35
    public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, MessageBusInterface $messageBus)
36
    {
37
        $this->resourceMetadataFactory = $resourceMetadataFactory;
38
        $this->messageBus = $messageBus;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function supports($data): bool
45
    {
46
        return true === $this->resourceMetadataFactory->create($this->getObjectClass($data))->getAttribute('messenger');
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function persist($data)
53
    {
54
        $this->messageBus->dispatch($data);
55
56
        return $data;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function remove($data)
63
    {
64
        $this->messageBus->dispatch(new Envelope($data, new RemoveStamp()));
65
    }
66
}
67