Normalize::normalizeArray()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Squareetlabs\LaravelToon\Toon;
6
7
use DateTime;
8
use DateTimeInterface;
9
10
class Normalize
11
{
12
    public static function normalize(mixed $value): mixed
13
    {
14
        if (null === $value || is_bool($value) || is_int($value) || is_float($value) || is_string($value)) {
15
            return $value;
16
        }
17
18
        if ($value instanceof DateTimeInterface) {
19
            return $value->format(DateTimeInterface::ATOM);
20
        }
21
22
        if (is_array($value)) {
23
            return self::normalizeArray($value);
24
        }
25
26
        if (is_object($value)) {
27
            return self::normalizeObject($value);
28
        }
29
30
        return null;
31
    }
32
33
    private static function normalizeArray(array $array): mixed
34
    {
35
        $result = [];
36
        foreach ($array as $key => $item) {
37
            $normalizedKey = is_int($key) ? $key : (string)$key;
38
            $result[$normalizedKey] = self::normalize($item);
39
        }
40
41
        return $result;
42
    }
43
44
    private static function normalizeObject(object $object): mixed
45
    {
46
        if ($object instanceof DateTime || $object instanceof DateTimeInterface) {
47
            return $object->format(DateTimeInterface::ATOM);
48
        }
49
50
        // Handle enums
51
        if (method_exists($object, 'name') && method_exists($object, 'cases')) {
52
            if (method_exists($object, 'value')) {
53
                return $object->value;
54
            }
55
56
            return $object->name;
57
        }
58
59
        // Try to convert object to array
60
        if (method_exists($object, 'toArray')) {
61
            return self::normalize($object->toArray());
62
        }
63
64
        if (method_exists($object, 'jsonSerialize')) {
65
            return self::normalize($object->jsonSerialize());
66
        }
67
68
        return json_decode(json_encode($object, JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
69
    }
70
}
71
72