StringToActorsTransformer::reverseTransform()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 23

Duplication

Lines 23
Ratio 100 %

Importance

Changes 0
Metric Value
dl 23
loc 23
rs 9.552
c 0
b 0
f 0
cc 4
nc 4
nop 1
1
<?php
2
namespace KI\PonthubBundle\Transformer;
3
4
use Doctrine\ORM\EntityManager;
5
use Doctrine\ORM\EntityRepository;
6
use KI\PonthubBundle\Entity\Actor;
7
use Symfony\Component\Form\DataTransformerInterface;
8
9 View Code Duplication
class StringToActorsTransformer implements DataTransformerInterface
10
{
11
    protected $manager;
12
    protected $actorRepository;
13
14
    public function __construct(EntityManager $manager, EntityRepository $actorRepository)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $manager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
15
    {
16
        $this->manager         = $manager;
17
        $this->actorRepository = $actorRepository;
18
    }
19
20
    // En théorie, ne sera jamais utilisé
21
    public function transform($actors)
22
    {
23
        return '';
24
    }
25
26
    public function reverseTransform($string)
27
    {
28
        if (!$string) {
29
            return null;
30
        }
31
32
        $array = new \Doctrine\Common\Collections\ArrayCollection();
33
        foreach (explode(',', $string) as $actor) {
34
            $item = $this->actorRepository->findOneByName($actor);
35
36
            if ($item instanceof Actor) {
37
                $array->add($item);
38
            } else {
39
                $actorItem = new Actor();
40
                $actorItem->setName($actor);
41
                $this->manager->persist($actorItem);
42
                $array->add($actorItem);
43
            }
44
        }
45
        $this->manager->flush();
46
47
        return $array;
48
    }
49
}
50