1: <?php
2:
3: namespace PHPixie\Slice\Type;
4:
5: class ArrayData extends \PHPixie\Slice\Data\Implementation
6: {
7: protected $data;
8:
9: public function __construct($sliceBuilder, $data = array())
10: {
11: parent::__construct($sliceBuilder);
12: $this->data = $data;
13: }
14:
15: 16: 17: 18:
19: public function keys($path = null, $isRequired = false)
20: {
21: $data = $this->getData($path, $isRequired, array());
22: return array_keys($data);
23: }
24:
25: 26: 27: 28:
29: public function getData($path = null, $isRequired = false, $default = null)
30: {
31: if ($path !== null) {
32: list($parentPath, $key) = $this->splitPath($path);
33: $parent = &$this->findGroup($parentPath);
34: if ($parent !== null && array_key_exists($key, $parent)) {
35: return $parent[$key];
36: }
37:
38: }elseif(!empty($this->data)) {
39: return $this->data;
40:
41: }
42:
43: if (!$isRequired) {
44: return $default;
45: }
46:
47: throw new \PHPixie\Slice\Exception("Data for '$path' is not set.");
48: }
49:
50: 51: 52: 53:
54: public function slice($path = null)
55: {
56: return $this->arraySlice($path);
57: }
58:
59: 60: 61: 62:
63: public function arraySlice($path = null)
64: {
65: $data = $this->get($path);
66: return $this->sliceBuilder->arraySlice($data, $path);
67: }
68:
69: public function getIterator()
70: {
71: return new \ArrayIterator($this->data);
72: }
73:
74: protected function splitPath($path)
75: {
76: $path = explode('.', $path);
77: $key = array_pop($path);
78: return array($path, $key);
79: }
80:
81: protected function &findGroup($path, $createMissing = false) {
82: $group = &$this->data;
83: foreach ($path as $i => $key) {
84:
85: if (!array_key_exists($key, $group)) {
86: if (!$createMissing) {
87: $return = null;
88: return $return;
89: }
90:
91: $group[$key] = array();
92: }
93:
94: if (!is_array($group[$key])) {
95: if (!$createMissing) {
96: $return = null;
97: return $return;
98: }
99:
100: throw new \PHPixie\Slice\Exception("An element with key '$key' is not an array.");
101: }
102:
103: $group = &$group[$key];
104: }
105:
106: return $group;
107: }
108:
109: }
110: