Completed
Pull Request — master (#92)
by
unknown
02:51
created

CssSelectorExistsRule::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace whm\Smoke\Rules\Html;
4
5
use whm\Smoke\Http\Response;
6
use whm\Smoke\Rules\StandardRule;
7
use Symfony\Component\CssSelector\CssSelectorConverter;
8
9
/**
10
 * This rule checks if xpath is found in a html document.
11
 */
12
class CssSelectorExistsRule extends StandardRule
13
{
14
    protected $contentTypes = ['text/html'];
15
16
    private $cssSelectors;
17
18
    public function init(array $cssSelectors)
19
    {
20
        $this->cssSelectors = $cssSelectors;
21
    }
22
23
    public function doValidation(Response $response)
24
    {
25
        $domDocument = new \DOMDocument();
26
        @$domDocument->loadHTML((string) $response->getBody());
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
27
28
        $domXPath = new \DOMXPath($domDocument);
29
30
        foreach ($this->cssSelectors as $selector) {
31
            $converter = new CssSelectorConverter();
32
            $selectorAsXPath = $converter->toXPath($selector);
33
34
            $count = $domXPath->query($selectorAsXPath)->length;
35
36
            if ($count > 0) {
37
                $result = $count;
38
                $message = 'The xpath "' . $selector . '" was found ' . $count . ' times.';
39
            } else {
40
                throw new \RuntimeException('CSS Selector ' . $selector .' not found in DOM.');
41
            }
42
            $this->assert($result, $message);
43
        }
44
    }
45
}
46