Test Failed
Push — master ( 5db298...a758a4 )
by Daniel
04:14
created

ComponentUsageEventListener::onPostRead()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 2
nop 1
dl 0
loc 14
rs 9.9666
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\Api;
15
16
use Silverback\ApiComponentsBundle\Entity\Core\ComponentInterface;
17
use Silverback\ApiComponentsBundle\Metadata\Factory\ComponentUsageMetadataFactory;
18
use Symfony\Component\HttpKernel\Event\RequestEvent;
19
20
/**
21
 * If the usage endpoint is used for a component, this will override the output with usage metadata
22
 *
23
 * @author Daniel West <[email protected]>
24
 */
25
class ComponentUsageEventListener
26
{
27
    private ComponentUsageMetadataFactory $metadataFactory;
28
29
    public function __construct(ComponentUsageMetadataFactory $metadataFactory)
30
    {
31
        $this->metadataFactory = $metadataFactory;
32
    }
33
34
    public function onPostRead(RequestEvent $event): void
35
    {
36
        $request = $event->getRequest();
37
        $data = $request->attributes->get('data');
38
        $operationName = $request->attributes->get('_api_item_operation_name');
39
        if (
40
            empty($data) ||
41
            !$data instanceof ComponentInterface ||
42
            'get_usage' !== $operationName
43
        ) {
44
            return;
45
        }
46
47
        $request->attributes->set('data', $this->metadataFactory->create($data));
48
    }
49
}
50