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

Date::setValue()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

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