Passed
Pull Request — master (#54)
by Vincent
06:15
created

prefixRoute()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 11
ccs 0
cts 7
cp 0
rs 10
cc 3
nc 2
nop 2
crap 12
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\ApiPlatform\Metadata\Resource;
15
16
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
17
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
18
use Silverback\ApiComponentBundle\Entity\Core\AbstractComponent;
19
use Silverback\ApiComponentBundle\Entity\Core\AbstractPageData;
20
21
/**
22
 * @author Daniel West <[email protected]>
23
 */
24
class RoutingPrefixResourceMetadataFactory implements ResourceMetadataFactoryInterface
25
{
26
    private ResourceMetadataFactoryInterface $decorated;
27
28
    public function __construct(ResourceMetadataFactoryInterface $decorated)
29
    {
30
        $this->decorated = $decorated;
31
    }
32
33
    public function create(string $resourceClass): ResourceMetadata
34
    {
35
        $resourceMetadata = $this->decorated->create($resourceClass);
36
37
        $routePrefixParts = [];
38
39
        if (is_subclass_of($resourceClass, AbstractComponent::class)) {
40
            $routePrefixParts[] = 'component';
41
        } elseif (is_subclass_of($resourceClass, AbstractPageData::class)) {
42
            $routePrefixParts[] = 'page_data';
43
        } else {
44
            $reflection = new \ReflectionClass($resourceClass);
45
            $namespace = $reflection->getNamespaceName();
46
            $acbNamespace = 'Silverback\ApiComponentBundle\\';
47
48
            if (0 === strpos($namespace, $acbNamespace)) {
49
                $routePrefixParts[] = '_';
50
            }
51
        }
52
53
        if (!\count($routePrefixParts)) {
54
            return $resourceMetadata;
55
        }
56
57
        return $this->prefixRoute($routePrefixParts, $resourceMetadata);
58
    }
59
60
    private function prefixRoute(array $routePrefixParts, ResourceMetadata $resourceMetadata): ResourceMetadata
61
    {
62
        if ($currentRoutePrefix = $resourceMetadata->getAttribute('route_prefix')) {
63
            $routePrefixParts[] = trim($currentRoutePrefix, '/');
64
        }
65
        $newRoutePrefix = '/' . implode('/', $routePrefixParts);
66
67
        $attributes = $resourceMetadata->getAttributes() ?: [];
68
69
        return $resourceMetadata->withAttributes(array_merge($attributes, [
70
            'route_prefix' => $newRoutePrefix,
71
        ]));
72
    }
73
}
74