Completed
Push — master ( 236b50...7a7214 )
by Lars
02:07
created

AbstractSimpleHtmlDom::__isset()   B

Complexity

Conditions 10
Paths 9

Size

Total Lines 22

Duplication

Lines 22
Ratio 100 %

Code Coverage

Tests 12
CRAP Score 10.2918

Importance

Changes 0
Metric Value
dl 22
loc 22
ccs 12
cts 14
cp 0.8571
rs 7.6666
c 0
b 0
f 0
cc 10
nc 9
nop 1
crap 10.2918

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace voku\helper;
6
7
abstract class AbstractSimpleHtmlDom
8
{
9
    /**
10
     * @var array
11
     */
12
    protected static $functionAliases = [
13
        'children'     => 'childNodes',
14
        'first_child'  => 'firstChild',
15
        'last_child'   => 'lastChild',
16
        'next_sibling' => 'nextSibling',
17
        'prev_sibling' => 'previousSibling',
18
        'parent'       => 'parentNode',
19
        'outertext'    => 'html',
20
        'outerhtml'    => 'html',
21
        'innertext'    => 'innerHtml',
22
        'innerhtml'    => 'innerHtml',
23
    ];
24
25
    /**
26
     * @var \DOMElement|\DOMNode|null
27
     */
28
    protected $node;
29
30
    /**
31
     * @var SimpleHtmlAttributes|null
32
     */
33
    private $classListCache;
34
35
    /**
36
     * @param string $name
37
     * @param array  $arguments
38
     *
39
     * @throws \BadMethodCallException
40
     *
41
     * @return SimpleHtmlDomInterface|string|null
42
     */
43
    public function __call($name, $arguments)
44
    {
45
        $name = \strtolower($name);
46
47
        if (isset(self::$functionAliases[$name])) {
48
            return \call_user_func_array([$this, self::$functionAliases[$name]], $arguments);
49
        }
50
51
        throw new \BadMethodCallException('Method does not exist');
52
    }
53
54
    /**
55
     * @param string $name
56
     *
57
     * @return array|string|null
58
     */
59 77
    public function __get($name)
60
    {
61 77
        $nameOrig = $name;
62 77
        $name = \strtolower($name);
63
64
        switch ($name) {
65 77
            case 'outerhtml':
66 71
            case 'outertext':
67 61
            case 'html':
68 26
                return $this->html();
69 60
            case 'innerhtml':
70 48
            case 'innertext':
71 18
                return $this->innerHtml();
72 45
            case 'text':
73 40
            case 'plaintext':
74 21
                return $this->text();
75 28
            case 'tag':
76 5
                return $this->node ? $this->node->nodeName : '';
77 26
            case 'attr':
78
                return $this->getAllAttributes();
79 26
            case 'classlist':
80 12
                if ($this->classListCache === null) {
81 12
                    $this->classListCache = new SimpleHtmlAttributes($this->node ?? null, 'class');
0 ignored issues
show
Bug introduced by
It seems like $this->node ?? null can also be of type object<DOMNode>; however, voku\helper\SimpleHtmlAttributes::__construct() does only seem to accept null|object<DOMElement>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
82
                }
83
84 12
                return $this->classListCache;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->classListCache; (voku\helper\SimpleHtmlAttributes) is incompatible with the return type documented by voku\helper\AbstractSimpleHtmlDom::__get of type array|string|null.

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...
85
            default:
86 14
                if ($this->node && \property_exists($this->node, $nameOrig)) {
87 2
                    if (is_string($this->node->{$nameOrig})) {
88 2
                        return HtmlDomParser::putReplacedBackToPreserveHtmlEntities($this->node->{$nameOrig});
89
                    }
90
91
                    return $this->node->{$nameOrig};
92
                }
93
94 14
                return $this->getAttribute($name);
95
        }
96
    }
97
98
    /**
99
     * @param string $selector
100
     * @param int    $idx
101
     *
102
     * @return SimpleHtmlDomInterface|SimpleHtmlDomInterface[]|SimpleHtmlDomNodeInterface
103
     */
104 12
    public function __invoke($selector, $idx = null)
105
    {
106 12
        return $this->find($selector, $idx);
107
    }
108
109
    /**
110
     * @param string $name
111
     *
112
     * @return bool
113
     */
114 1 View Code Duplication
    public function __isset($name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
115
    {
116 1
        $nameOrig = $name;
117 1
        $name = \strtolower($name);
118
119
        switch ($name) {
120 1
            case 'outertext':
121 1
            case 'outerhtml':
122 1
            case 'innertext':
123 1
            case 'innerhtml':
124 1
            case 'plaintext':
125 1
            case 'text':
126 1
            case 'tag':
127
                return true;
128
            default:
129 1
                if ($this->node && \property_exists($this->node, $nameOrig)) {
130
                    return isset($this->node->{$nameOrig});
131
                }
132
133 1
                return $this->hasAttribute($name);
134
        }
135
    }
136
137
    /**
138
     * @param string $name
139
     * @param mixed  $value
140
     *
141
     * @return SimpleHtmlDomInterface|null
142
     */
143 22
    public function __set($name, $value)
144
    {
145 22
        $nameOrig = $name;
146 22
        $name = \strtolower($name);
147
148
        switch ($name) {
149 22
            case 'outerhtml':
150 19
            case 'outertext':
151 5
                return $this->replaceNodeWithString($value);
152 17
            case 'innertext':
153 15
            case 'innerhtml':
154 8
                return $this->replaceChildWithString($value);
155 13
            case 'plaintext':
156 1
                return $this->replaceTextWithString($value);
157 12
            case 'classlist':
158 1
                $name = 'class';
159 1
                $nameOrig = 'class';
160 View Code Duplication
            default:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
161 12
                if ($this->node && \property_exists($this->node, $nameOrig)) {
162
                    return $this->node->{$nameOrig} = $value;
163
                }
164
165 12
                return $this->setAttribute($name, $value);
166
        }
167
    }
168
169
    /**
170
     * @return string
171
     */
172 3
    public function __toString()
173
    {
174 3
        return $this->html();
175
    }
176
177
    /**
178
     * @param string $name
179
     *
180
     * @return void
181
     */
182
    public function __unset($name)
183
    {
184
        /** @noinspection UnusedFunctionResultInspection */
185
        $this->removeAttribute($name);
186
    }
187
188
    abstract public function find(string $selector, $idx = null);
189
190
    abstract public function getAllAttributes();
191
192
    abstract public function getAttribute(string $name): string;
193
194
    abstract public function hasAttribute(string $name): bool;
195
196
    abstract public function html(bool $multiDecodeNewHtmlEntity = false): string;
197
198
    abstract public function innerHtml(bool $multiDecodeNewHtmlEntity = false): string;
199
200
    abstract public function removeAttribute(string $name): SimpleHtmlDomInterface;
201
202
    abstract protected function replaceChildWithString(string $string): SimpleHtmlDomInterface;
203
204
    abstract protected function replaceNodeWithString(string $string): SimpleHtmlDomInterface;
205
206
    abstract protected function replaceTextWithString($string): SimpleHtmlDomInterface;
207
208
    abstract public function setAttribute(string $name, $value = null, bool $strict = false): SimpleHtmlDomInterface;
209
210
    abstract public function text(): string;
211
}
212