ValueData::call()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 2
1
<?php
2
/* @description     Transformation Style Sheets - Revolutionising PHP templating    *
3
 * @author          Tom Butler [email protected]                                             *
4
 * @copyright       2017 Tom Butler <[email protected]> | https://r.je/                      *
5
 * @license         http://www.opensource.org/licenses/bsd-license.php  BSD License *
6
 * @version         1.2                                                             */
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
	//Read $key from array, $this->data = $this->data[$key] but also works for objects
17
	private function traverseInto($key) {
18
		if (isset($this->data->{$key})) $this->data = $this->data->{$key};
19
		else if ($this->isArray() && isset($this->data[$key])) $this->data = $this->data[$key];
20
	}
21
22
	public function traverse($key, $result) {
23
		if ($key !== null) $this->traverseInto($key);
24
		else {
25
			//But if the key is null, replace the data structure with the result of the last function call
26
			$lastResult = $result->pop();
27
			if ($lastResult) {
28
				$this->data = $lastResult;
29
				return $lastResult;
30
			}
31
		}
32
	}
33
34
	private function isArray() {
35
		return is_array($this->data) || $this->data instanceof \ArrayAccess;
36
	}
37
38
	public function getData() {
39
		return $this->data;
40
	}
41
42
	public function read($value) {
43
		if ($this->isArray()) {
44
			if (isset($this->data[$value])) return $this->data[$value];
45
		}
46
		else if (isset($this->data->$value)) return $this->data->$value;
47
		else return null;
48
	}
49
50
	public function call($func, $args) {
51
		return $this->data->$func(...$args);
52
	}
53
54
	public function methodExists($name) {
55
		return method_exists($this->data, $name);
56
	}
57
58
	public function parseNested($parser, $token, $funcName) {
59
		$args = $parser->parseTokens($token['value'], $this->data);
60
		if ($args[0] === $this->data) $args = [];
61
		return $this->callFuncOnObject($this->data, $funcName, $args);
62
	}
63
64
	private function callFuncOnObject($obj, $func, $args) {
65
		if (isset($obj->$func) && is_callable($obj->$func)) return call_user_func_array($obj->$func, $args);
66
		else if (is_callable([$obj, $func])) return call_user_func_array([$obj, $func], $args);
67
		else return false;
68
	}
69
70
	public function extract($last, $autoLookup, $traversing) {
71
		$value = $this->read($last);
72
		if ($value !== null && ($autoLookup || $traversing) ) {
73
			return $value;
74
		}
75
		throw new \UnexpectedValueException('Not found');
76
	}
77
}
78