1: | <?php |
2: | |
3: | namespace Zippy\Html\DataList; |
4: | |
5: | use Zippy\Interfaces\DataSource; |
6: | use Zippy\Interfaces\Binding; |
7: | |
8: | |
9: | |
10: | |
11: | class ArrayDataSource implements DataSource |
12: | { |
13: | private $data; |
14: | |
15: | |
16: | |
17: | |
18: | |
19: | public function getArray() { |
20: | if ($this->data instanceof Binding) { |
21: | return $this->data->getValue(); |
22: | } else { |
23: | return $this->data; |
24: | } |
25: | } |
26: | |
27: | |
28: | |
29: | |
30: | |
31: | |
32: | |
33: | |
34: | public function __construct($source, $property = null) { |
35: | if ($source instanceof \Zippy\Html\HtmlComponent) { |
36: | $this->data = new \Zippy\Binding\ArrayPropertyBinding($source, $property); |
37: | } else { |
38: | $this->data = $source; |
39: | } |
40: | } |
41: | |
42: | |
43: | |
44: | |
45: | public function getItemCount() { |
46: | return count($this->getArray()); |
47: | } |
48: | |
49: | |
50: | |
51: | |
52: | public function getItems($start, $count, $sortfield = null, $asc = null) { |
53: | |
54: | $list = $this->getArray(); |
55: | if ($sortfield != null) { |
56: | |
57: | uasort( |
58: | $list, |
59: | function ($a, $b) use ($sortfield, $asc) { |
60: | if ($asc == 'desc') { |
61: | if (is_numeric($a->{$sortfield}) && is_numeric($a->{$sortfield})) { |
62: | return $b->{$sortfield} > $a->{$sortfield}; |
63: | } else { |
64: | return strcmp($b->{$sortfield}, $a->{$sortfield}); |
65: | } |
66: | } else { |
67: | if (is_numeric($a->{$sortfield}) && is_numeric($b->{$sortfield})) { |
68: | return $a->{$sortfield} > $b->{$sortfield}; |
69: | } else { |
70: | return strcmp($a->{$sortfield}, $b->{$sortfield}); |
71: | } |
72: | } |
73: | } |
74: | ); |
75: | } |
76: | if ($start >= 0 or $count >= 0) { |
77: | return array_slice($list, $start, $count); |
78: | } |
79: | return $list; |
80: | } |
81: | |
82: | |
83: | |
84: | |
85: | public function getItem($id) { |
86: | $list = $this->getArray(); |
87: | foreach ($list as $item) { |
88: | if ($item->getID() === $id) { |
89: | return $item; |
90: | } |
91: | } |
92: | return null; |
93: | } |
94: | |
95: | |
96: | public function setArray($source) { |
97: | $this->data = $source; |
98: | } |
99: | |
100: | } |
101: | |