GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( b7113a...02ec9b )
by Ross
25s queued 16s
created

AbstractEntityRepository::getOneBy()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
ccs 0
cts 7
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Repositories;
4
5
use Doctrine\Common\Collections\Criteria;
6
use Doctrine\DBAL\Types\ConversionException;
7
use Doctrine\ORM\EntityManagerInterface;
8
use Doctrine\ORM\EntityRepository;
9
use Doctrine\ORM\LazyCriteriaCollection;
10
use Doctrine\ORM\Mapping\ClassMetadata;
11
use Doctrine\ORM\NativeQuery;
12
use Doctrine\ORM\Query;
13
use Doctrine\ORM\QueryBuilder;
14
use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\NamespaceHelper;
15
use EdmondsCommerce\DoctrineStaticMeta\Entity\Factory\EntityFactoryInterface;
16
use EdmondsCommerce\DoctrineStaticMeta\Entity\Interfaces\EntityInterface;
17
use EdmondsCommerce\DoctrineStaticMeta\Exception\DoctrineStaticMetaException;
18
19
/**
20
 * Class AbstractEntityRepository
21
 *
22
 * This provides a base class that handles instantiating the correctly configured EntityRepository and provides an
23
 * extensible baseline for further customisation
24
 *
25
 * We have extracted an interface from the standard Doctrine EntityRepository and implemented that
26
 * However, so we can add type safety, we can't "actually" implement it
27
 *
28
 * We have also deliberately left out the magic calls. Please make real methods in your concrete repository class
29
 *
30
 * Note, there are quite a few PHPMD warnings, however it needs to respect the legacy interface so they are being
31
 * suppressed
32
 *
33
 * @package EdmondsCommerce\DoctrineStaticMeta\Entity\Repositories
34
 * @SuppressWarnings(PHPMD.TooManyPublicMethods)
35
 * @SuppressWarnings(PHPMD.ExcessivePublicCount)
36
 * @SuppressWarnings(PHPMD.NumberOfChildren)
37
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
38
 */
39
abstract class AbstractEntityRepository implements EntityRepositoryInterface
40
{
41
    /**
42
     * @var EntityManagerInterface
43
     */
44
    protected $entityManager;
45
    /**
46
     * @var EntityRepository
47
     */
48
    protected $entityRepository;
49
    /**
50
     * @var string
51
     */
52
    protected $repositoryFactoryFqn;
53
    /**
54
     * @var ClassMetadata|null
55
     */
56
    protected $metaData;
57
    /**
58
     * @var NamespaceHelper
59
     */
60
    protected $namespaceHelper;
61
    /**
62
     * @var EntityFactoryInterface
63
     */
64
    private $entityFactory;
65
66
    /**
67
     * AbstractEntityRepositoryFactory constructor.
68
     *
69
     * @param EntityManagerInterface $entityManager
70
     * @param EntityFactoryInterface $entityFactory
71
     * @param NamespaceHelper|null   $namespaceHelper
72
     */
73
    public function __construct(
74
        EntityManagerInterface $entityManager,
75
        EntityFactoryInterface $entityFactory,
76
        NamespaceHelper $namespaceHelper
77
    ) {
78
        $this->entityManager   = $entityManager;
79
        $this->namespaceHelper = $namespaceHelper;
80
        $this->entityFactory   = $entityFactory;
81
        $this->initRepository();
82
    }
83
84
    protected function initRepository(): void
85
    {
86
        if (null === $this->metaData) {
87
            $entityFqn      = $this->getEntityFqn();
88
            $this->metaData = $this->entityManager->getClassMetadata($entityFqn);
89
        }
90
91
        $this->entityRepository = new EntityRepository($this->entityManager, $this->metaData);
92
    }
93
94
    protected function getEntityFqn(): string
95
    {
96
        return '\\' . \str_replace(
97
            [
98
                    'Entity\\Repositories',
99
                ],
100
            [
101
                    'Entities',
102
                ],
103
            $this->namespaceHelper->cropSuffix(static::class, 'Repository')
104
        );
105
    }
106
107
    public function getRandomResultFromQueryBuilder(QueryBuilder $queryBuilder, string $entityAlias): ?EntityInterface
108
    {
109
        $count = $this->getCountForQueryBuilder($queryBuilder, $entityAlias);
110
        if (0 === $count) {
111
            return null;
112
        }
113
114
        $queryBuilder->setMaxResults(1);
115
        $limitIndex = random_int(0, $count - 1);
116
        $results    = $queryBuilder->getQuery()
117
                                   ->setFirstResult($limitIndex)
118
                                   ->execute();
119
        $entity     = current($results);
120
        if (null === $entity) {
121
            return null;
122
        }
123
        $this->initialiseEntity($entity);
124
125
        return $entity;
126
    }
127
128
    public function getCountForQueryBuilder(QueryBuilder $queryBuilder, string $aliasToCount): int
129
    {
130
        $clone = clone $queryBuilder;
131
        $clone->select($queryBuilder->expr()->count($aliasToCount));
132
133
        return (int)$clone->getQuery()->getSingleScalarResult();
134
    }
135
136
    public function initialiseEntity(EntityInterface $entity)
137
    {
138
        $this->entityFactory->initialiseEntity($entity);
139
140
        return $entity;
141
    }
142
143
    /**
144
     * @return array|EntityInterface[]
145
     */
146
    public function findAll(): array
147
    {
148
        return $this->initialiseEntities($this->entityRepository->findAll());
149
    }
150
151
    public function initialiseEntities($entities)
152
    {
153
        foreach ($entities as $entity) {
154
            $this->initialiseEntity($entity);
155
        }
156
157
        return $entities;
158
    }
159
160
    /**
161
     * @param mixed    $id
162
     * @param int|null $lockMode
163
     * @param int|null $lockVersion
164
     *
165
     * @return EntityInterface
166
     * @throws DoctrineStaticMetaException
167
     */
168
    public function get($id, ?int $lockMode = null, ?int $lockVersion = null)
169
    {
170
        try {
171
            $entity = $this->find($id, $lockMode, $lockVersion);
172
        } catch (ConversionException $e) {
173
            $error = 'Failed getting by id ' . $id
174
                     . ', unless configured as an int ID entity, this should be a valid UUID';
175
            throw new DoctrineStaticMetaException($error, $e->getCode(), $e);
176
        }
177
        if ($entity === null) {
178
            throw new DoctrineStaticMetaException('Could not find the entity with id ' . $id);
179
        }
180
181
        return $this->initialiseEntity($entity);
182
    }
183
184
    /**
185
     * @param mixed    $id
186
     * @param int|null $lockMode
187
     * @param int|null $lockVersion
188
     *
189
     * @return EntityInterface|null
190
     */
191
    public function find($id, ?int $lockMode = null, ?int $lockVersion = null)
192
    {
193
        $entity = $this->entityRepository->find($id, $lockMode, $lockVersion);
194
        if (null === $entity) {
195
            return null;
196
        }
197
        if ($entity instanceof EntityInterface) {
198
            $this->initialiseEntity($entity);
199
200
            return $entity;
201
        }
202
    }
203
204
    /**
205
     * @param array      $criteria
206
     * @param array|null $orderBy
207
     *
208
     * @return EntityInterface
209
     */
210
    public function getOneBy(array $criteria, ?array $orderBy = null)
211
    {
212
        $result = $this->findOneBy($criteria, $orderBy);
213
        if ($result === null) {
214
            throw new \RuntimeException('Could not find the entity');
215
        }
216
217
        return $this->initialiseEntity($result);
218
    }
219
220
    /**
221
     * @param array      $criteria
222
     * @param array|null $orderBy
223
     *
224
     * @return EntityInterface|null
225
     */
226
    public function findOneBy(array $criteria, ?array $orderBy = null)
227
    {
228
        $entity = $this->entityRepository->findOneBy($criteria, $orderBy);
229
        if (null === $entity) {
230
            return null;
231
        }
232
        if ($entity instanceof EntityInterface) {
233
            $this->initialiseEntity($entity);
234
235
            return $entity;
236
        }
237
    }
238
239
    /**
240
     * @param array $criteria
241
     *
242
     * @return EntityInterface|null
243
     */
244
    public function getRandomOneBy(array $criteria)
245
    {
246
        $found = $this->getRandomBy($criteria, 1);
247
        if ([] === $found) {
248
            throw new \RuntimeException('Failed finding any Entities with this criteria');
249
        }
250
        $entity = current($found);
251
        if ($entity instanceof EntityInterface) {
252
            return $entity;
253
        }
254
        throw new \RuntimeException('Unexpected Entity Type ' . get_class($entity));
255
    }
256
257
    /**
258
     * @param array $criteria
259
     *
260
     * @param int   $numToGet
261
     *
262
     * @return EntityInterface[]|array
263
     */
264
    public function getRandomBy(array $criteria, int $numToGet = 1): array
265
    {
266
        $count = $this->count($criteria);
267
        if (0 === $count) {
268
            return [];
269
        }
270
        $randOffset = rand(0, $count - $numToGet);
271
272
        return $this->findBy($criteria, null, $numToGet, $randOffset);
273
    }
274
275
    public function count(array $criteria = []): int
276
    {
277
        return $this->entityRepository->count($criteria);
278
    }
279
280
    /**
281
     * @return array|EntityInterface[]
282
     */
283
    public function findBy(array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null): array
284
    {
285
        return $this->initialiseEntities($this->entityRepository->findBy($criteria, $orderBy, $limit, $offset));
286
    }
287
288
    public function getClassName(): string
289
    {
290
        return $this->entityRepository->getClassName();
291
    }
292
293
    public function matching(Criteria $criteria): LazyCriteriaCollection
294
    {
295
        $collection = $this->entityRepository->matching($criteria);
296
        if ($collection instanceof LazyCriteriaCollection) {
0 ignored issues
show
introduced by
$collection is always a sub-type of Doctrine\ORM\LazyCriteriaCollection.
Loading history...
297
            return $this->initialiseEntities($collection);
298
        }
0 ignored issues
show
Bug Best Practice introduced by
The function implicitly returns null when the if condition on line 296 is false. This is incompatible with the type-hinted return Doctrine\ORM\LazyCriteriaCollection. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
299
    }
300
301
    public function createQueryBuilder(string $alias, string $indexBy = null): QueryBuilder
302
    {
303
        return $this->entityRepository->createQueryBuilder($alias, $indexBy);
304
    }
305
306
    public function createResultSetMappingBuilder(string $alias): Query\ResultSetMappingBuilder
307
    {
308
        return $this->entityRepository->createResultSetMappingBuilder($alias);
309
    }
310
311
    public function createNamedQuery(string $queryName): Query
312
    {
313
        return $this->entityRepository->createNamedQuery($queryName);
314
    }
315
316
    public function createNativeNamedQuery(string $queryName): NativeQuery
317
    {
318
        return $this->entityRepository->createNativeNamedQuery($queryName);
319
    }
320
321
    public function clear(): void
322
    {
323
        $this->entityRepository->clear();
324
    }
325
}
326