Replace::inLoop()   B
last analyzed

Complexity

Conditions 9
Paths 7

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 40
rs 7.7244
c 0
b 0
f 0
cc 9
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-2017 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 WebinoDraw\Dom\Element;
14
use WebinoDraw\Dom\NodeInterface;
15
use WebinoDraw\Dom\Text;
16
use WebinoDraw\Draw\Helper\AbstractHelper;
17
use WebinoDraw\Exception;
18
19
/**
20
 * Class Replace
21
 */
22
class Replace extends AbstractPlugin implements InLoopPluginInterface
23
{
24
    /**
25
     * @param PluginArgument $arg
26
     */
27
    public function inLoop(PluginArgument $arg)
28
    {
29
        $spec = $arg->getSpec();
30
        if (!array_key_exists('replace', $spec)
31
            || null === $spec['replace']
32
        ) {
33
            return;
34
        }
35
36
        $node = $arg->getNode();
37
        if (!($node instanceof Element) && !($node instanceof Text)) {
38
            throw new Exception\LogicException(
39
                sprintf('Expected node of type %s or %s ', Element::class, Text::class)
40
            );
41
        }
42
43
        if (empty($node->parentNode)) {
44
            // node already removed
45
            return;
46
        }
47
48
        $node->nodeValue = '';
49
        $varTranslation  = $arg->getVarTranslation();
50
51
        $helper = $arg->getHelper();
52
        if (!($helper instanceof AbstractHelper)) {
53
            throw new Exception\LogicException('Expected draw helper of type ' . AbstractHelper::class);
54
        }
55
56
        $translatedHtml = $helper->translateValue($spec['replace'], $varTranslation, $spec);
57
        if (empty($translatedHtml)) {
58
            return;
59
        }
60
61
        $newNode = $node->replaceWith($translatedHtml);
62
        if ($newNode instanceof NodeInterface) {
63
            $arg->setNode($newNode);
64
            $this->updateNodeVarTranslation($newNode, $arg);
65
        }
66
    }
67
}
68