Passed
Push — v2 ( 0900e0...35ac0b )
by Daniel
06:52
created

prefixComponentRoute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 10
ccs 0
cts 7
cp 0
crap 6
rs 10
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 Silverback\ApiComponentBundle\Entity\Core\AbstractComponent;
19
20
/**
21
 * @author Daniel West <[email protected]>
22
 */
23
class AutoRoutePrefixMetadataFactory implements ResourceMetadataFactoryInterface
24
{
25
    private ResourceMetadataFactoryInterface $decorated;
26
27
    public function __construct(ResourceMetadataFactoryInterface $decorated)
28
    {
29
        $this->decorated = $decorated;
30
    }
31
32
    public function create(string $resourceClass): ResourceMetadata
33
    {
34
        $resourceMetadata = $this->decorated->create($resourceClass);
35
        if (!is_subclass_of($resourceClass, AbstractComponent::class)) {
36
            return $resourceMetadata;
37
        }
38
        return $this->prefixComponentRoute($resourceMetadata);
39
    }
40
41
    private function prefixComponentRoute(ResourceMetadata $resourceMetadata): ResourceMetadata
42
    {
43
        $routePrefixParts = ['component'];
44
        if ($currentRoutePrefix = $resourceMetadata->getAttribute('route_prefix')) {
45
            $routePrefixParts[] = trim($currentRoutePrefix, '/');
46
        }
47
        $newRoutePrefix = '/' . implode('/', $routePrefixParts);
48
49
        return $resourceMetadata->withAttributes([
50
            'route_prefix' => $newRoutePrefix,
51
        ]);
52
    }
53
}
54