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

Date   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 91.67%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 21
dl 0
loc 54
ccs 22
cts 24
cp 0.9167
rs 10
c 1
b 0
f 1
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
     *
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