Passed
Pull Request — master (#22)
by Aleksei
02:32
created

Date::__toString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Http\Header\Value;
6
7
use DateTimeImmutable;
8
use DateTimeInterface;
9
use Exception;
10
use Yiisoft\Http\Header\DateHeader;
11
use Yiisoft\Http\Header\Internal\BaseHeaderValue;
12
13
class Date extends BaseHeaderValue
14
{
15
    public const NAME = 'Date';
16
17
    private ?DateTimeImmutable $datetimeObject = null;
18
19
    /**
20
     * Date constructor.
21
     * @param DateTimeInterface|string $value
22
     */
23 11
    public function __construct($value = '')
24
    {
25 11
        if ($value instanceof DateTimeInterface) {
26 1
            $value = $value->format(DateTimeInterface::RFC7231);
27
        }
28 11
        parent::__construct($value);
29 11
    }
30
31 6
    public function __toString(): string
32
    {
33 6
        return $this->datetimeObject === null
34 3
            ? parent::__toString()
35 6
            : $this->datetimeObject->format(DateTimeInterface::RFC7231);
36
    }
37
38
    final public static function createHeader(): DateHeader
39
    {
40
        return new DateHeader(static::class);
41
    }
42
43 7
    final public function getDatetimeValue(): ?DateTimeImmutable
44
    {
45 7
        return $this->datetimeObject;
46
    }
47
48 1
    final public function withValueFromDatetime(DateTimeInterface $date): self
49
    {
50 1
        return $this->withValue($date->format(DateTimeInterface::RFC7231));
51
    }
52
53 11
    final protected function setValue(string $value): void
54
    {
55
        try {
56 11
            if ($value !== '' && !$this->validateDateTime($value)) {
57 4
                throw new \InvalidArgumentException('Invalid date format.');
58
            }
59 10
            $this->datetimeObject = new DateTimeImmutable($value);
60 10
            $this->error = null;
61 4
        } catch (Exception $e) {
62 4
            $this->datetimeObject = null;
63 4
            $this->error = $e;
64
        }
65 11
        parent::setValue($value);
66 11
    }
67
}
68