|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace steevanb\EntityUtils\Repository; |
|
4
|
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityNotFoundException; |
|
6
|
|
|
use Doctrine\ORM\Mapping\ClassMetadata; |
|
7
|
|
|
|
|
8
|
|
|
trait GetTrait |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* @param mixed $id |
|
12
|
|
|
* @param int|null $lockMode |
|
13
|
|
|
* @param int|null $lockVersion |
|
14
|
|
|
* @return object |
|
15
|
|
|
*/ |
|
16
|
|
|
abstract public function find($id, $lockMode = null, $lockVersion = null); |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @param array $criteria |
|
20
|
|
|
* @param array|null $orderBy |
|
21
|
|
|
* @return object |
|
22
|
|
|
*/ |
|
23
|
|
|
abstract public function findOneBy(array $criteria, array $orderBy = null); |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @return ClassMetadata |
|
27
|
|
|
*/ |
|
28
|
|
|
abstract protected function getClassMetadata(); |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @param mixed $entity |
|
32
|
|
|
* @param array $criteria |
|
33
|
|
|
* @throws EntityNotFoundException |
|
34
|
|
|
*/ |
|
35
|
|
|
protected function assertIsEntity($entity, array $criteria) |
|
36
|
|
|
{ |
|
37
|
|
|
if ($entity instanceof \stdClass === false) { |
|
38
|
|
|
$message = 'Entity of type "' . $this->getClassMetadata()->getName() . '"'; |
|
39
|
|
|
$criteriaForMessage = []; |
|
40
|
|
|
foreach ($criteria as $name => $value) { |
|
41
|
|
|
$criteriaForMessage[] = $name . ' = ' . $value; |
|
42
|
|
|
} |
|
43
|
|
|
$message .= ' was not found with ' . (count($criteriaForMessage) > 1 ? ' criteria' : 'criterion'); |
|
44
|
|
|
$message .= ' : ' . implode(', ', $criteriaForMessage); |
|
45
|
|
|
throw new EntityNotFoundException($message); |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* @param mixed $id |
|
51
|
|
|
* @param int|null $lockMode |
|
52
|
|
|
* @param int|null $lockVersion |
|
53
|
|
|
* @return object |
|
54
|
|
|
* @throws EntityNotFoundException |
|
55
|
|
|
*/ |
|
56
|
|
|
public function get($id, $lockMode = null, $lockVersion = null) |
|
57
|
|
|
{ |
|
58
|
|
|
$entity = $this->find($id, $lockMode, $lockVersion); |
|
59
|
|
|
$this->assertIsEntity($entity, array('id' => $id)); |
|
60
|
|
|
|
|
61
|
|
|
return $entity; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @param array $criteria |
|
66
|
|
|
* @param array|null $orderBy |
|
67
|
|
|
* @return object |
|
68
|
|
|
* @throws EntityNotFoundException |
|
69
|
|
|
*/ |
|
70
|
|
|
public function getOneBy(array $criteria, array $orderBy = null) |
|
71
|
|
|
{ |
|
72
|
|
|
$entity = $this->findOneBy($criteria, $orderBy); |
|
73
|
|
|
$this->assertIsEntity($entity, $criteria); |
|
74
|
|
|
|
|
75
|
|
|
return $entity; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|