1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Igni\Storage\Driver\MongoDB; |
4
|
|
|
|
5
|
|
|
use Igni\Storage\Driver\GenericRepository; |
6
|
|
|
use Igni\Storage\Exception\RepositoryException; |
7
|
|
|
use Igni\Storage\Storable; |
8
|
|
|
|
9
|
|
|
abstract class Repository extends GenericRepository |
10
|
|
|
{ |
11
|
|
|
public function get($id): Storable |
12
|
|
|
{ |
13
|
|
|
$cursor = $this->connection->find( |
|
|
|
|
14
|
|
|
$this->metaData->getSource(), |
15
|
|
|
['_id' => $id], |
16
|
|
|
['limit' => 1] |
17
|
|
|
); |
18
|
|
|
$cursor->hydrateWith($this->hydrator); |
19
|
|
|
|
20
|
|
|
$entity = $cursor->current(); |
21
|
|
|
$cursor->close(); |
22
|
|
|
|
23
|
|
|
if (!$entity instanceof Storable) { |
24
|
|
|
throw RepositoryException::forNotFound($id); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
return $entity; |
28
|
|
|
} |
29
|
|
|
|
30
|
1 |
|
public function create(Storable $entity): Storable |
31
|
|
|
{ |
32
|
|
|
// Support id auto-generation. |
33
|
1 |
|
$entity->getId(); |
34
|
1 |
|
$data = $this->hydrator->extract($entity); |
35
|
1 |
|
if (isset($data['id'])) { |
36
|
1 |
|
$data['_id'] = $data['id']; |
37
|
1 |
|
unset($data['id']); |
38
|
|
|
} |
39
|
1 |
|
$this->connection->insert( |
|
|
|
|
40
|
1 |
|
$this->metaData->getSource(), |
41
|
1 |
|
$data |
42
|
|
|
); |
43
|
|
|
|
44
|
1 |
|
return $entity; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function remove(Storable $entity): Storable |
48
|
|
|
{ |
49
|
|
|
$this->connection->remove( |
|
|
|
|
50
|
|
|
$this->metaData->getSource(), |
51
|
|
|
$entity->getId()->getValue() |
52
|
|
|
); |
53
|
|
|
|
54
|
|
|
return $entity; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function update(Storable $entity): Storable |
58
|
|
|
{ |
59
|
|
|
$this->connection->update( |
|
|
|
|
60
|
|
|
$this->metaData->getSource(), |
61
|
|
|
$this->hydrator->extract($entity) |
62
|
|
|
); |
|
|
|
|
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|