Completed
Push — master ( 463605...f15859 )
by Guillaume
16:46
created

AbstractManager::findBy()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 4
1
<?php
2
3
namespace Starkerxp\StructureBundle\Manager;
4
5
use DateTime;
6
use Doctrine\ORM\EntityManager;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Starkerxp\StructureBundle\Manager\EntityManager.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use Doctrine\ORM\EntityRepository;
8
use Starkerxp\StructureBundle\Entity\Entity;
9
use Starkerxp\StructureBundle\Manager\Exception\ObjectClassNotAllowedException;
10
11
abstract class AbstractManager implements ManagerInterface
12
{
13
    /** @var EntityManager */
14
    protected $entityManager;
15
16
    /** @var EntityRepository */
17
    protected $repository;
18
19
    private $modeTransactionnal = false;
20
21
    /**
22
     * @param EntityManager $entityManager
23
     * @param $entity
24
     */
25
    public function __construct(EntityManager $entityManager, $entity)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. 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...
26
    {
27
        $this->entityManager = $entityManager;
28
        $this->repository = $this->entityManager->getRepository($entity);
29
    }
30
31
    /**
32
     * @param Entity $object
33
     *
34
     * @return Entity|boolean
35
     *
36
     * @throws ObjectClassNotAllowedException
37
     */
38
    public function insert(Entity $object)
39
    {
40
        if (!$this->getSupport($object)) {
41
            throw new ObjectClassNotAllowedException();
42
        }
43
        $object->setCreatedAt(new DateTime());
44
        $this->entityManager->persist($object);
45
        $this->flush();
46
47
        return $object;
48
    }
49
50
    /**
51
     * Permet de gérer un flush en mode transactions manuelles.
52
     */
53
    private function flush()
54
    {
55
        if ($this->modeTransactionnal) {
56
            $this->entityManager->commit();
57
        }
58
        $this->entityManager->flush();
59
    }
60
61
    /**
62
     * @param Entity $object
63
     *
64
     * @return Entity|boolean
65
     *
66
     * @throws ObjectClassNotAllowedException
67
     */
68
    public function update(Entity $object)
69
    {
70
        if (!$this->getSupport($object)) {
71
            throw new ObjectClassNotAllowedException();
72
        }
73
        $object->setUpdatedAt(new DateTime());
74
        $this->flush();
75
76
        return $object;
77
    }
78
79
    /**
80
     * @param Entity $object
81
     * @throws ObjectClassNotAllowedException
82
     */
83
    public function delete(Entity $object)
84
    {
85
        if (!$this->getSupport($object)) {
86
            throw new ObjectClassNotAllowedException();
87
        }
88
        $this->entityManager->remove($object);
89
        $this->flush();
90
    }
91
92
    /**
93
     * Finds an entity by its primary key / identifier.
94
     *
95
     * @param mixed $id The identifier.
96
     * @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants
97
     *                              or NULL if no specific lock mode should be used
98
     *                              during the search.
99
     * @param int|null $lockVersion The lock version.
100
     *
101
     * @return object|null The entity instance or NULL if the entity can not be found.
102
     */
103
    public function find($id, $lockMode = null, $lockVersion = null)
104
    {
105
        return $this->repository->find($id, $lockMode, $lockVersion);
106
    }
107
108
    /**
109
     * Finds a single entity by a set of criteria.
110
     *
111
     * @param array $criteria
112
     * @param array|null $orderBy
113
     *
114
     * @return object|null The entity instance or NULL if the entity can not be found.
115
     */
116
    public function findOneBy(array $criteria, array $orderBy = null)
117
    {
118
        return $this->repository->findOneBy($criteria, $orderBy);
119
    }
120
121
    /**
122
     * Finds entities by a set of criteria.
123
     *
124
     * @param array $criteria
125
     * @param array|null $orderBy
126
     * @param int|null $limit
127
     * @param int|null $offset
128
     *
129
     * @return array The objects.
130
     */
131
    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
132
    {
133
        return $this->repository->findBy($criteria, $orderBy, $limit, $offset);
134
    }
135
136
    /**
137
     * Finds all entities in the repository.
138
     *
139
     * @return array The entities.
140
     */
141
    public function findAll()
142
    {
143
        return $this->repository->findAll();
144
    }
145
146
    /**
147
     * @return EntityRepository
148
     */
149
    public function getRepository()
150
    {
151
        return $this->repository;
152
    }
153
154
    /**
155
     * Vide l'UnitOfWork de l'entity manager.
156
     */
157
    public function clear()
158
    {
159
        $this->entityManager->clear();
160
    }
161
162
    /**
163
     * Permet de passer en gestion des transations manuelles. (Conseillé par SensioLabs).
164
     */
165
    public function beginTransaction()
166
    {
167
        $this->modeTransactionnal = true;
168
        $this->entityManager->beginTransaction();
169
    }
170
171
    /**
172
     * Dans le cas d'une gestion des transactions manuelles en cas d'échec on rollback le tout.
173
     */
174
    public function rollback()
175
    {
176
        if ($this->modeTransactionnal) {
177
            $this->entityManager->rollback();
178
            $this->entityManager->close();
179
            $this->modeTransactionnal = false;
180
        }
181
    }
182
183
184
    protected function exportFields(array $array, array $fields = [])
185
    {
186
        if (empty($fields)) {
187
            return $array;
188
        }
189
        $export = [];
190
        foreach ($fields as $row) {
191
            $export[$row] = $array[$row];
192
        }
193
        return $export;
194
    }
195
196
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
197