-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConvertor.php
More file actions
77 lines (64 loc) · 1.82 KB
/
Convertor.php
File metadata and controls
77 lines (64 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
declare(strict_types=1);
namespace Inspirum\Arrayable;
use RuntimeException;
use UnexpectedValueException;
use stdClass;
use function is_int;
use function is_iterable;
use function is_string;
use const PHP_INT_MAX;
final class Convertor
{
/**
* Can be cast to array
*/
public static function isArrayable(mixed $data): bool
{
return is_iterable($data) || $data instanceof Arrayable || $data instanceof stdClass;
}
/**
* Cast anything to array
*
* @param positive-int|null $limit
*
* @return array<int|string,mixed>
*
* @throws \RuntimeException
*/
public static function toArray(mixed $data, ?int $limit = null): array
{
return self::toArrayWithDepth($data, $limit ?? PHP_INT_MAX, 1);
}
/**
* @return ($depth is 1 ? array<mixed> : mixed)
*/
private static function toArrayWithDepth(mixed $data, int $limit, int $depth): mixed
{
if ($limit <= 0) {
throw new UnexpectedValueException('Limit value should be positive number');
}
if ($depth > $limit) {
return $data;
}
if ($data instanceof Arrayable) {
$data = $data->__toArray();
} elseif ($data instanceof stdClass) {
$data = (array) $data;
}
if (is_iterable($data)) {
$arrayData = [];
foreach ($data as $k => $v) {
if (!is_int($k) && !is_string($k)) {
throw new RuntimeException('Iterable key must be int|string');
}
$arrayData[$k] = self::toArrayWithDepth($v, $limit, $depth + 1);
}
return $arrayData;
}
if ($depth === 1) {
throw new RuntimeException('Cannot cast to array');
}
return $data;
}
}