Completed
Push — master ( 0e62dc...fa05db )
by Ivan
03:20
created

Reader::setDocumentContent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4286
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
3
namespace SP\Crawler;
4
5
use SP\Spiderling\CrawlerInterface;
6
use SP\Crawler\Element\ClickRequestInterface;
7
use SP\Crawler\Element\ClickableInterface;
8
use SP\Crawler\Element\SelectableInterface;
9
use Psr\Http\Message\RequestInterface;
10
use SP\Spiderling\Query\AbstractQuery;
11
use GuzzleHttp\Psr7\Uri;
12
use Psr\Http\Message\UriInterface;
13
use DOMDocument;
14
use DOMElement;
15
use DOMXPath;
16
use InvalidArgumentException;
17
use BadMethodCallException;
18
19
/**
20
 * @author    Ivan Kerin <[email protected]>
21
 * @copyright 2015, Clippings Ltd.
22
 * @license   http://spdx.org/licenses/BSD-3-Clause
23
 */
24
class Reader implements CrawlerInterface
25
{
26
    /**
27
     * @var DOMDocument
28
     */
29
    private $document;
30
31
    /**
32
     * @var DOMXPath
33
     */
34
    private $xpath;
35
36
    /**
37
     * @var ElementMap
38
     */
39
    private $inputMap;
40
41
    /**
42
     * @param DOMDocument $document
43
     */
44 1
    public function __construct(DOMDocument $document)
45
    {
46 1
        $this->document = $document;
47
48 1
        $this->xpath = new DOMXPath($document);
49
50 1
        $this->inputMap = new InputMap($this);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \SP\Crawler\InputMap($this) of type object<SP\Crawler\InputMap> is incompatible with the declared type object<SP\Crawler\ElementMap> of property $inputMap.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
51 1
    }
52
53
    /**
54
     * @param  string $content
55
     * @return self
56
     */
57 1
    public function setDocumentContent($content)
58
    {
59 1
        $this->document->loadHtml((string) $content);
60 1
        $this->xpath = new DOMXPath($this->document);
61
62 1
        return $this;
63
    }
64
65
    /**
66
     * @return DOMDocument
67
     */
68 1
    public function getDocument()
69
    {
70 1
        return $this->document;
71
    }
72
73
    /**
74
     * @return DOMXPath
75
     */
76 1
    public function getXPath()
77
    {
78 1
        return $this->xpath;
79
    }
80
81
    /**
82
     * @return ElementMap
83
     */
84 1
    public function getInputMap()
85
    {
86 1
        return $this->inputMap;
87
    }
88
89
    /**
90
     * @param  string $id
91
     * @throws BadMethodCallException
92
     */
93 3
    public function click($id)
94
    {
95 3
        $input = $this->getInput($this->getElement($id));
96
97 3
        if ($input instanceof ClickableInterface) {
98 1
            $input->click();
99 3
        } elseif ($input instanceof ClickRequestInterface) {
100 1
            $request = $input->clickRequest();
101 1
            $this->sendRequest($request);
102 1
        } else {
103 1
            throw new BadMethodCallException(
104 1
                sprintf('Cannot click on %s, %s', get_class($input), $id)
105 1
            );
106
        }
107 2
    }
108
109
    /**
110
     * @param  string $id
111
     * @throws BadMethodCallException
112
     */
113 2
    public function select($id)
114
    {
115 2
        $input = $this->getInput($this->getElement($id));
116
117 2
        if ($input instanceof SelectableInterface) {
118 1
            $input->select();
119 1
        } else {
120 1
            throw new BadMethodCallException(
121 1
                sprintf('Cannot select on %s, %s', get_class($input), $id)
122 1
            );
123
        }
124 1
    }
125
126
    /**
127
     * @param  RequestInterface $input
0 ignored issues
show
Bug introduced by
There is no parameter named $input. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
128
     * @throws BadMethodCallException
129
     */
130 1
    public function sendRequest(RequestInterface $request)
131
    {
132 1
        throw new BadMethodCallException(
133 1
            sprintf('Cannot send request to %s', $request->getUri())
134 1
        );
135
    }
136
137
    /**
138
     * @param  string $url
139
     * @throws BadMethodCallException
140
     */
141 1
    public function open(UriInterface $url)
142
    {
143 1
        throw new BadMethodCallException(
144 1
            sprintf('Method %s not supported by %s', __METHOD__, __CLASS__)
145 1
        );
146
    }
147
148
    /**
149
     * @return Psr\Http\Message\UriInterface
150
     */
151 1
    public function getUri()
152
    {
153 1
        return new Uri('');
154
    }
155
156
    /**
157
     * @param  string          $xpath
158
     * @param  DOMElement|null $scope
159
     * @return DOMNodeList
160
     */
161 1
    public function query($xpath, DOMElement $scope = null)
162
    {
163 1
        return $this->getXpath()->query($xpath, $scope);
164
    }
165
166
    /**
167
     * @param  string $xpath
168
     * @throws InvalidArgumentException when id not found
169
     * @return DOMElement
170
     */
171 1
    public function getElement($xpath)
172
    {
173 1
        $items = $this->query($xpath);
174
175 1
        if (0 === $items->length) {
176 1
            throw new InvalidArgumentException(
177 1
                sprintf('Node with id %s does not exist', $xpath)
178 1
            );
179
        }
180
181 1
        return $items->item(0);
182
    }
183
184
    /**
185
     * @param  string $id
186
     * @throws InvalidArgumentException when id not found
187
     * @return string
188
     */
189 1
    public function getText($id)
190
    {
191 1
        $element = $this->getElement($id);
192
193 1
        return trim(preg_replace('/[ \s\f\n\r\t\v ]+/u', ' ', $element->textContent));
194
    }
195
196
    /**
197
     * @param  string $id
198
     * @throws InvalidArgumentException when id not found
199
     * @return string
200
     */
201 1
    public function getTagName($id)
202
    {
203 1
        return $this->getElement($id)->tagName;
204
    }
205
206
    /**
207
     * @param  string $id
208
     * @param  string $name
209
     * @throws InvalidArgumentException when id not found
210
     * @return string
211
     */
212 1
    public function getAttribute($id, $name)
213
    {
214 1
        return $this->getElement($id)->getAttribute($name);
215
    }
216
217
    /**
218
     * @param  string $id
219
     * @throws InvalidArgumentException when id not found
220
     * @return string
221
     */
222 1
    public function getHtml($id)
223
    {
224 1
        return $this->document->saveXml($this->getElement($id));
225
    }
226
227
    /**
228
     * @return string
229
     */
230 1
    public function getFullHtml()
231
    {
232 1
        return $this->document->saveHtml();
233
    }
234
235
    /**
236
     * @param  string $id
237
     * @throws InvalidArgumentException when id not found
238
     * @return boolean
239
     */
240 3
    public function isVisible($id)
241
    {
242 3
        $element = $this->getElement($id);
243
244
        $conditions = [
245 3
            "contains(@style, 'display:none')",
246 3
            "contains(@style, 'display: none')",
247 3
            "self::script",
248 3
            "self::head",
249 3
        ];
250
251 3
        $hidden = $this->xpath->query(
252 3
            './ancestor-or-self::*['.join(' or ', $conditions).']',
253
            $element
254 3
        );
255
256 3
        return $hidden->length == 0;
257
    }
258
259
    /**
260
     * @param  string $id
261
     * @throws InvalidArgumentException when id not found
262
     * @return boolean
263
     */
264 4
    public function isSelected($id)
265
    {
266 4
        return $this->getElement($id)->hasAttribute('selected');
267
    }
268
269
    /**
270
     * @param  string $id
271
     * @throws InvalidArgumentException when id not found
272
     * @return boolean
273
     */
274 6
    public function isChecked($id)
275
    {
276 6
        return $this->getElement($id)->hasAttribute('checked');
277
    }
278
279
    /**
280
     * @param  DOMElement $element
281
     * @throws InvalidArgumentException when id not found
282
     * @return Element\AbstractElement
283
     */
284 9
    public function getInput(DOMElement $element)
285
    {
286 9
        return $this->inputMap->get($element);
287
    }
288
289
    /**
290
     * @param  string $id
291
     * @throws InvalidArgumentException when id not found
292
     * @return mixed
293
     */
294 1
    public function getValue($id)
295
    {
296 1
        return $this->getInput($this->getElement($id))->getValue();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SP\Crawler\Element\AbstractElement as the method getValue() does only exist in the following sub-classes of SP\Crawler\Element\AbstractElement: SP\Crawler\Element\Checkbox, SP\Crawler\Element\File, SP\Crawler\Element\Input, SP\Crawler\Element\Option, SP\Crawler\Element\Radio, SP\Crawler\Element\Select, SP\Crawler\Element\Textarea. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
297
    }
298
299
    /**
300
     * @param  string $id
301
     * @param  string $value
302
     * @throws InvalidArgumentException when id not found
303
     */
304 1
    public function setValue($id, $value)
305
    {
306 1
        $input = $this->getInput($this->getElement($id));
307
308 1
        if (false === $input->isDisabled()) {
309 1
            $input->setValue($value);
310 1
        }
311 1
    }
312
313
    /**
314
     * @param  AbstractQuery $query
315
     * @param  string        $parent
316
     * @return array
317
     */
318 1
    public function queryIds(AbstractQuery $query, $parent = null)
319
    {
320 1
        $xpath = $parent.$query->getXPath();
321
322 1
        $ids = [];
323
324 1
        foreach ($this->query($xpath) as $index => $element) {
325 1
            $ids []= "($xpath)[".($index+1)."]";
326 1
        }
327
328 1
        return $query->getFilters()->matchAll($this, $ids);
329
    }
330
}
331