Completed
Push — master ( 01d609...f0430d )
by Mathieu
11s
created

AssertJsonResponse::assertJsonStructureEquals()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
crap 2
1
<?php
2
3
namespace LaravelFr\ApiTesting;
4
5
use Illuminate\Foundation\Testing\TestResponse;
6
7
trait AssertJsonResponse
8
{
9
    use AssertArrays;
10
11
    public function __construct()
12
    {
13
        if (class_exists(TestResponse::class)) {
14
            $this->addJsonResponseMacros();
15
        }
16
    }
17
18
    /**
19
     * Add the functions to the TestResponse objects.
20
     */
21 1
    public function addJsonResponseMacros()
22
    {
23
        $trait = $this;
24
25
        TestResponse::macro('assertJsonStructureEquals', function ($structure) use ($trait) {
26 1
            return $trait->assertJsonStructureEquals($structure, $this->decodeResponseJson());
27
        });
28
29
        TestResponse::macro('seeJsonTypedStructure', function ($structure) use ($trait) {
30 1
            return $trait->seeJsonTypedStructure($structure, $this->decodeResponseJson());
31
        });
32
33 1
        TestResponse::macro('jsonResponse', function ($key = null) use ($trait) {
34 1
            return $trait->jsonResponse($key, $this->decodeResponseJson());
35
        });
36
    }
37
38
    /**
39
     * Assert that the JSON response has exactly the given structure.
40
     *
41
     * @param  array $structure
42
     * @param  array|null $responseData
43
     *
44
     * @return $this
45
     */
46 2
    public function assertJsonStructureEquals($structure, $responseData = null)
47
    {
48 2
        if (!$responseData) {
49 1
            $responseData = $this->decodeResponseJson();
50
        }
51
52 2
        return $this->assertArrayStructureEquals($structure, $responseData);
53
    }
54
55
    /**
56
     * Assert that the JSON response has a given typed structure.
57
     *
58
     * @param  array $structure
59
     * @param  array|null $responseData
60
     * @return $this
61
     */
62 2
    public function seeJsonTypedStructure($structure, $responseData = null)
63
    {
64 2
        if (!$responseData) {
65 1
            $responseData = $this->decodeResponseJson();
66
        }
67
68 2
        return $this->seeArrayTypedStructure($structure, $responseData);
69
    }
70
71
    /**
72
     * Return the json response or a part of it as an array.
73
     *
74
     * @param  string $key
75
     * @param  array|null $responseData
76
     *
77
     * @return mixed
78
     */
79 2
    public function jsonResponse($key = null, $responseData = null)
80
    {
81 2
        if (!$responseData) {
82 1
            $responseData = $this->decodeResponseJson();
83
        }
84
85 2
        return array_get($responseData, $key);
86
    }
87
}
88