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

Date   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 21
c 1
b 0
f 1
dl 0
loc 53
ccs 22
cts 24
cp 0.9167
rs 10
wmc 11

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A setValue() 0 13 4
A withValueFromDatetime() 0 3 1
A getDatetimeValue() 0 3 1
A __toString() 0 5 2
A createHeader() 0 3 1
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