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

ElementData   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
c 1
b 0
f 0
lcom 1
cbo 0
dl 0
loc 31
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A bind() 0 7 4
A isObjectArray() 0 3 3
A getData() 0 7 4
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
}