EntityToIdObjectTransformer::reverseTransform()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 15
cp 0
rs 9.6333
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 12
1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
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 FOS\RestBundle\Form\Transformer;
13
14
use Doctrine\Common\Persistence\ObjectManager;
15
use Symfony\Component\Form\DataTransformerInterface;
16
use Symfony\Component\Form\Exception\TransformationFailedException;
17
18
/**
19
 * Class EntityToIdObjectTransformer.
20
 *
21
 * @author Marc Juchli <[email protected]>
22
 *
23
 * @internal
24
 */
25
class EntityToIdObjectTransformer implements DataTransformerInterface
26
{
27
    private $om;
28
    private $entityName;
29
30
    public function __construct(ObjectManager $om, string $entityName)
31
    {
32
        $this->entityName = $entityName;
33
        $this->om = $om;
34
    }
35
36
    /**
37
     * Do nothing.
38
     *
39
     * @param object|null $object
40
     */
41
    public function transform($object): string
42
    {
43
        if (null === $object) {
44
            return '';
45
        }
46
47
        return current(array_values($this->om->getClassMetadata($this->entityName)->getIdentifierValues($object)));
48
    }
49
50
    /**
51
     * Transforms an array including an identifier to an object.
52
     *
53
     * @param array $idObject
54
     *
55
     * @throws TransformationFailedException if object is not found
56
     */
57
    public function reverseTransform($idObject): ?object
58
    {
59
        if (!is_array($idObject)) {
60
            return null;
61
        }
62
63
        $identifier = current(array_values($this->om->getClassMetadata($this->entityName)->getIdentifier()));
64
        $id = $idObject[$identifier];
65
66
        $object = $this->om
67
            ->getRepository($this->entityName)
68
            ->findOneBy([$identifier => $id]);
69
70
        if (null === $object) {
71
            throw new TransformationFailedException(sprintf('An object with identifier key "%s" and value "%s" does not exist!', $identifier, $id));
72
        }
73
74
        return $object;
75
    }
76
}
77