/
EntityToIdTransformer.php
83 lines (68 loc) · 2.48 KB
/
EntityToIdTransformer.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
<?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\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Collections\Collection;
class EntityToIdTransformer implements DataTransformerInterface
{
private $choiceList;
public function __construct(EntityChoiceList $choiceList)
{
$this->choiceList = $choiceList;
}
/**
* Transforms entities into choice keys.
*
* @param Collection|object $entity A collection of entities, a single entity or NULL
*
* @return mixed An array of choice keys, a single key or NULL
*/
public function transform($entity)
{
if (null === $entity || '' === $entity) {
return '';
}
if (!is_object($entity)) {
throw new UnexpectedTypeException($entity, 'object');
}
if ($entity instanceof Collection) {
throw new \InvalidArgumentException('Expected an object, but got a collection. Did you forget to pass "multiple=true" to an entity field?');
}
if (count($this->choiceList->getIdentifier()) > 1) {
// load all choices
$availableEntities = $this->choiceList->getEntities();
return array_search($entity, $availableEntities);
}
return current($this->choiceList->getIdentifierValues($entity));
}
/**
* Transforms choice keys into entities.
*
* @param mixed $key An array of keys, a single key or NULL
*
* @return Collection|object A collection of entities, a single entity or NULL
*/
public function reverseTransform($key)
{
if ('' === $key || null === $key) {
return null;
}
if (count($this->choiceList->getIdentifier()) > 1 && !is_numeric($key)) {
throw new UnexpectedTypeException($key, 'numeric');
}
if (!($entities = $this->choiceList->getEntitiesByKeys(array($key)))) {
throw new TransformationFailedException(sprintf('The entity with key "%s" could not be found', $key));
}
return $entities[0];
}
}