DateTimeTypeAdapter   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 17
c 0
b 0
f 0
dl 0
loc 64
ccs 18
cts 18
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A read() 0 20 3
A write() 0 3 2
A __construct() 0 4 1
1
<?php
2
/*
3
 * Copyright (c) Nate Brunette.
4
 * Distributed under the MIT License (http://opensource.org/licenses/MIT)
5
 */
6
7
declare(strict_types=1);
8
9
namespace Tebru\Gson\TypeAdapter;
10
11
use DateTimeInterface;
12
use Tebru\Gson\Context\ReaderContext;
13
use Tebru\Gson\Context\WriterContext;
14
use Tebru\Gson\Exception\JsonSyntaxException;
15
use Tebru\Gson\TypeAdapter;
16
use Tebru\PhpType\TypeToken;
17
18
/**
19
 * Class DateTimeTypeAdapter
20
 *
21
 * @author Nate Brunette <[email protected]>
22
 */
23
class DateTimeTypeAdapter extends TypeAdapter
24
{
25
    /**
26
     * @var TypeToken
27
     */
28
    protected $type;
29
30
    /**
31
     * @var string
32
     */
33
    protected $format;
34
35
    /**
36
     * Constructor
37
     *
38
     * @param TypeToken $type
39
     * @param string $format
40
     */
41 7
    public function __construct(TypeToken $type, string $format)
42
    {
43 7
        $this->type = $type;
44 7
        $this->format = $format;
45 7
    }
46
47
    /**
48
     * Read the next value, convert it to its type and return it
49
     *
50
     * @param string|null $value
51
     * @param ReaderContext $context
52
     * @return DateTimeInterface|null
53
     */
54 4
    public function read($value, ReaderContext $context): ?DateTimeInterface
55
    {
56 4
        if ($value === null) {
57 1
            return null;
58
        }
59
60 3
        $class = $this->type->rawType;
61
62
        /** @noinspection PhpUndefinedMethodInspection */
63 3
        $dateTime = $class::createFromFormat($this->format, $value);
64
65 3
        if ($dateTime !== false) {
66 2
            return $dateTime;
67
        }
68
69 1
        throw new JsonSyntaxException(sprintf(
70 1
            'Could not create "%s" class from "%s" using format "%s"',
71 1
            $class,
72 1
            $value,
73 1
            $this->format
74
        ));
75
    }
76
77
    /**
78
     * Write the value to the writer for the type
79
     *
80
     * @param DateTimeInterface $value
81
     * @param WriterContext $context
82
     * @return string|null
83
     */
84 3
    public function write($value, WriterContext $context): ?string
85
    {
86 3
        return $value === null ? null : $value->format($this->format);
87
    }
88
}
89