Skip to content

Commit 728fcf4

Browse files
Assertions for verifying the data types of arrays (#19)
1 parent b0a95b6 commit 728fcf4

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

composer.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,12 @@
1818
"psr-4": {
1919
"JMac\\Testing\\": "src/"
2020
}
21+
},
22+
"extra": {
23+
"laravel": {
24+
"providers": [
25+
"JMac\\Testing\\AdditionalAssertionsServiceProvider"
26+
]
27+
}
2128
}
2229
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
namespace JMac\Testing;
4+
5+
use Illuminate\Support\ServiceProvider;
6+
use JMac\Testing\Traits\AdditionalAssertions;
7+
8+
class AdditionalAssertionsServiceProvider extends ServiceProvider
9+
{
10+
public function register()
11+
{
12+
$test_response_class = class_exists(\Illuminate\Testing\TestResponse::class)
13+
? \Illuminate\Testing\TestResponse::class
14+
: \Illuminate\Foundation\Testing\TestResponse::class;
15+
16+
if (!$test_response_class::hasMacro('assertJsonTypedStructure')) {
17+
$test_response_class::macro('assertJsonTypedStructure', function (array $structure) {
18+
AdditionalAssertions::assertArrayStructure($structure, $this->json());
19+
20+
return $this;
21+
});
22+
}
23+
}
24+
}
25+
26+

src/Traits/AdditionalAssertions.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,44 @@ public function assertValidationRuleContains($rule, string $class)
108108
}
109109
}
110110

111+
public static function assertArrayStructure(array $structure, array $actual)
112+
{
113+
foreach ($structure as $key => $type) {
114+
if (is_array($type) && $key === '*') {
115+
PHPUnitAssert::assertIsArray($actual);
116+
117+
foreach ($actual as $data) {
118+
static::assertArrayStructure($structure['*'], $data);
119+
}
120+
} elseif (is_array($type) && array_key_exists($key, $structure)) {
121+
if (is_array($structure[$key])) {
122+
static::assertArrayStructure($structure[$key], $actual[$key]);
123+
}
124+
} else {
125+
switch ($type) {
126+
case 'string':
127+
PHPUnitAssert::assertIsString($actual[$key]);
128+
break;
129+
case 'integer':
130+
PHPUnitAssert::assertIsInt($actual[$key]);
131+
break;
132+
case 'number':
133+
PHPUnitAssert::assertIsNumeric($actual[$key]);
134+
break;
135+
case 'boolean':
136+
PHPUnitAssert::assertIsBool($actual[$key]);
137+
break;
138+
case 'array':
139+
PHPUnitAssert::assertIsArray($actual[$key]);
140+
break;
141+
default:
142+
PHPUnitAssert::fail('unexpected type: ' . $type);
143+
}
144+
}
145+
}
146+
}
147+
148+
111149
private function normalizeRules(array $rules)
112150
{
113151
return array_map([$this, 'expandRules'], $rules);

0 commit comments

Comments
 (0)