Completed
Push — develop ( e0343e...7d04f4 )
by Daniel
08:13
created

JsonContext   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 65
rs 10
c 2
b 0
f 0
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A saveEntityIdAsVar() 0 5 1
A getVar() 0 6 2
A saveJsonVar() 0 3 1
A setJsonVarNode() 0 5 1
A getJsonVar() 0 6 2
1
<?php
2
3
use Behat\Gherkin\Node\PyStringNode;
4
use Behatch\Context\JsonContext as BaseJsonContext;
5
6
final class JsonContext extends BaseJsonContext
7
{
8
    private static $vars = [];
9
    private static $jsonVars = [];
10
11
    /**
12
     * @param $var
13
     * @return \Behatch\Json\Json
14
     * @throws Exception
15
     */
16
    public static function getJsonVar($var): \Behatch\Json\Json
17
    {
18
        if (!isset(self::$jsonVars[$var])) {
19
            throw new \Exception(sprintf("The JSON variable %s has not been set", $var));
20
        }
21
        return self::$jsonVars[$var];
22
    }
23
24
    /**
25
     * @param $var
26
     * @return mixed
27
     * @throws Exception
28
     */
29
    public static function getVar($var)
30
    {
31
        if (!isset(self::$vars[$var])) {
32
            throw new \Exception(sprintf("The variable %s has not been set", $var));
33
        }
34
        return self::$vars[$var];
35
    }
36
37
    /**
38
     * @Then save the entity id as :var
39
     * @param string $var
40
     * @throws Exception
41
     */
42
    public function saveEntityIdAsVar(string $var)
43
    {
44
        $json = $this->getJson();
45
        $id = $this->inspector->evaluate($json, '@id');
46
        static::$vars[$var] = $id;
0 ignored issues
show
Bug introduced by
Since $vars is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $vars to at least protected.
Loading history...
47
    }
48
49
    /**
50
     * @Given the json variable :name is:
51
     * @param string $name
52
     * @param PyStringNode $var
53
     */
54
    public function saveJsonVar(string $name, PyStringNode $var)
55
    {
56
        self::$jsonVars[$name] = new \Behatch\Json\Json($var);
57
    }
58
59
    /**
60
     * @Given the node :node of the json variable :name is equal to the variable :value
61
     * @param $node
62
     * @param $name
63
     * @param $value
64
     * @throws Exception
65
     */
66
    public function setJsonVarNode($node, $name, $value)
67
    {
68
        $jsonData = self::getJsonVar($name)->getContent();
69
        $jsonData->$node = self::getVar($value);
70
        $this->saveJsonVar($name, new PyStringNode([json_encode($jsonData)], 1));
71
    }
72
}
73