Test Failed
Pull Request — main (#140)
by Daniel
04:22
created

UserResourceMetadataCollectionFactory::create()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 19
nc 4
nop 1
dl 0
loc 30
rs 9.0111
c 1
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\ApiPlatform\Metadata\Resource;
15
16
use ApiPlatform\Metadata\ApiResource;
17
use ApiPlatform\Metadata\Get;
18
use ApiPlatform\Metadata\HttpOperation;
19
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
20
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
21
use Silverback\ApiComponentsBundle\Entity\User\AbstractUser;
22
23
/**
24
 * Adds a /me endpoint.
25
 *
26
 * @author Daniel West <[email protected]>
27
 */
28
class UserResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface
29
{
30
    private ResourceMetadataCollectionFactoryInterface $decorated;
31
32
    public function __construct(ResourceMetadataCollectionFactoryInterface $decorated)
33
    {
34
        $this->decorated = $decorated;
35
    }
36
37
    public function create(string $resourceClass): ResourceMetadataCollection
38
    {
39
        $resourceMetadata = $this->decorated->create($resourceClass);
40
        if (!is_a($resourceClass, AbstractUser::class, true)) {
41
            return $resourceMetadata;
42
        }
43
44
        $newResources = [];
45
        /** @var ApiResource $resourceMetadatum */
46
        foreach ($resourceMetadata as $resourceMetadatum) {
47
            $operations = $resourceMetadatum->getOperations();
48
            if ($operations) {
49
                foreach ($operations as $operation) {
50
                    if ($operation instanceof Get) {
51
                        $newOperation = (new HttpOperation(HttpOperation::METHOD_GET, '/me.{_format}'))
52
                            ->withShortName($operation->getShortName());
53
                        $operations->add(
54
                            'me',
55
                            $newOperation
56
                                ->withName('me')
57
                                ->withSecurity('is_granted("IS_AUTHENTICATED_FULLY")')
58
                                ->withClass($operation->getClass())
59
                        );
60
                    }
61
                }
62
            }
63
            $newResources[] = $resourceMetadatum;
64
        }
65
66
        return new ResourceMetadataCollection($resourceClass, $newResources);
67
    }
68
}
69