Issues (8)

src/Convertor.php (2 issues)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Inspirum\Arrayable;
6
7
use RuntimeException;
8
use UnexpectedValueException;
9
use stdClass;
10
use function is_iterable;
11
use const PHP_INT_MAX;
12
13
final class Convertor
14
{
15
    /**
16
     * Can be cast to array
17
     */
18 14
    public static function isArrayable(mixed $data): bool
19
    {
20 14
        return is_iterable($data) || $data instanceof Arrayable || $data instanceof stdClass;
21
    }
22
23
    /**
24
     * Cast anything to array
25
     *
26
     * @param positive-int|null $limit
0 ignored issues
show
Documentation Bug introduced by
The doc comment positive-int|null at position 0 could not be parsed: Unknown type name 'positive-int' at position 0 in positive-int|null.
Loading history...
27
     *
28
     * @return array<int|string,mixed>
29
     *
30
     * @throws \RuntimeException
31
     */
32 14
    public static function toArray(mixed $data, ?int $limit = null): array
33
    {
34 14
        return self::toArrayWithDepth($data, $limit ?? PHP_INT_MAX, 1);
35
    }
36
37
    /**
38
     * @return ($depth is 1 ? array<mixed> : mixed)
0 ignored issues
show
Documentation Bug introduced by
The doc comment ($depth at position 1 could not be parsed: Unknown type name '$depth' at position 1 in ($depth.
Loading history...
39
     */
40 14
    private static function toArrayWithDepth(mixed $data, int $limit, int $depth): mixed
41
    {
42 14
        if ($limit <= 0) {
43 2
            throw new UnexpectedValueException('Limit value should be positive number');
44
        }
45
46 12
        if ($depth > $limit) {
47 2
            return $data;
48
        }
49
50 12
        if ($data instanceof Arrayable) {
51 3
            $data = $data->__toArray();
52 12
        } elseif ($data instanceof stdClass) {
53 2
            $data = (array) $data;
54
        }
55
56 12
        if (is_iterable($data)) {
57 11
            $arrayData = [];
58 11
            foreach ($data as $k => $v) {
59 11
                $arrayData[$k] = self::toArrayWithDepth($v, $limit, $depth + 1);
60
            }
61
62 11
            return $arrayData;
63
        }
64
65 11
        if ($depth === 1) {
66 1
            throw new RuntimeException('Cannot cast to array');
67
        }
68
69 10
        return $data;
70
    }
71
}
72