Completed
Push — master ( a046ab...1a416e )
by Бабичев
02:17
created

AHTMLNode::offsetGet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Bavix\AdvancedHtmlDom;
4
5
/**
6
 * Class AHTMLNode
7
 *
8
 * @package Bavix\AdvancedHtmlDom
9
 *
10
 * @property-read string $clean_text
11
 */
12
class AHTMLNode extends AdvancedHtmlBase implements \ArrayAccess
13
{
14
15
    /**
16
     * @var
17
     */
18
    private $_path;
19
20
    /**
21
     * AHTMLNode constructor.
22
     *
23
     * @param $node
24
     * @param $doc
25
     */
26 4
    public function __construct($node, $doc)
27
    {
28 4
        $this->node    = $node;
29 4
        $this->_path   = $node->getNodePath();
30 4
        $this->doc     = $doc;
31 4
        $this->is_text = $node->nodeName === '#text';
32 4
    }
33
34
    /**
35
     * @inheritdoc
36
     */
37 2
    public function __destruct()
38
    {
39 2
        $this->_path = null;
40 2
        unset($this->_path);
41 2
        parent::__destruct();
42 2
    }
43
44
    /**
45
     * @param $html
46
     *
47
     * @return mixed
48
     */
49
    private function get_fragment($html)
50
    {
51
        $dom = $this->doc->dom;
52
        $fragment = $dom->createDocumentFragment() or die('nope');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
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...
53
        $fragment->appendXML($html);
54
55
        return $fragment;
56
    }
57
58
    /**
59
     * @param $html
60
     *
61
     * @return AHTMLNode|null
62
     */
63
    public function replace($html)
64
    {
65
        $node = empty($html) ? null : $this->before($html);
66
        $this->remove();
67
68
        return $node;
69
    }
70
71
    /**
72
     * @param $html
73
     *
74
     * @return AHTMLNode
75
     */
76
    public function before($html)
77
    {
78
        $fragment = $this->get_fragment($html);
79
        $this->node->parentNode->insertBefore($fragment, $this->node);
80
81
        return new AHTMLNode($this->node->previousSibling, $this->doc);
82
    }
83
84
    /**
85
     * @param $html
86
     */
87
    public function after($html)
88
    {
89
        $fragment = $this->get_fragment($html);
90
        if ($ref_node = $this->node->nextSibling)
91
        {
92
            $this->node->parentNode->insertBefore($fragment, $ref_node);
93
        } else {
94
            $this->node->parentNode->appendChild($fragment);
95
        }
96
    }
97
98
    /**
99
     * @param $str
100
     *
101
     * @return mixed
102
     */
103
    public function decamelize($str)
104
    {
105
        $str = \preg_replace_callback(
106
            '/(^|[a-z])([A-Z])/',
107
            function($matches) {
108
                return
109
                    \strtolower(
110
                        \strlen($matches[1])
111
                            ? $matches[1] . '_' . $matches[2] : $matches[2]
112
                    );
113
            },
114
            $str
115
        );
116
117
        return \preg_replace('/ /', '_', \strtolower($str));
118
    }
119
120
    /**
121
     * @return array
122
     */
123
    public function attributes()
124
    {
125
        $ret = array();
126
        foreach ($this->node->attributes as $attr) {
127
            $ret[$attr->nodeName] = $attr->nodeValue;
128
        }
129
130
        return $ret;
131
    }
132
133
    /**
134
     * @param null $key
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $key is correct as it would always require null to be passed?
Loading history...
135
     * @param int  $level
136
     *
137
     * @return array
138
     */
139
    public function flatten($key = null, $level = 1)
140
    {
141
142
        $children = $this->children;
0 ignored issues
show
Bug Best Practice introduced by
The property children does not exist on Bavix\AdvancedHtmlDom\AHTMLNode. Since you implemented __get, consider adding a @property annotation.
Loading history...
143
        $ret      = array();
144
        $tag      = $this->tag;
0 ignored issues
show
Bug Best Practice introduced by
The property tag does not exist on Bavix\AdvancedHtmlDom\AHTMLNode. Since you implemented __get, consider adding a @property annotation.
Loading history...
145
146
        if ($this->at('./preceding-sibling::' . $this->tag) || $this->at('./following-sibling::' . $this->tag) || ($key = $this->tag . 's'))
0 ignored issues
show
Bug introduced by
Are you sure $this->tag of type null|Bavix\AdvancedHtmlD...edHtmlDom\AHTMLNodeList can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

146
        if ($this->at('./preceding-sibling::' . /** @scrutinizer ignore-type */ $this->tag) || $this->at('./following-sibling::' . $this->tag) || ($key = $this->tag . 's'))
Loading history...
Bug introduced by
The method at() does not exist on Bavix\AdvancedHtmlDom\AHTMLNode. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

146
        if ($this->/** @scrutinizer ignore-call */ at('./preceding-sibling::' . $this->tag) || $this->at('./following-sibling::' . $this->tag) || ($key = $this->tag . 's'))
Loading history...
147
        {
148
            $count = $this->search('./preceding-sibling::' . $this->tag)->length + 1;
0 ignored issues
show
Bug Best Practice introduced by
The property length does not exist on Bavix\AdvancedHtmlDom\AHTMLNodeList. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
The method search() does not exist on Bavix\AdvancedHtmlDom\AHTMLNode. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

148
            $count = $this->/** @scrutinizer ignore-call */ search('./preceding-sibling::' . $this->tag)->length + 1;
Loading history...
149
            $tag .= '_' . $count;
150
        }
151
152
        if ($children->length == 0)
153
        {
154
            $ret[$this->decamelize(\implode(' ', \array_filter(array($key, $tag))))] = $this->text;
0 ignored issues
show
Bug Best Practice introduced by
The property text does not exist on Bavix\AdvancedHtmlDom\AHTMLNode. Since you implemented __get, consider adding a @property annotation.
Loading history...
155
        } else {
156
            $flatten = [];
157
            foreach ($children as $child)
158
            {
159
                $flatten[] = $child->flatten(\implode(' ', \array_filter(array($key, $level <= 0 ? $tag : null))), $level - 1);
160
//                $ret = array_merge($ret, $child->flatten(implode(' ', array_filter(array($key, $level <= 0 ? $tag : null))), $level - 1));
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
161
            }
162
163
            $ret = \array_merge($ret, ...$flatten);
164
        }
165
166
        return $ret;
167
    }
168
169
    /**
170
     * @param $name
171
     * @param $value
172
     */
173
    public function __set($name, $value)
174
    {
175
        switch ($name)
176
        {
177
            case 'text':
178
            case 'innertext':
179
            case 'innerText':
180
            case 'plaintext':
181
                $this->node->nodeValue = $value;
182
183
                return;
184
            case 'outertext':
185
                $this->replace($value);
186
187
                return;
188
            case 'tag':
189
                $el = $this->replace('<' . $value . '>' . $this->innerhtml . '</' . $value . '>');
0 ignored issues
show
Bug Best Practice introduced by
The property innerhtml does not exist on Bavix\AdvancedHtmlDom\AHTMLNode. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
Are you sure $this->innerhtml of type null|Bavix\AdvancedHtmlD...edHtmlDom\AHTMLNodeList can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

189
                $el = $this->replace('<' . $value . '>' . /** @scrutinizer ignore-type */ $this->innerhtml . '</' . $value . '>');
Loading history...
190
                foreach ($this->node->attributes as $_name => $att)
191
                {
192
                    $el->$_name = $att->nodeValue;
193
                }
194
                $this->node = $el->node;
195
196
                return;
197
198
        }
199
200
        $this->offsetSet($name, $value);
201
    }
202
203
    /**
204
     * @param mixed $offset
205
     *
206
     * @return bool
207
     */
208
    public function offsetExists($offset)
209
    {
210
        return true;
211
    }
212
213
    /**
214
     * @param mixed $offset
215
     *
216
     * @return mixed
217
     */
218
    public function offsetGet($offset)
219
    {
220
        return $this->node->getAttribute($offset);
221
    }
222
223
    /**
224
     * @param mixed $key
225
     * @param mixed $value
226
     */
227
    public function offsetSet($key, $value)
228
    {
229
        if (\in_array($key, ['_path','dom','doc','node']))
230
        {
231
            return;
232
        }
233
234
        if ($value)
235
        {
236
            $this->node->setAttribute($key, $value);
237
            return;
238
        }
239
240
        $this->node->removeAttribute($key);
241
        //trigger_error('offsetSet not implemented', E_USER_WARNING);
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
242
    }
243
244
    /**
245
     * @param mixed $offset
246
     */
247
    public function offsetUnset($offset)
248
    {
249
        \trigger_error('offsetUnset not implemented', E_USER_WARNING);
250
    }
251
252
    /**
253
     * @return mixed
254
     */
255
    public function title()
256
    {
257
        return $this->node->getAttribute('title');
258
    }
259
}
260