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\Manager; |
8
|
|
|
use Igni\Storage\Storable; |
9
|
|
|
|
10
|
|
|
abstract class Repository implements RepositoryInterface |
11
|
|
|
{ |
12
|
|
|
protected $connection; |
13
|
|
|
protected $entityManager; |
14
|
|
|
protected $hydrator; |
15
|
|
|
protected $metaData; |
16
|
|
|
|
17
|
18 |
|
final public function __construct(Connection $connection, Manager $entityManager) |
18
|
|
|
{ |
19
|
18 |
|
$this->connection = $connection; |
20
|
18 |
|
$this->entityManager = $entityManager; |
21
|
18 |
|
$this->metaData = $entityManager->getMetaData($this->getEntityClass()); |
22
|
18 |
|
$this->hydrator = $entityManager->getHydrator($this->getEntityClass()); |
23
|
18 |
|
} |
24
|
|
|
|
25
|
2 |
|
public function get($id): Storable |
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 Storable) { |
38
|
|
|
throw RepositoryException::forNotFound($id); |
39
|
|
|
} |
40
|
|
|
|
41
|
2 |
|
return $entity; |
42
|
|
|
} |
43
|
|
|
|
44
|
1 |
|
public function create(Storable $entity): Storable |
45
|
|
|
{ |
46
|
|
|
// Support id auto-generation. |
47
|
1 |
|
$entity->getId(); |
48
|
1 |
|
$data = $this->hydrator->extract($entity); |
49
|
1 |
|
if (isset($data['id'])) { |
50
|
1 |
|
$data['_id'] = $data['id']; |
51
|
1 |
|
unset($data['id']); |
52
|
|
|
} |
53
|
1 |
|
$this->connection->insert( |
54
|
1 |
|
$this->metaData->getSource(), |
55
|
1 |
|
$data |
56
|
|
|
); |
57
|
|
|
|
58
|
1 |
|
return $entity; |
59
|
|
|
} |
60
|
|
|
|
61
|
1 |
|
public function remove(Storable $entity): Storable |
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(Storable $entity): Storable |
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: