Test Failed
Push — v2 ( ff58b5...1cae4f )
by Daniel
06:08 queued 46s
created

ResourceDtoOutputClassMetadataFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 28
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A create() 0 19 4
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component 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\ApiComponentBundle\Metadata;
15
16
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
17
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
18
use ReflectionClass;
19
use Silverback\ApiComponentBundle\Entity\Core\AbstractPageData;
20
use Silverback\ApiComponentBundle\Entity\Utility\FileInterface;
21
22
/**
23
 * This is to explicitly define the output class of any resource implementing FilterInterface
24
 * This is so that the Data Transformer will be called.
25
 *
26
 * @author Daniel West <[email protected]>
27
 */
28
class ResourceDtoOutputClassMetadataFactory implements ResourceMetadataFactoryInterface
29
{
30
    private ResourceMetadataFactoryInterface $decorated;
31
32
    public function __construct(ResourceMetadataFactoryInterface $decorated)
33
    {
34
        $this->decorated = $decorated;
35
    }
36
37
    public function create(string $resourceClass): ResourceMetadata
38
    {
39
        $resourceMetadata = $this->decorated->create($resourceClass);
40
        $reflection = new ReflectionClass($resourceClass);
41
        if (!$reflection->isSubclassOf(FileInterface::class)) {
42
            return $resourceMetadata;
43
        }
44
45
        if (!$resourceMetadata->getAttribute('output')) {
46
            $attributes = $resourceMetadata->getAttributes() ?: [];
47
            $resourceMetadata = $resourceMetadata->withAttributes(array_merge($attributes, [
48
                'output' => [
49
                    'class' => $resourceClass,
50
                    'name' => $reflection->getShortName(),
51
                ],
52
            ]));
53
        }
54
55
        return $resourceMetadata;
56
    }
57
}
58