Passed
Push — master ( 486ab4...2a2608 )
by Michael
03:12
created

DateTimeHandler::toResource()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 6

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.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 4
nop 2
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, array $parameters)
19
    {
20 2
        if (! $value instanceof \DateTimeInterface) {
21 1
            $value = new \DateTimeImmutable((string) $value);
22
        }
23
24 2
        if (isset($parameters[self::PARAMETER_FORMAT])) {
25 2
            return $value->format($parameters[self::PARAMETER_FORMAT]);
26
        }
27
28
        return $value->format(DATE_RFC3339);
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 2
    public function fromResource($value)
35
    {
36 2
        if ($value instanceof \DateTimeInterface) {
37 1
            return $value;
38
        }
39
40 1
        return new \DateTimeImmutable((string) $value);
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function supports(): array
47
    {
48
        return ['datetime'];
49
    }
50
}