DateTimeHandler   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 68.75%

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 0
dl 0
loc 48
c 0
b 0
f 0
ccs 11
cts 16
cp 0.6875
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A toResource() 0 16 4
A fromResource() 0 12 3
A supports() 0 4 1
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
}