Completed
Push — master ( 26547b...4331e3 )
by Guillaume
03:13
created

EntityToIdObjectTransformer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 4
dl 0
loc 65
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A transform() 0 8 2
A reverseTransform() 0 17 2
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: DIEU
5
 * Date: 21/06/2017
6
 * Time: 01:20
7
 */
8
9
namespace Starkerxp\StructureBundle\Services;
10
11
use Doctrine\Common\Persistence\ObjectManager;
12
use Symfony\Component\Form\DataTransformerInterface;
13
use Symfony\Component\Form\Exception\TransformationFailedException;
14
15
class EntityToIdObjectTransformer implements DataTransformerInterface
16
{
17
    /**
18
     * @var ObjectManager
19
     */
20
    private $om;
21
22
    /**
23
     * @var string
24
     */
25
    private $entityName;
26
27
    /**
28
     * @param ObjectManager $om
29
     * @param string        $entityName
30
     */
31
    public function __construct(ObjectManager $om, $entityName)
32
    {
33
        $this->entityName = $entityName;
34
        $this->om = $om;
35
    }
36
37
    /**
38
     * Do nothing.
39
     *
40
     * @param object|null $object
41
     *
42
     * @return string
43
     */
44
    public function transform($object)
45
    {
46
        if (null === $object) {
47
            return '';
48
        }
49
50
        return current(array_values($this->om->getClassMetadata($this->entityName)->getIdentifierValues($object)));
51
    }
52
53
    /**
54
     * Transforms an array including an identifier to an object.
55
     *
56
     * @param array $idObject
57
     *
58
     * @throws TransformationFailedException if object is not found
59
     *
60
     * @return object|null
61
     */
62
    public function reverseTransform($idObject)
63
    {
64
        $identifier = current(array_values($this->om->getClassMetadata($this->entityName)->getIdentifier()));
65
66
        $object = $this->om
67
            ->getRepository($this->entityName)
68
            ->findOneBy([$identifier => $idObject]);
69
70
        if (null === $object) {
71
            throw new TransformationFailedException(sprintf(
72
                'An object with identifier key "%s" and value "%s" does not exist!',
73
                $identifier, $idObject
74
            ));
75
        }
76
77
        return $object;
78
    }
79
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
80