1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace BoneMvc\Module\Unicorn\Repository; |
6
|
|
|
|
7
|
|
|
use BoneMvc\Module\Unicorn\Collection\UnicornCollection; |
8
|
|
|
use BoneMvc\Module\Unicorn\Entity\Unicorn; |
9
|
|
|
use Doctrine\ORM\EntityNotFoundException; |
10
|
|
|
use Doctrine\ORM\EntityRepository; |
11
|
|
|
|
12
|
|
View Code Duplication |
class UnicornRepository extends EntityRepository |
|
|
|
|
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @param int $id |
16
|
|
|
* @param int|null $lockMode |
17
|
|
|
* @param int|null $lockVersion |
18
|
|
|
* @return Unicorn |
19
|
|
|
* @throws \Doctrine\ORM\ORMException |
20
|
|
|
*/ |
21
|
|
|
public function find($id, $lockMode = null, $lockVersion = null): Unicorn |
22
|
|
|
{ |
23
|
|
|
/** @var Unicorn $unicorn */ |
24
|
|
|
$unicorn = parent::find($id, $lockMode, $lockVersion); |
25
|
|
|
if (!$unicorn) { |
26
|
|
|
throw new EntityNotFoundException('Unicorn not found.', 404); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
return $unicorn; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param Unicorn $unicorn |
34
|
|
|
* @return $unicorn |
|
|
|
|
35
|
|
|
* @throws \Doctrine\ORM\ORMException |
36
|
|
|
* @throws \Doctrine\ORM\OptimisticLockException |
37
|
|
|
*/ |
38
|
|
|
public function save(Unicorn $unicorn): Unicorn |
39
|
|
|
{ |
40
|
|
|
if(!$unicorn->getID()) { |
41
|
|
|
$this->_em->persist($unicorn); |
42
|
|
|
} |
43
|
|
|
$this->_em->flush($unicorn); |
44
|
|
|
|
45
|
|
|
return $unicorn; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param Unicorn $unicorn |
50
|
|
|
* @throws \Doctrine\ORM\OptimisticLockException |
51
|
|
|
* @throws \Doctrine\ORM\ORMException |
52
|
|
|
*/ |
53
|
|
|
public function delete(Unicorn $unicorn): void |
54
|
|
|
{ |
55
|
|
|
$this->_em->remove($unicorn); |
56
|
|
|
$this->_em->flush($unicorn); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @return int |
61
|
|
|
* @throws \Doctrine\ORM\NoResultException |
62
|
|
|
* @throws \Doctrine\ORM\NonUniqueResultException |
63
|
|
|
*/ |
64
|
|
|
public function getTotalUnicornCount(): int |
65
|
|
|
{ |
66
|
|
|
$qb = $this->createQueryBuilder('u'); |
67
|
|
|
$qb->select('count(u.id)'); |
68
|
|
|
$query = $qb->getQuery(); |
69
|
|
|
|
70
|
|
|
return (int) $query->getSingleScalarResult(); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
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.