Completed
Push — master ( 247d83...132dc2 )
by Tom
02:31
created

ElementData::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 3
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\Hook;
8
/* Maps which data is applied to which element */
9
class ElementData {
10
	private $data; 
11
	private $elementMap;
12
13
	public function __construct(\SplObjectStorage $elementMap, $data) {
14
		$this->elementMap = $elementMap;
15
		$this->data = $data;
16
	}
17
18
	/** Binds data to an element */
19
	public function bind(\DomNode $element, $data, $type = 'data') {
20
		//This is a bit of a hack to workaround #24, might need a better way of doing this if it causes a problem
21
		if (is_array($data) && $this->isObjectArray($data)) $data = $data[0];
22
		$content = isset($this->elementMap[$element]) ? $this->elementMap[$element] : [];
23
		$content[$type] = $data;
24
		$this->elementMap[$element] = $content;
25
	}
26
27
	private function isObjectArray(array $data) {
28
		return count($data) === 1 && isset($data[0]) && is_object($data[0]);
29
	}
30
31
	/** Returns the data that has been bound to $element, or, if no data is bound to $element climb the DOM tree to find the data bound to a parent node*/
32
	public function getData(\DomElement $element = null, $type = 'data') {
33
		while ($element) {
34
			if (isset($this->elementMap[$element]) && isset($this->elementMap[$element][$type])) return $this->elementMap[$element][$type];
35
			$element = $element->parentNode;
36
		}
37
		return $this->data;
38
	}
39
}