|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Igni\Storage\Driver\MongoDB; |
|
4
|
|
|
|
|
5
|
|
|
use Igni\Storage\Exception\RepositoryException; |
|
6
|
|
|
use Igni\Storage\Repository as RepositoryInterface; |
|
7
|
|
|
use Igni\Storage\EntityManager; |
|
8
|
|
|
use Igni\Storage\Entity; |
|
9
|
|
|
|
|
10
|
|
|
abstract class Repository implements RepositoryInterface |
|
11
|
|
|
{ |
|
12
|
|
|
protected $connection; |
|
13
|
|
|
protected $entityManager; |
|
14
|
|
|
protected $hydrator; |
|
15
|
|
|
protected $metaData; |
|
16
|
|
|
|
|
17
|
17 |
|
final public function __construct(Connection $connection, EntityManager $entityManager) |
|
18
|
|
|
{ |
|
19
|
17 |
|
$this->connection = $connection; |
|
20
|
17 |
|
$this->entityManager = $entityManager; |
|
21
|
17 |
|
$this->metaData = $entityManager->getMetaData($this->getEntityClass()); |
|
22
|
17 |
|
$this->hydrator = $entityManager->getHydrator($this->getEntityClass()); |
|
23
|
17 |
|
} |
|
24
|
|
|
|
|
25
|
2 |
|
public function get($id): Entity |
|
26
|
|
|
{ |
|
27
|
2 |
|
$cursor = $this->connection->find( |
|
28
|
2 |
|
$this->metaData->getSource(), |
|
29
|
2 |
|
['_id' => $id], |
|
30
|
2 |
|
['limit' => 1] |
|
31
|
|
|
); |
|
32
|
2 |
|
$cursor->setHydrator($this->hydrator); |
|
33
|
|
|
|
|
34
|
2 |
|
$entity = $cursor->current(); |
|
35
|
2 |
|
$cursor->close(); |
|
36
|
|
|
|
|
37
|
2 |
|
if (!$entity instanceof Entity) { |
|
38
|
|
|
throw RepositoryException::forNotFound($id); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
2 |
|
return $entity; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function create(Entity $entity): Entity |
|
45
|
|
|
{ |
|
46
|
|
|
// Support id auto-generation. |
|
47
|
|
|
$entity->getId(); |
|
48
|
|
|
$data = $this->hydrator->extract($entity); |
|
49
|
|
|
if (isset($data['id'])) { |
|
50
|
|
|
$data['_id'] = $data['id']; |
|
51
|
|
|
unset($data['id']); |
|
52
|
|
|
} |
|
53
|
|
|
$this->connection->insert( |
|
54
|
|
|
$this->metaData->getSource(), |
|
55
|
|
|
$data |
|
56
|
|
|
); |
|
57
|
|
|
|
|
58
|
|
|
return $entity; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
1 |
|
public function remove(Entity $entity): Entity |
|
62
|
|
|
{ |
|
63
|
1 |
|
$this->connection->remove( |
|
64
|
1 |
|
$this->metaData->getSource(), |
|
65
|
1 |
|
$entity->getId()->getValue() |
|
66
|
|
|
); |
|
67
|
|
|
|
|
68
|
1 |
|
return $entity; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
public function update(Entity $entity): Entity |
|
72
|
|
|
{ |
|
73
|
|
|
$this->connection->update( |
|
74
|
|
|
$this->metaData->getSource(), |
|
75
|
|
|
$this->hydrator->extract($entity) |
|
76
|
|
|
); |
|
|
|
|
|
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
abstract public function getEntityClass(): string; |
|
80
|
|
|
} |
|
81
|
|
|
|
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: