Completed
Push — master ( c5c3fa...229692 )
by Nate
03:20
created

DateTimeTypeAdapter::read()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 12
cts 12
cp 1
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 14
nc 3
nop 1
crap 3
1
<?php
2
/*
3
 * Copyright (c) Nate Brunette.
4
 * Distributed under the MIT License (http://opensource.org/licenses/MIT)
5
 */
6
7
namespace Tebru\Gson\Internal\TypeAdapter;
8
9
use DateTime;
10
use Tebru\Gson\Exception\JsonSyntaxException;
11
use Tebru\Gson\JsonWritable;
12
use Tebru\Gson\JsonReadable;
13
use Tebru\Gson\JsonToken;
14
use Tebru\Gson\TypeAdapter;
15
use Tebru\PhpType\TypeToken;
16
17
/**
18
 * Class DateTimeTypeAdapter
19
 *
20
 * @author Nate Brunette <[email protected]>
21
 */
22
final class DateTimeTypeAdapter extends TypeAdapter
23
{
24
    /**
25
     * @var TypeToken
26
     */
27
    private $type;
28
29
    /**
30
     * @var string
31
     */
32
    private $format;
33
34
    /**
35
     * Constructor
36
     *
37
     * @param TypeToken $type
38
     * @param string $format
39
     */
40 5
    public function __construct(TypeToken $type, string $format)
41
    {
42 5
        $this->type = $type;
43 5
        $this->format = $format;
44 5
    }
45
46
    /**
47
     * Read the next value, convert it to its type and return it
48
     *
49
     * @param JsonReadable $reader
50
     * @return DateTime|null
51
     * @throws \Tebru\Gson\Exception\JsonSyntaxException If the DateTime could not be created from format
52
     */
53 3
    public function read(JsonReadable $reader): ?DateTime
54
    {
55 3
        if ($reader->peek() === JsonToken::NULL) {
56 1
            return $reader->nextNull();
57
        }
58
59 2
        $formattedDateTime = $reader->nextString();
60
61
        /** @var DateTime $class */
62 2
        $class = $this->type->getRawType();
63
64 2
        $dateTime = $class::createFromFormat($this->format, $formattedDateTime);
65
66 2
        if ($dateTime !== false) {
67 1
            return $dateTime;
68
        }
69
70 1
        throw new JsonSyntaxException(sprintf(
71 1
            'Could not create "%s" class from "%s" using format "%s" at "%s"',
72
            $class,
73
            $formattedDateTime,
74 1
            $this->format,
75 1
            $reader->getPath()
76
        ));
77
    }
78
79
    /**
80
     * Write the value to the writer for the type
81
     *
82
     * @param JsonWritable $writer
83
     * @param DateTime $value
84
     * @return void
85
     */
86 2
    public function write(JsonWritable $writer, $value): void
87
    {
88 2
        if (null === $value) {
89 1
            $writer->writeNull();
90
91 1
            return;
92
        }
93
94 1
        $dateTime = $value->format($this->format);
95 1
        $writer->writeString($dateTime);
96 1
    }
97
}
98