Completed
Push — master ( 7dfd4a...0ec6f2 )
by Tom
02:00
created

Content::addContentPseudo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
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       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\Property;
8
class Content implements \Transphporm\Property {
9
	private $contentPseudo = [];
10
	private $formatter;
11
12
	public function __construct(\Transphporm\Hook\Formatter $formatter) {
13
		$this->formatter = $formatter;
14
	}
15
16
	public function run(array $values, \DomElement $element, array $rules, \Transphporm\Hook\PseudoMatcher $pseudoMatcher, array $properties = []) {
17
		if (!$this->shouldRun($element)) return false;
18
19
		$values = $this->formatter->format($values, $rules);
20
21
		if (!$this->processPseudo($values, $element, $pseudoMatcher)) {
22
			//Remove the current contents
23
			$this->removeAllChildren($element);
24
			//Now make a text node
25
			if ($this->getContentMode($rules) === 'replace') $this->replaceContent($element, $values);
26
			else $this->appendContent($element, $values);
27
		}
28
	}
29
30
	private function shouldRun($element) {
31
		do {
32
			if ($element->getAttribute('transphporm') == 'includedtemplate') return false;
33
		}
34
		while (($element = $element->parentNode) instanceof \DomElement);
35
		return true;
36
	}
37
38
	private function getContentMode($rules) {
39
		return (isset($rules['content-mode'])) ? $rules['content-mode']->read() : 'append';
40
	}
41
42
	public function addContentPseudo($name, ContentPseudo $contentPseudo) {
43
		$this->contentPseudo[$name] = $contentPseudo;
44
	}
45
46
	private function processPseudo($value, $element, $pseudoMatcher) {
47
		foreach ($this->contentPseudo as $pseudoName => $pseudoFunction) {
48
			if ($pseudoMatcher->hasFunction($pseudoName)) {
49
				$pseudoFunction->run($value, $pseudoMatcher->getFuncArgs($pseudoName, $element)[0], $element, $pseudoMatcher);
50
				return true;
51
			}
52
		}
53
		return false;
54
	}
55
56
	public function getNode($node, $document) {
57
		foreach ($node as $n) {
58
			if (is_array($n)) {
59
				foreach ($this->getNode($n, $document) as $new) yield $new;
60
			}
61
			else {
62
				yield $this->convertNode($n, $document);
63
			}
64
		}
65
	}
66
67
	private function convertNode($node, $document) {
68
		if ($node instanceof \DomElement || $node instanceof \DOMComment) {
69
			$new = $document->importNode($node, true);
70
			//Removing this might cause problems with caching...
71
			//$new->setAttribute('transphporm', 'added');
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
72
		}
73
		else {
74
			if ($node instanceof \DomText) $node = $node->nodeValue;
75
			$new = $document->createElement('text');
76
77
			$new->appendChild($document->createTextNode($node));
78
			$new->setAttribute('transphporm', 'text');
79
		}
80
		return $new;
81
	}
82
83
84
	private function replaceContent($element, $content) {
85
		if ($element->getAttribute('transphporm') == 'added') return;
86
		//If this rule was cached, the elements that were added last time need to be removed prior to running the rule again.
87
		if ($element->getAttribute('transphporm')) {
88
			$this->replaceCachedContent($element);
89
		}
90
91
		foreach ($this->getNode($content, $element->ownerDocument) as $node) {
92
			if (!$node->getAttribute('transphporm'))  $node->setAttribute('transphporm', 'added');
93
			$element->parentNode->insertBefore($node, $element);
94
		}
95
96
		//Remove the original element from the final output
97
		$element->setAttribute('transphporm', 'remove');
98
	}
99
100
	private function replaceCachedContent($element) {
101
		$el = $element;
102
		while ($el = $el->previousSibling) {
103
			if ($el->nodeType == 1 && $el->getAttribute('transphporm') != 'remove') {
104
				$el->parentNode->removeChild($el);
105
			}
106
		}
107
		$this->fixPreserveWhitespacRemoveChild($element);
108
	}
109
110
	// $doc->preserveWhiteSpace = false should fix this but it doesn't
111
	// Remove extra whitespace created by removeChild to avoid the cache growing 1 byte every time it's reloaded
112
	// This may need to be moved in future, anywhere elements are being removed and files are cached may need to apply this fix
113
	private function fixPreserveWhitespacRemoveChild($element) {
114
		if ($element->previousSibling instanceof \DomText && trim($element->previousSibling->isElementContentWhiteSpace())) {
115
			$element->parentNode->removeChild($element->previousSibling);
116
		}
117
	}
118
119
	private function appendContent($element, $content) {
120
		foreach ($this->getNode($content, $element->ownerDocument) as $node) {
121
			$element->appendChild($node);
122
		}
123
	}
124
125
	private function removeAllChildren($element) {
126
		while ($element->hasChildNodes()) $element->removeChild($element->firstChild);
127
	}
128
}