DateFormatValueObject::getValue()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 3
c 1
b 0
f 1
dl 0
loc 6
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TimiTao\ValueObject\Beberlei\Nullable;
6
7
use DateTime;
8
use DateTimeImmutable;
9
use Exception;
10
use TimiTao\ValueObject\Nullable\DateTime\DateFormatValueObject as DateFormatValueObjectInterface;
11
12
abstract class DateFormatValueObject implements DateFormatValueObjectInterface
13
{
14
    private $value;
15
16
    private $format;
17
18
    /**
19
     * @throws Exception if value is invalid
20
     */
21
    public function __construct(?DateTimeImmutable $value, string $format = DateTime::ATOM)
22
    {
23
        $this->guard($value, $format);
24
        $this->value = $value;
25
        $this->format = $format;
26
    }
27
28
    public function equals(DateFormatValueObjectInterface $other): bool
29
    {
30
        if (static::class !== get_class($other)) {
31
            return false;
32
        }
33
        if ($this->getValue() === null xor $other->getValue() === null) {
34
            return false;
35
        }
36
        if ($this->getValue() === $other->getValue()) {
37
            return true;
38
        }
39
        /** @var DateTimeImmutable $dateTime */
40
        $dateTime = $this->getDateTime();
41
        /** @var DateTimeImmutable $otherDateTime */
42
        $otherDateTime = $other->getDateTime();
43
        return $dateTime->getTimestamp() === $otherDateTime->getTimestamp();
44
    }
45
46
    public function getValue(): ?string
47
    {
48
        if ($this->value === null) {
49
            return null;
50
        }
51
        return $this->value->format($this->format);
52
    }
53
54
    public function getDateTime(): ?DateTimeImmutable
55
    {
56
        return $this->value;
57
    }
58
59
    /**
60
     * @throws Exception if value is invalid
61
     */
62
    abstract protected function guard(?DateTimeImmutable $value, string $format): void;
63
}
64