Completed
Pull Request — 2.0 (#996)
by
unknown
02:54
created

IdentifierManagerTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 3
dl 0
loc 55
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
C normalizeIdentifiers() 0 38 8
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[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
namespace ApiPlatform\Core\Bridge\Doctrine\Orm\Util;
13
14
use ApiPlatform\Core\Exception\PropertyNotFoundException;
15
use Doctrine\Common\Persistence\ObjectManager;
16
17
/**
18
 * @internal
19
 */
20
trait IdentifierManagerTrait
21
{
22
    private $propertyNameCollectionFactory;
23
    private $propertyMetadataFactory;
24
25
    /**
26
     * Transform and check the identifier, composite or not.
27
     *
28
     * @param int|string    $id
29
     * @param ObjectManager $manager
30
     * @param string        $resourceClass
31
     *
32
     * @throws PropertyNotFoundException
33
     *
34
     * @return array
35
     */
36
    public function normalizeIdentifiers($id, ObjectManager $manager, string $resourceClass): array
37
    {
38
        $identifierValues = [$id];
39
        $doctrineMetadataIdentifier = $manager->getClassMetadata($resourceClass)->getIdentifier();
40
41
        if (2 <= count($doctrineMetadataIdentifier)) {
42
            $identifiers = explode(';', $id);
43
            $identifiersMap = [];
44
45
            // first transform identifiers to a proper key/value array
46
            foreach ($identifiers as $identifier) {
47
                $keyValue = explode('=', $identifier);
48
                $identifiersMap[$keyValue[0]] = $keyValue[1];
49
            }
50
        }
51
52
        $identifiers = [];
53
        $i = 0;
54
55
        foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) {
56
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName);
57
58
            $identifier = $propertyMetadata->isIdentifier();
59
            if (null === $identifier || false === $identifier) {
60
                continue;
61
            }
62
63
            $identifier = !isset($identifiersMap) ? $identifierValues[$i] ?? null : $identifiersMap[$propertyName] ?? null;
64
            if (null === $identifier) {
65
                throw new PropertyNotFoundException(sprintf('Invalid identifier "%s", "%s" has not been found.', $id, $propertyName));
66
            }
67
68
            $identifiers[$propertyName] = $identifier;
69
            ++$i;
70
        }
71
72
        return $identifiers;
73
    }
74
}
75