Failed Conditions
Pull Request — master (#6743)
by Grégoire
11:31
created

EntityRepository::getClassName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ORM;
6
7
use Doctrine\Common\Collections\Collection;
8
use Doctrine\Common\Collections\Criteria;
9
use Doctrine\Common\Collections\Selectable;
10
use Doctrine\Common\Persistence\ObjectRepository;
11
use Doctrine\Common\Util\Inflector;
12
use Doctrine\ORM\Mapping\ClassMetadata;
13
use Doctrine\ORM\Query\ResultSetMappingBuilder;
14
use Doctrine\ORM\Repository\Exception\InvalidMagicMethodCall;
15
use function array_slice;
16
use function lcfirst;
17
use function sprintf;
18
use function strpos;
19
use function substr;
20
21
/**
22
 * An EntityRepository serves as a repository for entities with generic as well as
23
 * business specific methods for retrieving entities.
24
 *
25
 * This class is designed for inheritance and users can subclass this class to
26
 * write their own repositories with business-specific methods to locate entities.
27
 */
28
class EntityRepository implements ObjectRepository, Selectable
29
{
30
    /** @var string */
31
    protected $entityName;
32
33
    /** @var EntityManagerInterface */
34
    protected $em;
35
36
    /** @var ClassMetadata */
37
    protected $class;
38
39
    /**
40
     * Initializes a new <tt>EntityRepository</tt>.
41
     *
42
     * @param EntityManagerInterface $em    The EntityManager to use.
43
     * @param Mapping\ClassMetadata  $class The class descriptor.
44
     */
45 137
    public function __construct(EntityManagerInterface $em, Mapping\ClassMetadata $class)
46
    {
47 137
        $this->entityName = $class->getClassName();
48 137
        $this->em         = $em;
49 137
        $this->class      = $class;
50 137
    }
51
52
    /**
53
     * Creates a new QueryBuilder instance that is prepopulated for this entity name.
54
     *
55
     * @param string $alias
56
     * @param string $indexBy The index for the from.
57
     *
58
     * @return QueryBuilder
59
     */
60 8
    public function createQueryBuilder($alias, $indexBy = null)
61
    {
62 8
        return $this->em->createQueryBuilder()
63 8
            ->select($alias)
64 8
            ->from($this->entityName, $alias, $indexBy);
65
    }
66
67
    /**
68
     * Creates a new result set mapping builder for this entity.
69
     *
70
     * The column naming strategy is "INCREMENT".
71
     *
72
     * @param string $alias
73
     *
74
     * @return ResultSetMappingBuilder
75
     */
76 1
    public function createResultSetMappingBuilder($alias)
77
    {
78 1
        $rsm = new ResultSetMappingBuilder($this->em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT);
79 1
        $rsm->addRootEntityFromClassMetadata($this->entityName, $alias);
80
81 1
        return $rsm;
82
    }
83
84
    /**
85
     * Clears the repository, causing all managed entities to become detached.
86
     */
87
    public function clear()
88
    {
89
        $this->em->clear($this->class->getRootClassName());
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 15
    public function find($id, $lockMode = null, $lockVersion = null)
104
    {
105 15
        return $this->em->find($this->entityName, $id, $lockMode, $lockVersion);
0 ignored issues
show
Unused Code introduced by
The call to Doctrine\Common\Persistence\ObjectManager::find() has too many arguments starting with $lockMode. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

105
        return $this->em->/** @scrutinizer ignore-call */ find($this->entityName, $id, $lockMode, $lockVersion);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
106
    }
107
108
    /**
109
     * Finds all entities in the repository.
110
     *
111
     * @return object[] The entities.
112
     */
113 33
    public function findAll()
114
    {
115 33
        return $this->findBy([]);
116
    }
117
118
    /**
119
     * Finds entities by a set of criteria.
120
     *
121
     * @param mixed[]  $criteria
122
     * @param mixed[]  $orderBy
123
     * @param int|null $limit
124
     * @param int|null $offset
125
     *
126
     * @return object[] The objects.
127
     *
128
     * @todo guilhermeblanco Change orderBy to use a blank array by default (requires Common\Persistence change).
129
     */
130 64
    public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null)
131
    {
132 64
        $persister = $this->em->getUnitOfWork()->getEntityPersister($this->entityName);
133
134 64
        return $persister->loadAll($criteria, $orderBy !== null ? $orderBy : [], $limit, $offset);
135
    }
136
137
    /**
138
     * Finds a single entity by a set of criteria.
139
     *
140
     * @param mixed[] $criteria
141
     * @param mixed[] $orderBy
142
     *
143
     * @return object|null The entity instance or NULL if the entity can not be found.
144
     */
145 20
    public function findOneBy(array $criteria, array $orderBy = [])
146
    {
147 20
        $persister = $this->em->getUnitOfWork()->getEntityPersister($this->entityName);
148
149 20
        return $persister->load($criteria, null, null, [], null, 1, $orderBy);
150
    }
151
152
    /**
153
     * Counts entities by a set of criteria.
154
     *
155
     * @todo Add this method to `ObjectRepository` interface in the next major release
156
     *
157
     * @param Criteria[] $criteria
158
     *
159
     * @return int The cardinality of the objects that match the given criteria.
160
     */
161 2
    public function count(array $criteria)
162
    {
163 2
        return $this->em->getUnitOfWork()->getEntityPersister($this->entityName)->count($criteria);
164
    }
165
166
    /**
167
     * Adds support for magic method calls.
168
     *
169
     * @param string  $method
170
     * @param mixed[] $arguments
171
     *
172
     * @return mixed The returned value from the resolved method.
173
     *
174
     * @throws ORMException
175
     * @throws \BadMethodCallException If the method called is invalid.
176
     */
177 13
    public function __call($method, $arguments)
178
    {
179 13
        if (strpos($method, 'findBy') === 0) {
180 8
            return $this->resolveMagicCall('findBy', substr($method, 6), $arguments);
181
        }
182
183 5
        if (strpos($method, 'findOneBy') === 0) {
184 3
            return $this->resolveMagicCall('findOneBy', substr($method, 9), $arguments);
185
        }
186
187 2
        if (strpos($method, 'countBy') === 0) {
188 1
            return $this->resolveMagicCall('count', substr($method, 7), $arguments);
189
        }
190
191 1
        throw new \BadMethodCallException(
192 1
            sprintf(
193 1
                "Undefined method '%s'. The method name must start with either findBy, findOneBy or countBy!",
194 1
                $method
195
            )
196
        );
197
    }
198
199
    /**
200
     * @return string
201
     */
202
    protected function getEntityName()
203
    {
204
        return $this->entityName;
205
    }
206
207
    /**
208
     * @return string
209
     */
210
    public function getClassName()
211
    {
212
        return $this->getEntityName();
213
    }
214
215
    /**
216
     * @return EntityManagerInterface
217
     */
218
    protected function getEntityManager()
219
    {
220
        return $this->em;
221
    }
222
223
    /**
224
     * @return Mapping\ClassMetadata
225
     */
226
    protected function getClassMetadata()
227
    {
228
        return $this->class;
229
    }
230
231
    /**
232
     * Select all elements from a selectable that match the expression and
233
     * return a new collection containing these elements.
234
     *
235
     * @return Collection|object[]
236
     */
237 26
    public function matching(Criteria $criteria)
238
    {
239 26
        $persister = $this->em->getUnitOfWork()->getEntityPersister($this->entityName);
240
241 26
        return new LazyCriteriaCollection($persister, $criteria);
242
    }
243
244
    /**
245
     * Resolves a magic method call to the proper existent method at `EntityRepository`.
246
     *
247
     * @param string  $method    The method to call
248
     * @param string  $by        The property name used as condition
249
     * @param mixed[] $arguments The arguments to pass at method call
250
     *
251
     * @throws ORMException If the method called is invalid or the requested field/association does not exist.
252
     *
253
     * @return mixed
254
     */
255 12
    private function resolveMagicCall($method, $by, array $arguments)
256
    {
257 12
        if (! $arguments) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $arguments of type array<mixed,mixed> is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
258 1
            throw InvalidMagicMethodCall::onMissingParameter($method . $by);
259
        }
260
261 11
        $fieldName = lcfirst(Inflector::classify($by));
262
263 11
        if ($this->class->getProperty($fieldName) === null) {
264 1
            throw InvalidMagicMethodCall::becauseFieldNotFoundIn(
265 1
                $this->entityName,
266 1
                $fieldName,
267 1
                $method . $by
268
            );
269
        }
270
271 10
        return $this->{$method}([$fieldName => $arguments[0]], ...array_slice($arguments, 1));
272
    }
273
}
274