/
OneEntityToIdTransformer.php
executable file
·111 lines (91 loc) · 3 KB
/
OneEntityToIdTransformer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine\Form\DataTransformer;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\Exception\FormException;
use Symfony\Component\Form\Util\PropertyPath;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\NoResultException;
class OneEntityToIdTransformer implements DataTransformerInterface
{
private $em;
private $class;
private $property;
private $queryBuilder;
private $unitOfWork;
public function __construct(EntityManager $em, $class, $property, $queryBuilder)
{
if (null !== $queryBuilder && ! $queryBuilder instanceof \Closure) {
throw new UnexpectedTypeException($queryBuilder, '\Closure');
}
if (null === $class) {
throw new UnexpectedTypeException($class, 'string');
}
$this->em = $em;
$this->unitOfWork = $em->getUnitOfWork();
$this->class = $class;
$this->queryBuilder = $queryBuilder;
if ($property) {
$this->property = $property;
}
}
/**
* Fetch the id of the entity to populate the form
*/
public function transform($data)
{
if (null === $data) {
return null;
}
if (!$this->unitOfWork->isInIdentityMap($data)) {
throw new FormException('Entities passed to the choice field must be managed');
}
if ($this->property) {
$propertyPath = new PropertyPath($this->property);
return $propertyPath->getValue($data);
}
return current($this->unitOfWork->getEntityIdentifier($data));
}
/**
* Try to fetch the entity from its id in the database
*/
public function reverseTransform($data)
{
if (!$data) {
return null;
}
$em = $this->em;
$repository = $em->getRepository($this->class);
if ($qb = $this->queryBuilder) {
// Call the closure with the repository and the id
$qb = $qb($repository, $data);
try {
$result = $qb->getQuery()->getSingleResult();
} catch (NoResultException $e) {
$result = null;
}
} else {
// Defaults to find()
if ($this->property) {
$result = $repository->findOneBy(array($this->property => $data));
} else {
$result = $repository->find($data);
}
}
if (!$result) {
throw new TransformationFailedException('Can not find entity');
}
return $result;
}
}