1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LaravelFr\ApiTesting; |
4
|
|
|
|
5
|
|
|
use Illuminate\Foundation\Testing\Concerns\MakesHttpRequests; |
6
|
|
|
|
7
|
|
|
trait AssertJsonResponse |
8
|
|
|
{ |
9
|
|
|
use AssertArrays, MakesHttpRequests; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Assert that the JSON response has exactly the given structure. |
13
|
|
|
* |
14
|
|
|
* @param array $structure |
15
|
|
|
* @param array|null $responseData |
16
|
|
|
* |
17
|
|
|
* @return $this |
18
|
|
|
*/ |
19
|
1 |
|
public function seeJsonStructureEquals(array $structure, $responseData = null) |
20
|
|
|
{ |
21
|
1 |
|
if (!$responseData) { |
22
|
1 |
|
$responseData = $this->decodeResponseJson(); |
23
|
|
|
} |
24
|
|
|
|
25
|
1 |
|
return $this->assertArrayStructureEquals($structure, $responseData); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Return the json response or a part of it as an array. |
30
|
|
|
* |
31
|
|
|
* @param string $key |
32
|
|
|
* |
33
|
|
|
* @return mixed |
34
|
|
|
*/ |
35
|
1 |
|
public function jsonResponse($key = null) |
36
|
|
|
{ |
37
|
1 |
|
$response = $this->decodeResponseJson(); |
38
|
|
|
|
39
|
1 |
|
return $key ? array_get($response, $key) : $response; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Assert that the JSON response has a given typed structure. |
44
|
|
|
* |
45
|
|
|
* @param array|null $structure |
46
|
|
|
* @param array|null $responseData |
47
|
|
|
* @return $this |
48
|
|
|
*/ |
49
|
1 |
|
public function seeJsonTypedStructure(array $structure = null, $responseData = null) |
50
|
|
|
{ |
51
|
1 |
|
if (is_null($structure)) { |
52
|
|
|
return $this->seeJsonStructure($structure); |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
if (!$responseData) { |
56
|
1 |
|
$responseData = json_decode($this->response->getContent(), true); |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
foreach ($structure as $key => $type) { |
60
|
1 |
|
if (is_array($type) && $key === '*') { |
61
|
|
|
$this->assertInternalType('array', $responseData); |
62
|
|
|
|
63
|
|
|
foreach ($responseData as $responseDataItem) { |
64
|
|
|
$this->seeJsonTypedStructure($structure['*'], $responseDataItem); |
65
|
|
|
} |
66
|
1 |
|
} elseif (is_array($type) && array_key_exists($key, $structure)) { |
67
|
1 |
|
if (is_array($structure[$key])) { |
68
|
1 |
|
$this->seeJsonTypedStructure($structure[$key], $responseData[$key]); |
69
|
|
|
} |
70
|
|
|
} else { |
71
|
1 |
|
$this->assertInternalType($type, $responseData[$key]); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
1 |
|
return $this; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|