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 ( e4e275...7e47ac )
by joseph
07:04 queued 07:01
created

AbstractEntityRepository::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1.0876

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 3
dl 0
loc 9
ccs 5
cts 9
cp 0.5556
crap 1.0876
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 9
    public function __construct(
74
        EntityManagerInterface $entityManager,
75
        EntityFactoryInterface $entityFactory,
76
        NamespaceHelper $namespaceHelper
77
    ) {
78 9
        $this->entityManager   = $entityManager;
79 9
        $this->namespaceHelper = $namespaceHelper;
80 9
        $this->entityFactory   = $entityFactory;
81 9
        $this->initRepository();
82 9
    }
83
84 9
    protected function initRepository(): void
85
    {
86 9
        if (null === $this->metaData) {
87 9
            $entityFqn      = $this->getEntityFqn();
88 9
            $this->metaData = $this->entityManager->getClassMetadata($entityFqn);
89
        }
90
91 9
        $this->entityRepository = new EntityRepository($this->entityManager, $this->metaData);
92 9
    }
93
94 9
    protected function getEntityFqn(): string
95
    {
96 9
        return '\\' . \str_replace(
97
            [
98 9
                    'Entity\\Repositories',
99
                ],
100
            [
101 9
                    'Entities',
102
                ],
103 9
            $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 3
    public function initialiseEntity(EntityInterface $entity)
137
    {
138 3
        $this->entityFactory->initialiseEntity($entity);
139
140 3
        return $entity;
141
    }
142
143
    /**
144
     * @return array|EntityInterface[]
145
     */
146 1
    public function findAll(): array
147
    {
148 1
        return $this->initialiseEntities($this->entityRepository->findAll());
149
    }
150
151 3
    public function initialiseEntities($entities)
152
    {
153 3
        foreach ($entities as $entity) {
154 3
            $this->initialiseEntity($entity);
155
        }
156
157 3
        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 2
    public function get($id, ?int $lockMode = null, ?int $lockVersion = null)
169
    {
170
        try {
171 2
            $entity = $this->find($id, $lockMode, $lockVersion);
172 1
        } catch (ConversionException $e) {
173 1
            $error = 'Failed getting by id ' . $id
174 1
                     . ', unless configured as an int ID entity, this should be a valid UUID';
175 1
            throw new DoctrineStaticMetaException($error, $e->getCode(), $e);
176
        }
177 1
        if ($entity === null) {
178
            throw new DoctrineStaticMetaException('Could not find the entity with id ' . $id);
179
        }
180
181 1
        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 2
    public function find($id, ?int $lockMode = null, ?int $lockVersion = null)
192
    {
193 2
        $entity = $this->entityRepository->find($id, $lockMode, $lockVersion);
194 1
        if (null === $entity) {
195
            return null;
196
        }
197 1
        if ($entity instanceof EntityInterface) {
198 1
            $this->initialiseEntity($entity);
199
200 1
            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 2
    public function findOneBy(array $criteria, ?array $orderBy = null)
227
    {
228 2
        $entity = $this->entityRepository->findOneBy($criteria, $orderBy);
229 2
        if (null === $entity) {
230 1
            return null;
231
        }
232 1
        if ($entity instanceof EntityInterface) {
233 1
            $this->initialiseEntity($entity);
234
235 1
            return $entity;
236
        }
237
    }
238
239
    /**
240
     * @param array $criteria
241
     *
242
     * @return EntityInterface|null
243
     */
244 1
    public function getRandomOneBy(array $criteria)
245
    {
246 1
        $found = $this->getRandomBy($criteria, 1);
247 1
        if ([] === $found) {
248
            throw new \RuntimeException('Failed finding any Entities with this criteria');
249
        }
250 1
        $entity = current($found);
251 1
        if ($entity instanceof EntityInterface) {
252 1
            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 2
    public function getRandomBy(array $criteria, int $numToGet = 1): array
265
    {
266 2
        $count = $this->count($criteria);
267 2
        if (0 === $count) {
268
            return [];
269
        }
270 2
        $randOffset = rand(0, $count - $numToGet);
271
272 2
        return $this->findBy($criteria, null, $numToGet, $randOffset);
273
    }
274
275 3
    public function count(array $criteria = []): int
276
    {
277 3
        return $this->entityRepository->count($criteria);
278
    }
279
280
    /**
281
     * @return array|EntityInterface[]
282
     */
283 3
    public function findBy(array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null): array
284
    {
285 3
        return $this->initialiseEntities($this->entityRepository->findBy($criteria, $orderBy, $limit, $offset));
286
    }
287
288 1
    public function matching(Criteria $criteria): LazyCriteriaCollection
289
    {
290 1
        $collection = $this->entityRepository->matching($criteria);
291 1
        if ($collection instanceof LazyCriteriaCollection) {
0 ignored issues
show
introduced by
$collection is always a sub-type of Doctrine\ORM\LazyCriteriaCollection.
Loading history...
292 1
            return $this->initialiseEntities($collection);
293
        }
0 ignored issues
show
Bug Best Practice introduced by
The function implicitly returns null when the if condition on line 291 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...
294
    }
295
296 2
    public function createQueryBuilder(string $alias, string $indexBy = null): QueryBuilder
297
    {
298
        #return $this->entityRepository->createQueryBuilder($alias, $indexBy);
299 2
        return (new UuidQueryBuilder($this->entityManager))
300 2
            ->select($alias)
301 2
            ->from($this->getClassName(), $alias, $indexBy);
302
    }
303
304 3
    public function getClassName(): string
305
    {
306 3
        return $this->entityRepository->getClassName();
307
    }
308
309 1
    public function createResultSetMappingBuilder(string $alias): Query\ResultSetMappingBuilder
310
    {
311 1
        return $this->entityRepository->createResultSetMappingBuilder($alias);
312
    }
313
314
    public function createNamedQuery(string $queryName): Query
315
    {
316
        return $this->entityRepository->createNamedQuery($queryName);
317
    }
318
319
    public function createNativeNamedQuery(string $queryName): NativeQuery
320
    {
321
        return $this->entityRepository->createNativeNamedQuery($queryName);
322
    }
323
324 1
    public function clear(): void
325
    {
326 1
        $this->entityRepository->clear();
327 1
    }
328
}
329