Completed
Pull Request — master (#92)
by
unknown
03:12
created

CssSelectorExistsRule   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 4 1
B doValidation() 0 28 4
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
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(Response $response)
25
    {
26
        $domDocument = new \DOMDocument();
27
        @$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...
28
29
        $domXPath = new \DOMXPath($domDocument);
30
31
        $error = false;
32
        $snotFoundSelectors = array();
33
34
        foreach ($this->cssSelectors as $selector) {
35
            $converter = new CssSelectorConverter();
36
            $selectorAsXPath = $converter->toXPath($selector['pattern']);
37
38
            $count = $domXPath->query($selectorAsXPath)->length;
39
40
            if ($count == 0) {
41
                $error = true;
42
                $snotFoundSelectors[] = $selector['pattern'];
43
            }
44
        }
45
46
        if ($error === true) {
47
            $allNotFoundSelectors = implode('", "', $snotFoundSelectors);
48
49
            throw new ValidationFailedException('CSS Selector "' . $allNotFoundSelectors .'" not found in DOM.');
50
        }
51
    }
52
}
53