]> Raphaël G. Git Repositories - airbundle/blob - Transformer/DanceTransformer.php
Rename Command/Command in Command
[airbundle] / Transformer / DanceTransformer.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys AirBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
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 Rapsys\AirBundle\Transformer;
13
14 use Doctrine\Common\Collections\ArrayCollection;
15 use Doctrine\Common\Collections\Collection;
16 use Doctrine\ORM\EntityManagerInterface;
17
18 use Symfony\Component\Form\DataTransformerInterface;
19 use Symfony\Component\Form\Exception\TransformationFailedException;
20
21 use Rapsys\AirBundle\Entity\Dance;
22
23 /**
24 * {@inheritdoc}
25 */
26 class DanceTransformer implements DataTransformerInterface {
27 /**
28 * Public constructor
29 *
30 * @param EntityManagerInterface $manager The entity manager
31 */
32 public function __construct(private EntityManagerInterface $manager) {
33 }
34
35 /**
36 * Transforms a dance object array or collection to an int array
37 *
38 * @param Dance $dances The dance instances array
39 * @return array The dance ids
40 */
41 public function transform($dances) {
42 //Without dances
43 if (null === $dances) {
44 return [];
45 }
46
47 //With collection instance
48 if ($dances instanceof Collection) {
49 $dances = $dances->toArray();
50 }
51
52 //Return dance ids
53 return array_map(function ($d) { return $d->getId(); }, $dances);
54 }
55
56 /**
57 * Transforms an int array to a dance object collection
58 *
59 * @param array $ids
60 * @throws TransformationFailedException when object (dance) is not found
61 * @return array The dance instances array
62 */
63 public function reverseTransform($ids) {
64 //Without ids
65 if ('' === $ids || null === $ids) {
66 $ids = [];
67 //With ids
68 } else {
69 $ids = (array) $ids;
70 }
71
72 //Iterate on ids
73 foreach($ids as $k => $id) {
74 //Replace with dance instance
75 $ids[$k] = $this->manager->getRepository(Dance::class)->findOneById($id);
76
77 //Without dance
78 if (null === $ids[$k]) {
79 //Throw exception
80 throw new TransformationFailedException(sprintf('Dance with id "%d" does not exist!', $id));
81 }
82 }
83
84 //Return collection
85 return new ArrayCollection($ids);
86 }
87 }