DateTimeHandler::fromResource()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 5
cts 6
cp 0.8333
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 3
crap 3.0416
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Component\JsonApi\Mapper\Handler\DataTypeHandler;
5
6
/**
7
 * DateTime handler
8
 *
9
 * @package Mikemirten\Component\JsonApi\Mapper\Handler\DataTypeHandler
10
 */
11
class DateTimeHandler implements DataTypeHandlerInterface
12
{
13
    const PARAMETER_FORMAT = 0;
14
15
    /**
16
     * {@inheritdoc}
17
     */
18 2
    public function toResource($value, string $type, array $parameters)
19
    {
20 2
        if ($value === null) {
21
            return;
22
        }
23
24 2
        if (! $value instanceof \DateTimeInterface) {
25 1
            $value = new \DateTimeImmutable((string) $value);
26
        }
27
28 2
        if (isset($parameters[self::PARAMETER_FORMAT])) {
29 2
            return $value->format($parameters[self::PARAMETER_FORMAT]);
30
        }
31
32
        return $value->format(DATE_RFC3339);
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 2
    public function fromResource($value, string $type, array $parameters)
39
    {
40 2
        if ($value === null) {
41
            return;
42
        }
43
44 2
        if ($value instanceof \DateTimeInterface) {
45 1
            return $value;
46
        }
47
48 1
        return new \DateTimeImmutable((string) $value);
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function supports(): array
55
    {
56
        return ['datetime'];
57
    }
58
}