1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Inspirum\Arrayable\Tests; |
6
|
|
|
|
7
|
|
|
use Inspirum\Arrayable\BaseModel; |
8
|
|
|
use PHPUnit\Framework\TestCase; |
9
|
|
|
use Throwable; |
10
|
|
|
use function json_encode; |
11
|
|
|
|
12
|
|
|
final class BaseModelTest extends TestCase |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @param array<mixed> $data |
16
|
|
|
* |
17
|
|
|
* @dataProvider providesToArray |
18
|
|
|
*/ |
19
|
|
|
public function testJsonSerialize(array $data, string|Throwable $result): void |
20
|
|
|
{ |
21
|
|
|
if ($result instanceof Throwable) { |
22
|
|
|
self::expectException($result::class); |
23
|
|
|
self::expectExceptionMessage($result->getMessage()); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
$model = new class ($data) extends BaseModel { |
27
|
|
|
/** |
28
|
|
|
* @param array<mixed> $data |
29
|
|
|
*/ |
30
|
|
|
public function __construct(private array $data) |
31
|
|
|
{ |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @return array<mixed> |
36
|
|
|
*/ |
37
|
|
|
public function __toArray(): array |
38
|
|
|
{ |
39
|
|
|
return $this->data; |
40
|
|
|
} |
41
|
|
|
}; |
42
|
|
|
|
43
|
|
|
self::assertSame($data, $model->__toArray()); |
44
|
|
|
self::assertSame($data, $model->toArray()); |
45
|
|
|
self::assertSame($data, $model->jsonSerialize()); |
46
|
|
|
self::assertSame($result, (string) $model); |
47
|
|
|
self::assertSame($result, json_encode($model)); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @return iterable<array<string, mixed>> |
52
|
|
|
*/ |
53
|
|
|
public function providesToArray(): iterable |
54
|
|
|
{ |
55
|
|
|
yield [ |
56
|
|
|
'data' => [1, 3, 4], |
57
|
|
|
'result' => '[1,3,4]', |
58
|
|
|
]; |
59
|
|
|
|
60
|
|
|
yield [ |
61
|
|
|
'data' => ['a' => 1, 3, 'c' => true, 4], |
62
|
|
|
'result' => '{"a":1,"0":3,"c":true,"1":4}', |
63
|
|
|
]; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|