Completed
Push — master ( c78d5c...5cf6af )
by Nils
02:40
created

JsonPathExistsRule::checkRelation()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 6.9811
c 0
b 0
f 0
cc 7
eloc 15
nc 7
nop 3
1
<?php
2
3
namespace whm\Smoke\Rules\Json;
4
5
use Doctrine\Tests\Common\Annotations\False;
6
use Peekmo\JsonPath\JsonStore;
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, $value, $count)
33
    {
34
        switch ($relation) {
35
            case 'equals':
36
                if ($value !== $count) {
37
                    return false;
38
                }
39
                break;
40
            case 'less than':
41
                if ($value >= $count) {
42
                    return false;
43
                }
44
                break;
45
            case 'greater than':
46
                if ($value <= $count) {
47
                    return false;
48
                }
49
                break;
50
        }
51
52
        return true;
53
    }
54
55
    public function doValidation(Response $response)
56
    {
57
        $json = json_decode($response->getBody());
58
        $store = new JsonStore($json);
59
60
        $error = false;
61
        $noCorrectJsonPaths = array();
62
63
        foreach ($this->jsonPaths as $path) {
64
            $jsonValue = $store->get($path['pattern']);
65
            $count = count($jsonValue);
66
67
            if ($jsonValue === false || (is_array($jsonValue) && empty($jsonValue))) {
68
                $error = true;
69
                $noCorrectJsonPaths[] = $path['pattern'] . ' (JSON Path not found)';
70
            }
71
            if ($this->checkRelation($path['relation'], $path['value'], $count) === false) {
72
                $error = true;
73
                $noCorrectJsonPaths[] = $path['pattern'] . ' (number of JSONPaths is not correct corresponding to the given relation/value)';
74
            }
75
        }
76
77
        if ($error === true) {
78
            $allNoCorrectJsonPaths = implode('", "', $noCorrectJsonPaths);
79
            throw new ValidationFailedException('Disonances with JSON Paths "' . $allNoCorrectJsonPaths . '!');
80
        }
81
    }
82
}
83