Completed
Push — master ( 1ce981...0b7883 )
by Tom
02:21
created

ValueData::isArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 2
eloc 2
nc 2
nop 0
1
<?php
2
/* @description     Transformation Style Sheets - Revolutionising PHP templating    *
3
 * @author          Tom Butler [email protected]                                             *
4
 * @copyright       2015 Tom Butler <[email protected]> | https://r.je/                      *
5
 * @license         http://www.opensource.org/licenses/bsd-license.php  BSD License *
6
 * @version         1.0                                                             */
7
namespace Transphporm\Parser;
8
/** Holds the data used by `ValueParser` */
9
class ValueData {
10
	private $data;
11
12
	public function __construct($data) {
13
		$this->data = $data;
14
	}
15
16
	public function traverse($key) {
17
		if (isset($this->data->{$key})) $this->data = $this->data->{$key};
18
		else if ($this->isArray() && isset($this->data[$key])) $this->data = $this->data[$key];
19
	}
20
21
	private function isArray() {
22
		return is_array($this->data) || $this->data instanceof \ArrayAccess;
23
	}
24
25
	public function read($value) {
26
		if ($this->isArray()) {
27
			if (isset($this->data[$value])) return $this->data[$value];
28
		}
29
		else if (isset($this->data->$value)) return $this->data->$value;
30
		else return false;
31
	}
32
33
	public function call($func, $args) {
34
		return $this->data->$func(...$args);
35
	}
36
37
	public function methodExists($name) {
38
		return method_exists($this->data, $name);
39
	}
40
41
	public function parseNested($parser, $token, $funcName) {
42
		$args = $parser->parseTokens($token['value'], $this->data);
43
		if ($args[0] == $this->data) $args = [];
44
		return $this->callFuncOnObject($this->data, $funcName, $args);
45
	}
46
47
	private function callFuncOnObject($obj, $func, $args) {
48
		if (isset($obj->$func) && is_callable($obj->$func)) return call_user_func_array($obj->$func, $args);
49
		else if (is_callable([$obj, $func])) return call_user_func_array([$obj, $func], $args);
50
		else return false;
51
	}
52
53
	public function extract($last, $autoLookup, $traversing) {
54
		$value = $this->read($last);
55
		if ($value && ($autoLookup || $traversing) ) {
56
			return $value;
57
		}
58
		throw new \UnexpectedValueException('Not found');
59
	}
60
}
61