Remove::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
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 DOMNode;
14
use DOMNodeList;
15
use WebinoDraw\Dom\Document;
16
use WebinoDraw\Dom\Locator;
17
use WebinoDraw\Exception;
18
19
/**
20
 * Class Remove
21
 */
22
class Remove implements InLoopPluginInterface
23
{
24
    /**
25
     * @var Locator
26
     */
27
    protected $locator;
28
29
    /**
30
     * @param Locator $locator
31
     */
32
    public function __construct(Locator $locator)
33
    {
34
        $this->locator = $locator;
35
    }
36
37
    /**
38
     * @param PluginArgument $arg
39
     */
40
    public function inLoop(PluginArgument $arg)
41
    {
42
        $spec = $arg->getSpec();
43
        if (empty($spec['remove'])) {
44
            return;
45
        }
46
47
        $node = $arg->getNode();
48
        if (!($node instanceof DOMNode)) {
49
            throw new Exception\LogicException('Expected node of type DOMNode');
50
        }
51
        if (!($node->ownerDocument instanceof Document)) {
52
            throw new Exception\LogicException('Expects node ownerDocument of type Dom\Document');
53
        }
54
55
        $helper = $arg->getHelper();
56
        $helper->setVarTranslation(null);
57
58
        $nodeXpath = $node->ownerDocument->getXpath();
59
        foreach ((array) $spec['remove'] as $removeLocator) {
60
            $helper->translate($removeLocator);
61
            $nodes = $nodeXpath->query($this->locator->set($removeLocator)->xpathMatchAny(), $node);
62
            $nodes and $this->removeNodes($nodes);
63
        }
64
    }
65
66
    /**
67
     * @param DOMNodeList $nodes
68
     * @return self
69
     * @throws Exception\LogicException
70
     */
71
    protected function removeNodes(DOMNodeList $nodes)
72
    {
73
        foreach ($nodes as $node) {
74
            if (!($node instanceof DOMNode)) {
75
                throw new Exception\LogicException('Expected node of type DOMNode');
76
            }
77
78
            empty($node->parentNode)
79
                or $node->parentNode->removeChild($node);
80
        }
81
82
        return $this;
83
    }
84
}
85