1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Spiral, Core Components |
4
|
|
|
* |
5
|
|
|
* @author Wolfy-J |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace Spiral\ODM\Entities; |
9
|
|
|
|
10
|
|
|
use MongoDB\Driver\Cursor; |
11
|
|
|
use Spiral\ODM\CompositableInterface; |
12
|
|
|
use Spiral\ODM\ODMInterface; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Iterates over given cursor and convert its values in a proper objects using instantiation |
16
|
|
|
* manager. Attention, this class is very important as it provides ability to story inherited |
17
|
|
|
* documents in one collection. |
18
|
|
|
* |
19
|
|
|
* Note: since new mongo drivers arrived you can emulate same functionality using '__pclass' |
20
|
|
|
* property. |
21
|
|
|
* |
22
|
|
|
* Note #2: ideally this class to be tested, but Cursor is final class and it seems unrealistic |
23
|
|
|
* without adding extra layer which will harm core readability . |
24
|
|
|
*/ |
25
|
|
|
class DocumentCursor extends \IteratorIterator |
26
|
|
|
{ |
27
|
|
|
/** |
28
|
|
|
* @var Cursor |
29
|
|
|
*/ |
30
|
|
|
private $cursor; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var string |
34
|
|
|
*/ |
35
|
|
|
private $class; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @var ODMInterface |
39
|
|
|
*/ |
40
|
|
|
private $odm; |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param Cursor $cursor |
44
|
|
|
* @param string $class |
45
|
|
|
* @param ODMInterface $odm |
46
|
|
|
*/ |
47
|
|
|
public function __construct(Cursor $cursor, string $class, ODMInterface $odm) |
48
|
|
|
{ |
49
|
|
|
//Ensuring cursor fetch types |
50
|
|
|
$cursor->setTypeMap([ |
51
|
|
|
'root' => 'array', |
52
|
|
|
'document' => 'array', |
53
|
|
|
'array' => 'array' |
54
|
|
|
]); |
55
|
|
|
|
56
|
|
|
parent::__construct($this->cursor = $cursor); |
57
|
|
|
|
58
|
|
|
$this->class = $class; |
59
|
|
|
$this->odm = $odm; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @return \Spiral\ODM\CompositableInterface |
64
|
|
|
*/ |
65
|
|
|
public function current(): CompositableInterface |
66
|
|
|
{ |
67
|
|
|
return $this->odm->make($this->class, parent::current(), false); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return Cursor |
72
|
|
|
*/ |
73
|
|
|
public function getCursor(): Cursor |
74
|
|
|
{ |
75
|
|
|
return $this->cursor; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @return array |
80
|
|
|
*/ |
81
|
|
|
public function toArray(): array |
82
|
|
|
{ |
83
|
|
|
return $this->fetchAll(); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Fetch all documents. |
88
|
|
|
* |
89
|
|
|
* @return CompositableInterface[] |
90
|
|
|
*/ |
91
|
|
|
public function fetchAll(): array |
92
|
|
|
{ |
93
|
|
|
$result = []; |
94
|
|
|
foreach ($this as $item) { |
95
|
|
|
$result[] = $item; |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
return $result; |
99
|
|
|
} |
100
|
|
|
} |