Completed
Push — caching ( 6c9b2f )
by Nate
03:39
created

DateTimeTypeAdapter::read()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 21
rs 9.8666
cc 3
nc 3
nop 2
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
     * Constructor
32
     *
33
     * @param TypeToken $type
34
     */
35
    public function __construct(TypeToken $type)
36
    {
37
        $this->type = $type;
38
    }
39
40
    /**
41
     * Read the next value, convert it to its type and return it
42
     *
43
     * @param string|null $value
44
     * @param ReaderContext $context
45
     * @return DateTimeInterface|null
46
     */
47
    public function read($value, ReaderContext $context): ?DateTimeInterface
48
    {
49
        if ($value === null) {
50
            return null;
51
        }
52
53
        $class = $this->type->rawType;
54
        $format = $context->getDateFormat();
55
56
        /** @noinspection PhpUndefinedMethodInspection */
57
        $dateTime = $class::createFromFormat($format, $value);
58
59
        if ($dateTime !== false) {
60
            return $dateTime;
61
        }
62
63
        throw new JsonSyntaxException(sprintf(
64
            'Could not create "%s" class from "%s" using format "%s"',
65
            $class,
66
            $value,
67
            $format
68
        ));
69
    }
70
71
    /**
72
     * Write the value to the writer for the type
73
     *
74
     * @param DateTimeInterface $value
75
     * @param WriterContext $context
76
     * @return string|null
77
     */
78
    public function write($value, WriterContext $context): ?string
79
    {
80
        return $value === null ? null : $value->format($context->getDateFormat());
81
    }
82
83
    /**
84
     * Return true if object can be written to disk
85
     *
86
     * @return bool
87
     */
88
    public function canCache(): bool
89
    {
90
        return true;
91
    }
92
}
93