]> Raphaël G. Git Repositories - airbundle/blob - Transformer/SubscriptionTransformer.php
Use getObject event args member function instead of deprecated getEntity
[airbundle] / Transformer / SubscriptionTransformer.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\User;
22
23 /**
24 * {@inheritdoc}
25 */
26 class SubscriptionTransformer 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 subscription object array or collection to an int array
37 *
38 * @param Collection|array $subscriptions The subscription instances array
39 * @return array The subscription ids
40 */
41 public function transform(mixed $subscriptions): mixed {
42 //Without subscriptions
43 if (null === $subscriptions) {
44 return [];
45 }
46
47 //With collection instance
48 if ($subscriptions instanceof Collection) {
49 $subscriptions = $subscriptions->toArray();
50 }
51
52 //Return subscription ids
53 return array_map(function ($d) { return $d->getId(); }, $subscriptions);
54 }
55
56 /**
57 * Transforms an int array to a subscription object collection
58 *
59 * @param array $ids
60 * @throws TransformationFailedException when object (subscription) is not found
61 * @return Collection The subscription instances array
62 */
63 public function reverseTransform(mixed $ids): mixed {
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 subscription instance
75 $ids[$k] = $this->manager->getRepository(User::class)->findOneById($id);
76
77 //Without subscription
78 if (null === $ids[$k]) {
79 //Throw exception
80 throw new TransformationFailedException(sprintf('User with id "%d" does not exist!', $id));
81 }
82 }
83
84 //Return collection
85 return new ArrayCollection($ids);
86 }
87 }