Completed
Push — master ( 543a8a...f3a8ad )
by Richard
02:07
created

ValueData::call()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 2
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 ((is_array($this->data) || $this->data instanceof \ArrayAccess) && isset($this->data[$key])) $this->data = $this->data[$key];
19
	}
20
21
	public function read($value) {
22
		if ((is_array($this->data) || $this->data instanceof \ArrayAccess)) {
23
			if (isset($this->data[$value])) return $this->data[$value];
24
		}
25
		else if (isset($this->data->$value)) return $this->data->$value;
26
		else return false;
27
	}
28
29
	public function call($func, $args) {
30
		return $this->data->$func(...$args);
31
	}
32
33
	public function methodExists($name) {
34
		return method_exists($this->data, $name);
35
	}
36
37
	public function parseNested($parser, $token, $funcName) {
38
		$args = $parser->parseTokens($token['value'], $this->data);
39
		if ($args[0] == $this->data) $args = [];
40
		return $this->callFuncOnObject($this->data, $funcName, $args);
41
	}
42
43
	private function callFuncOnObject($obj, $func, $args) {
44
		if (isset($obj->$func) && is_callable($obj->$func)) return call_user_func_array($obj->$func, $args);
45
		else if (is_callable([$obj, $func])) return call_user_func_array([$obj, $func], $args);
46
		else return false;
47
	}
48
49
	public function extract($last, $autoLookup) {
50
		$value = $this->read($last);
51
		if ($value && ($autoLookup || is_array($this->data) || $this->data instanceof \ArrayAccess) ) {
52
			return $value;
53
		}
54
		throw new \UnexpectedValueException('Not found');
55
	}
56
}
57