1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Respect\Structural\Driver\MongoDb; |
4
|
|
|
|
5
|
|
|
use Respect\Data\Collections\Collection; |
6
|
|
|
|
7
|
|
|
class MongoDriver extends AbstractDriver |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @var \MongoClient |
11
|
|
|
*/ |
12
|
|
|
private $connection; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var \MongoDB |
16
|
|
|
*/ |
17
|
|
|
private $database; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Driver constructor. |
21
|
|
|
* |
22
|
|
|
* @param \MongoClient $connection |
23
|
|
|
* @param string $database |
24
|
|
|
*/ |
25
|
12 |
|
public function __construct(\MongoClient $connection, $database) |
26
|
|
|
{ |
27
|
12 |
|
$this->connection = $connection; |
28
|
12 |
|
$this->database = $connection->selectDB($database); |
29
|
12 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @return \MongoDB |
33
|
|
|
*/ |
34
|
5 |
|
public function getDatabase() |
35
|
|
|
{ |
36
|
5 |
|
return $this->database; |
37
|
|
|
} |
38
|
|
|
|
39
|
1 |
|
public function getConnection() |
40
|
|
|
{ |
41
|
1 |
|
return $this->connection; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param \Iterator $cursor |
46
|
|
|
* |
47
|
|
|
* @return array |
48
|
|
|
*/ |
49
|
1 |
|
public function fetch(\Iterator $cursor) |
50
|
|
|
{ |
51
|
1 |
|
$data = $cursor->current(); |
52
|
1 |
|
$cursor->next(); |
53
|
|
|
|
54
|
1 |
|
return $data; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param array $collection |
59
|
|
|
* @param array $query |
60
|
|
|
* |
61
|
|
|
* @return \Iterator |
62
|
|
|
*/ |
63
|
2 |
|
public function find($collection, array $query = []) |
64
|
|
|
{ |
65
|
2 |
|
$cursor = $this->getDatabase()->selectCollection($collection)->find($query); |
66
|
2 |
|
$cursor->rewind(); |
67
|
|
|
|
68
|
2 |
|
return $cursor; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param int|string $id |
73
|
|
|
* |
74
|
|
|
* @return \MongoId|\MongoInt32 |
75
|
|
|
*/ |
76
|
2 |
|
public function createObjectId($id) |
77
|
|
|
{ |
78
|
2 |
|
if (is_int($id)) { |
79
|
|
|
return new \MongoInt32($id); |
80
|
|
|
} |
81
|
|
|
|
82
|
2 |
|
return new \MongoId($id); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* @param Collection $collection |
87
|
|
|
* @param $document |
88
|
|
|
* |
89
|
|
|
* @return void |
90
|
|
|
*/ |
91
|
1 |
|
public function insert($collection, $document) |
92
|
|
|
{ |
93
|
1 |
|
$this->getDatabase()->selectCollection($collection)->insert($document); |
94
|
1 |
|
} |
95
|
|
|
|
96
|
1 |
|
public function update($collection, $criteria, $document) |
97
|
|
|
{ |
98
|
1 |
|
$this->getDatabase()->selectCollection($collection)->update($criteria, $document); |
99
|
1 |
|
} |
100
|
|
|
|
101
|
1 |
|
public function remove($collection, $criteria) |
102
|
|
|
{ |
103
|
1 |
|
$this->getDatabase()->selectCollection($collection)->remove($criteria); |
104
|
1 |
|
} |
105
|
|
|
} |
106
|
|
|
|