Completed
Push — develop ( c4d291...65fed0 )
by Peter
02:27
created

Replace::inLoop()   D

Complexity

Conditions 9
Paths 7

Size

Total Lines 41
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 3 Features 1
Metric Value
c 8
b 3
f 1
dl 0
loc 41
rs 4.909
cc 9
eloc 24
nc 7
nop 1
1
<?php
2
/**
3
 * Webino (http://webino.sk)
4
 *
5
 * @link        https://github.com/webino/WebinoDraw for the canonical source repository
6
 * @copyright   Copyright (c) 2012-2016 Webino, s. r. o. (http://webino.sk)
7
 * @author      Peter Bačinský <[email protected]>
8
 * @license     BSD-3-Clause
9
 */
10
11
namespace WebinoDraw\Manipulator\Plugin;
12
13
use DOMElement;
14
use WebinoDraw\Dom\Element;
15
use WebinoDraw\Dom\NodeInterface;
16
use WebinoDraw\Dom\Text;
17
use WebinoDraw\Draw\Helper\AbstractHelper;
18
use WebinoDraw\Exception;
19
20
/**
21
 * Class Replace
22
 */
23
class Replace extends AbstractPlugin implements
24
    InLoopPluginInterface,
25
    PostLoopPluginInterface
26
{
27
    /**
28
     * @var array
29
     */
30
    protected $nodesToRemove = [];
31
32
    /**
33
     * @param PluginArgument $arg
34
     */
35
    public function inLoop(PluginArgument $arg)
36
    {
37
        $spec = $arg->getSpec();
38
        if (!array_key_exists('replace', $spec)
39
            || null === $spec['replace']
40
        ) {
41
            return;
42
        }
43
44
        $node = $arg->getNode();
45
        if (!($node instanceof Element) && !($node instanceof Text)) {
46
            throw new Exception\LogicException(
47
                sprintf('Expected node of type %s or %s ', Element::class, Text::class)
48
            );
49
        }
50
51
        if (empty($node->parentNode)) {
52
            // node already removed
53
            return;
54
        }
55
56
        $node->nodeValue = '';
57
        $varTranslation  = $arg->getVarTranslation();
58
59
        $helper = $arg->getHelper();
60
        if (!($helper instanceof AbstractHelper)) {
61
            throw new Exception\LogicException('Expected draw helper of type ' . AbstractHelper::class);
62
        }
63
64
        $translatedHtml = $helper->translateValue($spec['replace'], $varTranslation, $spec);
65
        if (empty($translatedHtml)) {
66
            return;
67
        }
68
69
        $newNode = $node->replaceWith($translatedHtml);
70
        $this->nodesToRemove[] = $node;
71
        if ($newNode instanceof NodeInterface) {
72
            $arg->setNode($newNode);
73
            $this->updateNodeVarTranslation($newNode, $arg);
74
        }
75
    }
76
77
    /**
78
     * @param PluginArgument $arg
79
     */
80
    public function postLoop(PluginArgument $arg)
81
    {
82
        foreach ($this->nodesToRemove as $node) {
83
            if ($node instanceof DOMElement && !empty($node->parentNode)) {
84
                $node->parentNode->removeChild($node);
85
            }
86
        }
87
    }
88
}
89