Completed
Pull Request — master (#93)
by
unknown
07:36
created

JsonPathExistsRule   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 4 1
B checkRelation() 0 21 7
C doValidation() 0 27 7
1
<?php
2
3
namespace whm\Smoke\Rules\Json;
4
5
use Doctrine\Tests\Common\Annotations\False;
6
use whm\Smoke\Http\Response;
7
use whm\Smoke\Rules\StandardRule;
8
use whm\Smoke\Rules\ValidationFailedException;
9
use Peekmo\JsonPath\JsonPath;
10
use Peekmo\JsonPath\JsonStore;
11
12
/**
13
 * This rule checks if xpath is found in a html document.
14
 */
15
class JsonPathExistsRule extends StandardRule
16
{
17
    protected $contentTypes = ['json'];
18
19
    private $jsonPaths;
20
21
    public function init(array $jsonPaths)
22
    {
23
        $this->jsonPaths = $jsonPaths;
24
    }
25
26
    /**
27
     * @param $relation string
28
     * @param $value int
29
     * @param $count int
30
     * @return boolean
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
        return true;
52
    }
53
54
    public function doValidation(Response $response)
55
    {
56
        $json = json_decode($response->getBody());
57
        $store = new JsonStore($json);
58
59
        $error = false;
60
        $noCorrectJsonPaths = array();
61
62
        foreach ($this->jsonPaths as $path) {
63
            $jsonValue = $store->get($path['pattern']);
64
            $count = count($jsonValue);
65
66
            if ($jsonValue === FALSE || (is_array($jsonValue) && empty($jsonValue))) {
67
                $error = true;
68
                $noCorrectJsonPaths[] = $path['pattern'] . ' (JSON Path not found)';
69
            }
70
            if ($this->checkRelation($path['relation'], $path['value'], $count) === false) {
71
                $error = true;
72
                $noCorrectJsonPaths[] = $path['pattern'] . ' (number of JSONPaths is not correct corresponding to the given relation/value)';
73
            }
74
        }
75
76
        if ($error === true) {
77
            $allNoCorrectJsonPaths = implode('", "', $noCorrectJsonPaths);
78
            throw new ValidationFailedException('Disonances with JSON Paths "' . $allNoCorrectJsonPaths . '!');
79
        }
80
    }
81
}
82