1
|
|
|
<?php |
2
|
|
|
namespace Maphper\DataSource; |
3
|
|
|
use Maphper\Maphper; |
4
|
|
|
class Mock implements \Maphper\DataSource { |
5
|
|
|
private $data; |
6
|
|
|
private $id; |
7
|
|
|
|
8
|
|
|
public function __construct(\ArrayObject $data, $id) { |
9
|
|
|
$this->data = $data; |
10
|
|
|
$this->id = is_array($id) ? $id : [$id]; |
11
|
|
|
} |
12
|
|
|
|
13
|
|
|
public function getPrimaryKey() { |
14
|
|
|
return $this->id; |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public function findById($id) { |
18
|
|
|
return isset($this->data[$id]) ? (array)$this->data[$id] : []; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function findByField(array $fields, $options = []) { |
22
|
|
|
$arrayFilter = new \Maphper\Lib\ArrayFilter(iterator_to_array($this->data->getIterator())); |
23
|
|
|
$filteredArray = $arrayFilter->filter($fields); |
24
|
|
|
if (isset($options['order'])) { |
25
|
|
|
list($columns, $order) = explode(' ', $options['order']); |
26
|
|
|
usort($filteredArray, $this->getOrderFunction($order, $columns)); |
27
|
|
|
} |
28
|
|
|
if (isset($options['offset'])) $filteredArray = array_slice($filteredArray, $options['offset']); |
29
|
|
|
if (isset($options['limit'])) $filteredArray = array_slice($filteredArray, 0, $options['limit']); |
30
|
|
|
return $filteredArray; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function findAggregate($function, $field, $group = null, array $criteria = [], array $options = []) { |
34
|
|
|
return $function($this->findByField($criteria)); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function deleteById($id) { |
38
|
|
|
unset($this->data[$id]); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function deleteByField(array $fields, array $options) { |
42
|
|
|
foreach ($this->findByField($fields, $options) as $val) unset($this->data[$val->{$this->id[0]}]); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function save($data) { |
46
|
|
|
if (isset($data->{$this->id[0]})) { |
47
|
|
|
$id = $data->{$this->id[0]}; |
48
|
|
|
} |
49
|
|
|
else { |
50
|
|
|
$id = count($this->data); |
51
|
|
|
$data->{$this->id[0]} = $id; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$this->data[$id] = (object)array_merge($this->findById($id), (array)$data); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function getErrors() { |
58
|
|
|
return []; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
private function getOrderFunction($order, $columns) { |
62
|
|
|
return function($a, $b) use ($order, $columns) { |
63
|
|
|
foreach (explode(',', $columns) as $column) { |
64
|
|
|
$aColumn = $a->$column; |
65
|
|
|
$bColumn = $b->$column; |
66
|
|
|
if ($aColumn === $bColumn) { |
67
|
|
|
$sortVal = 0; |
68
|
|
|
continue; |
69
|
|
|
} |
70
|
|
|
else $sortVal = ($aColumn < $bColumn) ? -1 : 1; |
71
|
|
|
break; |
72
|
|
|
} |
73
|
|
|
if ($order === 'desc') return -$sortVal; |
|
|
|
|
74
|
|
|
else return $sortVal; |
75
|
|
|
}; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|