1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace hanneskod\yaysondb; |
6
|
|
|
|
7
|
|
|
use hanneskod\yaysondb\Expression\ExpressionInterface; |
8
|
|
|
use hanneskod\yaysondb\Filter\CallableFilter; |
9
|
|
|
use hanneskod\yaysondb\Filter\ExpressionFilter; |
10
|
|
|
use hanneskod\yaysondb\Filter\FilterInterface; |
11
|
|
|
use hanneskod\yaysondb\Filter\LimitFilter; |
12
|
|
|
use hanneskod\yaysondb\Filter\OrderByFilter; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Basic implementation of FilterableInterface |
16
|
|
|
*/ |
17
|
|
|
class Filterable implements FilterableInterface |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var \Traversable Contained set of documents |
21
|
|
|
*/ |
22
|
|
|
private $docs; |
23
|
|
|
|
24
|
|
|
public function __construct(\Traversable $docs) |
25
|
|
|
{ |
26
|
|
|
$this->docs = $docs; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function count(): int |
30
|
|
|
{ |
31
|
|
|
$count = 0; |
32
|
|
|
|
33
|
|
|
foreach ($this->getIterator() as $doc) { |
34
|
|
|
$count ++; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return $count; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function each(callable $callable) |
41
|
|
|
{ |
42
|
|
|
foreach ($this as $doc) { |
43
|
|
|
$callable($doc); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function filter(FilterInterface $filter): FilterableInterface |
48
|
|
|
{ |
49
|
|
|
return new Filterable($filter->filter($this)); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function find(ExpressionInterface $expression): FilterableInterface |
53
|
|
|
{ |
54
|
|
|
return $this->filter(new ExpressionFilter($expression)); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function findOne(ExpressionInterface $expression): array |
58
|
|
|
{ |
59
|
|
|
return $this->find($expression)->first(); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function first(): array |
63
|
|
|
{ |
64
|
|
|
foreach ($this as $doc) { |
65
|
|
|
return (array)$doc; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return []; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
public function getIterator(): \Generator |
72
|
|
|
{ |
73
|
|
|
foreach ($this->docs as $doc) { |
74
|
|
|
yield $doc; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
public function isEmpty(): bool |
79
|
|
|
{ |
80
|
|
|
foreach ($this as $doc) { |
81
|
|
|
return false; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return true; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
public function limit(int $count, int $offset = 0): FilterableInterface |
88
|
|
|
{ |
89
|
|
|
return $this->filter(new LimitFilter($count, $offset)); |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
public function orderBy(string ...$keys): FilterableInterface |
93
|
|
|
{ |
94
|
|
|
return $this->filter(new OrderByFilter(...$keys)); |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
public function where(callable $callable): FilterableInterface |
98
|
|
|
{ |
99
|
|
|
return $this->filter(new CallableFilter($callable)); |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|