Element::setValue()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace WebinoDomLib\Dom;
4
5
use WebinoBaseLib\Util\ToString;
6
use WebinoDomLib\Dom;
7
use WebinoHtmlLib\Html\EscaperAwareTrait;
8
9
/**
10
 * Class Element
11
 */
12
class Element extends \DOMElement implements
13
    NodeInterface,
14
    NodeLocatorInterface
15
{
16
    use EscaperAwareTrait;
17
    use LocatorAwareTrait;
18
19
    /**
20
     * Return an element collection
21
     *
22
     * @param string|array $locator
23
     * @return NodeList
24
     */
25
    public function locate($locator)
26
    {
27
        $nodeList = $this->getLocator()->query($this, $locator);
28
        return new NodeList($nodeList);
29
    }
30
31
    /**
32
     * @param string $value Node value.
33
     * @return $this
34
     */
35
    public function setValue($value)
36
    {
37
        $this->nodeValue = $this->getEscaper()->escapeHtml($value);
38
        return $this;
39
    }
40
41
    /**
42
     * @param string $name
43
     * @param string $value
44
     * @return $this
45
     */
46
    public function setAttribute($name, $value)
47
    {
48
        if (empty($value)) {
49
            $this->removeAttribute($name);
50
            return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (WebinoDomLib\Dom\Element) is incompatible with the return type of the parent method DOMElement::setAttribute of type DOMAttr.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
51
        }
52
53
        parent::setAttribute($name, htmlspecialchars($value, ENT_QUOTES));
54
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (WebinoDomLib\Dom\Element) is incompatible with the return type of the parent method DOMElement::setAttribute of type DOMAttr.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
55
    }
56
57
    /**
58
     * @param string|array $html Valid XHTML code.
59
     * @return $this
60
     */
61
    public function setHtml($html)
62
    {
63
        $html = $this->normalizeHtml($html);
64
        if (empty($html)) {
65
            return $this;
66
        }
67
68
        $this->nodeValue = '';
69
        $frag = $this->ownerDocument->createDocumentFragment();
70
        $frag->appendXml($html);
71
72
        // TODO refactor
73
        if ($frag->firstChild) {
74
            $this->appendChild($frag);
75
        } else {
76
            /** @var Element $node */
77
            foreach ((new Dom($html))->locate('body') as $node) {
78
                foreach ($node->childNodes as $child) {
79
                    $this->appendChild($this->ownerDocument->importNode($child, true));
80
                }
81
            }
82
        }
83
84
        return $this;
85
    }
86
87
    /**
88
     * Returns the node body html
89
     *
90
     * @return string
91
     */
92
    public function getInnerHtml()
93
    {
94
        $html = '';
95
        foreach ($this->childNodes as $child) {
96
            $childHtml = $child->ownerDocument->saveXML($child);
97
            empty($childHtml) or $html .= $childHtml;
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
98
        }
99
        return $html;
100
    }
101
102
    /**
103
     * Returns the node html
104
     *
105
     * @return string
106
     */
107
    public function getOuterHtml()
108
    {
109
        return trim($this->ownerDocument->saveXML($this));
110
    }
111
112
    /**
113
     * @return bool
114
     */
115
    public function isEmpty()
116
    {
117
        $nodeValue = trim($this->nodeValue);
118
        if (!empty($nodeValue) || is_numeric($nodeValue)) {
119
            return false;
120
        }
121
122
        // node value is empty,
123
        // check for child other than text
124
        foreach ($this->childNodes as $childNode) {
125
            if (!($childNode instanceof \DOMText)) {
126
                return false;
127
            }
128
        }
129
130
        return true;
131
    }
132
133
    /**
134
     * @param string $nodeName New node name.
135
     * @return $this
136
     */
137
    public function rename($nodeName)
138
    {
139
        /** @var self $node */
140
        $node = $this->ownerDocument->createElement($nodeName);
141
142
        $html = $this->getInnerHtml();
143
        $html and $node->setHtml($html);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
144
145
        foreach ($this->attributes as $attrib) {
146
            $node->setAttributeNode($attrib);
147
        }
148
149
        $this->parentNode->insertBefore($node, $this);
150
        $this->remove();
151
152
        return $node;
153
    }
154
155
    /**
156
     * @param string|array $html
157
     * @return $this
158
     */
159
    public function replace($html)
160
    {
161
        $html = $this->normalizeHtml($html);
162
        if (empty($html)) {
163
            $this->remove();
164
            return $this;
165
        }
166
167
        $frag = $this->ownerDocument->createDocumentFragment();
168
        $frag->appendXML($html);
169
170
        // TODO refactor
171
        if ($frag->firstChild) {
172
            $node = $this->parentNode->insertBefore($frag, $this);
173
        } else {
174
            $nodes = [];
175
            /** @var Element $node */
176
            foreach ((new Dom($html))->locate('body') as $subNode) {
177
                foreach ($subNode->childNodes as $child) {
178
                    // TODO add node to node list
179
                    $nodes[] = $this->parentNode->insertBefore($this->ownerDocument->importNode($child, true), $this);
180
                }
181
            }
182
            $node = new NodeList($nodes);
183
        }
184
185
        $this->remove();
186
        return $node;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $node; (DOMNode|WebinoDomLib\Dom\NodeList) is incompatible with the return type declared by the interface WebinoDomLib\Dom\NodeInterface::replace of type WebinoDomLib\Dom\NodeInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
187
    }
188
189
    /**
190
     * @return $this
191
     */
192
    public function remove()
193
    {
194
        $this->parentNode->removeChild($this);
195
        return $this;
196
    }
197
198
    /**
199
     * @param string|array $html
200
     * @return string
201
     */
202
    private function normalizeHtml($html)
203
    {
204
        return ToString::value($html);
205
    }
206
}
207