JsonPathExistsRule::doValidation()   B
last analyzed

Complexity

Conditions 8
Paths 11

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 8.1315
c 0
b 0
f 0
cc 8
nc 11
nop 1
1
<?php
2
3
namespace whm\Smoke\Rules\Json;
4
5
use Peekmo\JsonPath\JsonStore;
6
use Psr\Http\Message\ResponseInterface;
7
use whm\Smoke\Http\Response;
8
use whm\Smoke\Rules\StandardRule;
9
use whm\Smoke\Rules\ValidationFailedException;
10
11
/**
12
 * This rule checks if xpath is found in a html document.
13
 */
14
class JsonPathExistsRule extends StandardRule
15
{
16
    protected $contentTypes = ['json'];
17
18
    private $jsonPaths;
19
20
    public function init(array $jsonPaths)
21
    {
22
        $this->jsonPaths = $jsonPaths;
23
    }
24
25
    /**
26
     * @param $relation string
27
     * @param $value int
28
     * @param $count int
29
     *
30
     * @return bool
31
     */
32
    private function checkRelation($relation, $expected, $current)
33
    {
34
        switch ($relation) {
35
            case 'equals':
36
                if ($expected !== $current) {
37
                    return false;
38
                }
39
                break;
40
            case 'less than':
41
                if ($expected <= $current) {
42
                    return false;
43
                }
44
                break;
45
            case 'greater than':
46
                if ($expected >= $current) {
47
                    return false;
48
                }
49
                break;
50
        }
51
52
        return true;
53
    }
54
55
    public function doValidation(ResponseInterface $response)
56
    {
57
        $body = (string)$response->getBody();
58
59
        $json = json_decode($body);
60
61
        if (!$json) {
62
            throw new ValidationFailedException('The given json document is empty or not valid json.');
63
        }
64
65
        $store = new JsonStore($json);
66
67
        $error = false;
68
        $noCorrectJsonPaths = array();
69
70
        foreach ($this->jsonPaths as $path) {
71
            $jsonValue = $store->get($path['pattern']);
72
            $count = count($jsonValue);
73
74
            if ($jsonValue === false || (is_array($jsonValue) && empty($jsonValue))) {
75
                $error = true;
76
                $noCorrectJsonPaths[] = $path['pattern'] . ' (JSON path not found)';
77
            }
78
            if ($this->checkRelation($path['relation'], (int)$path['value'], $count) === false) {
79
                $error = true;
80
                $noCorrectJsonPaths[] = $path['pattern'] . ' (' . $count . ' elements found, expected ' . $path['relation'] . ' ' . $path['value'] . ')';
81
            }
82
        }
83
84
        if ($error === true) {
85
            $allNoCorrectJsonPaths = implode('", "', $noCorrectJsonPaths);
86
            throw new ValidationFailedException('Disonances with JSON Paths "' . $allNoCorrectJsonPaths . '!');
87
        }
88
    }
89
}
90