DateTimeConverter::parseDateTimeToString()   B
last analyzed

Complexity

Conditions 7
Paths 5

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 7.0957

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 16
ccs 7
cts 8
cp 0.875
rs 8.8333
c 0
b 0
f 0
cc 7
nc 5
nop 1
crap 7.0957
1
<?php
2
3
namespace kalanis\Restful\Converters;
4
5
6
use DateTime;
7
use DateTimeInterface;
8
use Traversable;
9
10
11
/**
12
 * DateTimeConverter
13
 * @package kalanis\Restful\Converters
14
 * @template TK of string
15
 * @template TVal of mixed
16
 * @implements IConverter<TK, TVal>
17
 */
18 1
class DateTimeConverter implements IConverter
19
{
20
21
    /**
22
     * @param string $format of date time
23
     */
24 1
    public function __construct(
25
        private readonly string $format = 'c',
26
    )
27
    {
28 1
    }
29
30
    /**
31
     * Converts DateTime objects in resource to string
32
     * @param array<TK, TVal> $resource
33
     * @return array<int|string, mixed>
34
     */
35
    public function convert(array $resource): array
36
    {
37 1
        return (array) $this->parseDateTimeToString($resource);
38
    }
39
40
    /**
41
     * @param array<TK, TVal>|Traversable<TK, TVal>|string|int|object $array
42
     * @return array<string, mixed>|string
43
     */
44
    private function parseDateTimeToString(mixed $array): array|string
45
    {
46 1
        if (!is_array($array)) {
47 1
            if ($array instanceof DateTime || interface_exists('DateTimeInterface') && $array instanceof DateTimeInterface) {
48 1
                return $array->format($this->format);
49
            }
50
            return strval($array);
51
        }
52
53 1
        foreach ($array as $key => $value) {
54 1
            if (is_iterable($array)) {
55
                /** @var string|int|object $value */
56 1
                $array[$key] = $this->parseDateTimeToString($value);
57
            }
58
        }
59 1
        return $array;
60
    }
61
}
62