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

DateTimeHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 75%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 0
dl 0
loc 40
ccs 9
cts 12
cp 0.75
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A toResource() 0 12 3
A fromResource() 0 8 2
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, 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
}