CssSelectorExistsRule   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 6
c 0
b 0
f 0
lcom 1
cbo 4
dl 0
loc 48
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 4 1
A doValidation() 0 36 5
1
<?php
2
3
namespace whm\Smoke\Rules\Html;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Symfony\Component\CssSelector\CssSelectorConverter;
7
use whm\Smoke\Rules\StandardRule;
8
use whm\Smoke\Rules\ValidationFailedException;
9
10
/**
11
 * This rule checks if xpath is found in a html document.
12
 */
13
class CssSelectorExistsRule extends StandardRule
14
{
15
    protected $contentTypes = ['text/html'];
16
17
    private $cssSelectors;
18
19
    public function init(array $cssSelectors)
20
    {
21
        $this->cssSelectors = $cssSelectors;
22
    }
23
24
    public function doValidation(ResponseInterface $response)
25
    {
26
        $content = (string)$response->getBody();
27
28
        $domDocument = new \DOMDocument();
29
        @$domDocument->loadHTML($content);
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...
30
31
        $domXPath = new \DOMXPath($domDocument);
32
33
        $error = false;
34
        $snotFoundSelectors = array();
35
36
        $converter = new CssSelectorConverter();
37
38
        foreach ($this->cssSelectors as $selector) {
39
40
            try {
41
                $selectorAsXPath = $converter->toXPath($selector['pattern']);
42
            } catch (\Exception $e) {
43
                throw new ValidationFailedException('Invalid css selector (' . $selector['pattern'] . ').');
44
            }
45
46
            $count = $domXPath->query($selectorAsXPath)->length;
47
48
            if ($count === 0) {
49
                $error = true;
50
                $snotFoundSelectors[] = $selector['pattern'];
51
            }
52
        }
53
54
        if ($error === true) {
55
            $allNotFoundSelectors = implode('", "', $snotFoundSelectors);
56
57
            throw new ValidationFailedException('CSS Selector "' . $allNotFoundSelectors . '" not found in DOM.');
58
        }
59
    }
60
}
61