Completed
Branch master (23c5f7)
by Nils
03:13
created

XPathExistsRule::doValidation()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 26
rs 8.439
cc 5
eloc 18
nc 5
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
8
/**
9
 * This rule checks if xpath is found in a html document.
10
 */
11
class XPathExistsRule extends StandardRule
12
{
13
    protected $contentTypes = ['text/html'];
14
15
    private $xPaths;
16
17
    public function init(array $xPaths)
18
    {
19
        $this->xPaths = $xPaths;
20
    }
21
22
    public function doValidation(Response $response)
23
    {
24
        $domDocument = new \DOMDocument();
25
        @$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...
26
27
        $domXPath = new \DOMXPath($domDocument);
28
29
        foreach ($this->xPaths as $xpath) {
30
            $count = $domXPath->query($xpath['pattern'])->length;
31
32
            if ($xpath['relation'] = 'equals') {
33
                $result = $count === $xpath['value'];
34
                $message = 'The xpath "' . $xpath['pattern'] . '" was found ' . $count . ' times. Expected were exact ' . $xpath['value'] . ' occurencies.';
35
            } elseif ($xpath['relation'] === 'less than') {
36
                $result = $count < $xpath['value'];
37
                $message = 'The xpath "' . $xpath['pattern'] . '" was found ' . $count . ' times. Expected were less than ' . $xpath['value'] . '.';
38
            } elseif ($xpath['relation'] === 'greater than') {
39
                $result = $count > $xpath['value'];
40
                $message = 'The xpath "' . $xpath['pattern'] . '" was found ' . $count . ' times. Expected were more than ' . $xpath['value'] . '.';
41
            } else {
42
                throw new \RuntimeException('Relation not defined. Given "' . $xpath['relation'] . '" expected [equals, greater than, less than]');
43
            }
44
45
            $this->assert($result, $message);
46
        }
47
    }
48
}
49