Completed
Push — master ( 8ef8f1...b6a30a )
by Tom
04:29
created

ContentReplace   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 1
dl 0
loc 45
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B replaceContent() 0 15 6
A replaceCachedContent() 0 9 4
A fixPreserveWhitespaceRemoveChild() 0 5 4
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 ContentReplace {
9
	private $content;
10
11
	public function __construct(Content $content) {
12
		$this->content = $content;
13
	}
14
15
	public function replaceContent($element, $content) {
16
		if ($element->getAttribute('transphporm') == 'added') return;
17
		//If this rule was cached, the elements that were added last time need to be removed prior to running the rule again.
18
		if ($element->getAttribute('transphporm')) {
19
			$this->replaceCachedContent($element);
20
		}
21
22
		foreach ($this->content->getNode($content, $element->ownerDocument) as $node) {
23
			if ($node instanceof \DomElement && !$node->getAttribute('transphporm'))  $node->setAttribute('transphporm', 'added');
24
			$element->parentNode->insertBefore($node, $element);
25
		}
26
27
		//Remove the original element from the final output
28
		$element->setAttribute('transphporm', 'remove');
29
	}
30
31
32
33
	private function replaceCachedContent($element) {
34
		$el = $element;
35
		while ($el = $el->previousSibling) {
36
			if ($el->nodeType == 1 && $el->getAttribute('transphporm') != 'remove') {
37
				$el->parentNode->removeChild($el);
38
			}
39
		}
40
		$this->fixPreserveWhitespaceRemoveChild($element);
41
	}
42
43
	// $doc->preserveWhiteSpace = false should fix this but it doesn't
44
	// Remove extra whitespace created by removeChild to avoid the cache growing 1 byte every time it's reloaded
45
	// This may need to be moved in future, anywhere elements are being removed and files are cached may need to apply this fix
46
	// Also remove any comments to avoid the comment being re-added every time the cache is reloaded
47
	private function fixPreserveWhitespaceRemoveChild($element) {
48
		if ($element->previousSibling instanceof \DomComment || ($element->previousSibling instanceof \DomText && $element->previousSibling->isElementContentWhiteSpace())) {
49
			$element->parentNode->removeChild($element->previousSibling);
50
		}
51
	}
52
}