Completed
Push — master ( f0430d...4557df )
by Mathieu
01:34
created

AssertJsonResponse::addJsonResponseMacros()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 0
cts 10
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 0
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
    public function addJsonResponseMacros()
22
    {
23
        $trait = $this;
24
25
        TestResponse::macro('assertJsonStructureEquals', function ($structure) use ($trait) {
26
            return $trait->assertJsonStructureEquals($structure, $this->decodeResponseJson());
27
        });
28
29
        TestResponse::macro('seeJsonTypedStructure', function ($structure) use ($trait) {
30
            return $trait->seeJsonTypedStructure($structure, $this->decodeResponseJson());
31
        });
32
33
        TestResponse::macro('jsonResponse', function ($key = null) use ($trait) {
34
            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 1
    public function assertJsonStructureEquals($structure, $responseData = null)
47
    {
48 1
        if (!$responseData) {
49 1
            $responseData = $this->decodeResponseJson();
50 1
        }
51
52 1
        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 1
    public function seeJsonTypedStructure($structure, $responseData = null)
63
    {
64 1
        if (!$responseData) {
65 1
            $responseData = $this->decodeResponseJson();
66 1
        }
67
68 1
        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 1
    public function jsonResponse($key = null, $responseData = null)
80
    {
81 1
        if (!$responseData) {
82 1
            $responseData = $this->decodeResponseJson();
83 1
        }
84
85 1
        return array_get($responseData, $key);
86
    }
87
}
88