AbstractManager   A
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 203
Duplicated Lines 18.72 %

Coupling/Cohesion

Components 2
Dependencies 4

Importance

Changes 0
Metric Value
wmc 24
lcom 2
cbo 4
dl 38
loc 203
rs 10
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A insert() 14 14 3
A flush() 0 7 2
A update() 13 13 3
A delete() 11 11 3
A find() 0 4 1
A findOneBy() 0 4 1
A findBy() 0 4 1
A findAll() 0 4 1
A getRepository() 0 4 1
A clear() 0 4 1
A beginTransaction() 0 5 1
A rollback() 0 8 2
A exportFields() 0 12 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\AbstractEntity;
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 AbstractEntity $object
33
     *
34
     * @return AbstractEntity|boolean
35
     *
36
     * @throws ObjectClassNotAllowedException
37
     */
38 View Code Duplication
    public function insert(AbstractEntity $object)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
39
    {
40
        if (!$this->getSupport($object)) {
41
            throw new ObjectClassNotAllowedException();
42
        }
43
        $object->setCreatedAt(new DateTime());
44
        if (method_exists($this, "preInsert")) {
45
            $this->preInsert($object);
0 ignored issues
show
Bug introduced by
The method preInsert() does not exist on Starkerxp\StructureBundle\Manager\AbstractManager. Did you maybe mean insert()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
46
        }
47
        $this->entityManager->persist($object);
48
        $this->flush();
49
50
        return $object;
51
    }
52
53
    /**
54
     * Permet de gérer un flush en mode transactions manuelles.
55
     */
56
    private function flush()
57
    {
58
        if ($this->modeTransactionnal) {
59
            $this->entityManager->commit();
60
        }
61
        $this->entityManager->flush();
62
    }
63
64
    /**
65
     * @param AbstractEntity $object
66
     *
67
     * @return AbstractEntity|boolean
68
     *
69
     * @throws ObjectClassNotAllowedException
70
     */
71 View Code Duplication
    public function update(AbstractEntity $object)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
72
    {
73
        if (!$this->getSupport($object)) {
74
            throw new ObjectClassNotAllowedException();
75
        }
76
        $object->setUpdatedAt(new DateTime());
77
        if (method_exists($this, "preUpdate")) {
78
            $this->preUpdate($object);
0 ignored issues
show
Bug introduced by
The method preUpdate() does not exist on Starkerxp\StructureBundle\Manager\AbstractManager. Did you maybe mean update()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
79
        }
80
        $this->flush();
81
82
        return $object;
83
    }
84
85
    /**
86
     * @param Entity $object
87
     * @throws ObjectClassNotAllowedException
88
     */
89 View Code Duplication
    public function delete(AbstractEntity $object)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
90
    {
91
        if (!$this->getSupport($object)) {
92
            throw new ObjectClassNotAllowedException();
93
        }
94
        if (method_exists($this, "preDelete")) {
95
            $this->preDelete($object);
0 ignored issues
show
Bug introduced by
The method preDelete() does not exist on Starkerxp\StructureBundle\Manager\AbstractManager. Did you maybe mean delete()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
96
        }
97
        $this->entityManager->remove($object);
98
        $this->flush();
99
    }
100
101
    /**
102
     * Finds an entity by its primary key / identifier.
103
     *
104
     * @param mixed $id The identifier.
105
     * @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants
106
     *                              or NULL if no specific lock mode should be used
107
     *                              during the search.
108
     * @param int|null $lockVersion The lock version.
109
     *
110
     * @return Entity|object|null The entity instance or NULL if the entity can not be found.
111
     */
112
    public function find($id, $lockMode = null, $lockVersion = null)
113
    {
114
        return $this->repository->find($id, $lockMode, $lockVersion);
115
    }
116
117
    /**
118
     * Finds a single entity by a set of criteria.
119
     *
120
     * @param array $criteria
121
     * @param array|null $orderBy
122
     *
123
     * @return Entity|object|null The entity instance or NULL if the entity can not be found.
124
     */
125
    public function findOneBy(array $criteria, array $orderBy = null)
126
    {
127
        return $this->repository->findOneBy($criteria, $orderBy);
128
    }
129
130
    /**
131
     * Finds entities by a set of criteria.
132
     *
133
     * @param array $criteria
134
     * @param array|null $orderBy
135
     * @param int|null $limit
136
     * @param int|null $offset
137
     *
138
     * @return Entity[] The objects.
139
     */
140
    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
141
    {
142
        return $this->repository->findBy($criteria, $orderBy, $limit, $offset);
143
    }
144
145
    /**
146
     * Finds all entities in the repository.
147
     *
148
     * @return array The entities.
149
     */
150
    public function findAll()
151
    {
152
        return $this->repository->findAll();
153
    }
154
155
    /**
156
     * @return EntityRepository
157
     */
158
    public function getRepository()
159
    {
160
        return $this->repository;
161
    }
162
163
    /**
164
     * Vide l'UnitOfWork de l'entity manager.
165
     */
166
    public function clear()
167
    {
168
        $this->entityManager->clear();
169
    }
170
171
    /**
172
     * Permet de passer en gestion des transations manuelles. (Conseillé par SensioLabs).
173
     */
174
    public function beginTransaction()
175
    {
176
        $this->modeTransactionnal = true;
177
        $this->entityManager->beginTransaction();
178
    }
179
180
    /**
181
     * Dans le cas d'une gestion des transactions manuelles en cas d'échec on rollback le tout.
182
     */
183
    public function rollback()
184
    {
185
        if ($this->modeTransactionnal) {
186
            $this->entityManager->rollback();
187
            $this->entityManager->close();
188
            $this->modeTransactionnal = false;
189
        }
190
    }
191
192
    /**
193
     * Permet d'extraire uniquement les champs désirés.
194
     *
195
     * @param array $array
196
     * @param array $fields
197
     *
198
     * @return array
199
     */
200
    protected function exportFields(array $array, array $fields = [])
201
    {
202
        if (empty($fields)) {
203
            return $array;
204
        }
205
        $export = [];
206
        foreach ($fields as $row) {
207
            $export[$row] = $array[$row];
208
        }
209
210
        return $export;
211
    }
212
213
}
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...
214