-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConvertor.php
68 lines (58 loc) · 1.62 KB
/
Convertor.php
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
<?php
declare(strict_types=1);
namespace Inspirum\Arrayable;
use RuntimeException;
use Traversable;
use UnexpectedValueException;
use stdClass;
use function is_array;
use function is_iterable;
use function iterator_to_array;
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;
}
/**
* 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);
}
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 Traversable) {
$data = iterator_to_array($data);
} elseif ($data instanceof Arrayable) {
$data = $data->__toArray();
} elseif ($data instanceof stdClass) {
$data = (array) $data;
}
if (is_array($data)) {
foreach ($data as $k => $v) {
$data[$k] = self::toArrayWithDepth($v, $limit, $depth + 1);
}
} elseif ($depth === 1) {
throw new RuntimeException('Cannot cast to array');
}
return $data;
}
}