1 <?php
declare(strict_types
=1);
4 * This file is part of the Rapsys AirBundle package.
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Rapsys\AirBundle\Transformer
;
14 use Doctrine\Common\Collections\ArrayCollection
;
15 use Doctrine\Common\Collections\Collection
;
16 use Doctrine\ORM\EntityManagerInterface
;
18 use Symfony\Component\Form\DataTransformerInterface
;
19 use Symfony\Component\Form\Exception\TransformationFailedException
;
21 use Rapsys\AirBundle\Entity\User
;
26 class SubscriptionTransformer
implements DataTransformerInterface
{
30 * @param EntityManagerInterface $manager The entity manager
32 public function __construct(private EntityManagerInterface
$manager) {
36 * Transforms a subscription object array or collection to an int array
38 * @param Collection|array $subscriptions The subscription instances array
39 * @return array The subscription ids
41 public function transform(mixed $subscriptions): mixed {
42 //Without subscriptions
43 if (null === $subscriptions) {
47 //With collection instance
48 if ($subscriptions instanceof Collection
) {
49 $subscriptions = $subscriptions->toArray();
52 //Return subscription ids
53 return array_map(function ($d) { return $d
->getId(); }, $subscriptions);
57 * Transforms an int array to a subscription object collection
60 * @throws TransformationFailedException when object (subscription) is not found
61 * @return Collection The subscription instances array
63 public function reverseTransform(mixed $ids): mixed {
65 if ('' === $ids || null === $ids) {
73 foreach($ids as $k => $id) {
74 //Replace with subscription instance
75 $ids[$k] = $this->manager
->getRepository(User
::class)->findOneById($id);
77 //Without subscription
78 if (null === $ids[$k]) {
80 throw new TransformationFailedException(sprintf('User with id "%d" does not exist!', $id));
85 return new ArrayCollection($ids);