Passed
Push — master ( 008e72...5c8957 )
by Tomasz
02:43
created

DateFormatValueObject::getValue()   A

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 Throwable;
11
use TimiTao\ValueObject\Nullable\DateTime\DateFormatValueObject as DateFormatValueObjectInterface;
12
13
abstract class DateFormatValueObject implements DateFormatValueObjectInterface
14
{
15
    private $value;
16
17
    private $format;
18
19
    /**
20
     * @throws Exception if value is invalid
21
     */
22
    public function __construct(?DateTimeImmutable $value, string $format = DateTime::ATOM)
23
    {
24
        try {
25
            $this->guard($value);
26
        } catch (Throwable $e) {
27
            throw $this->throwException($value, $e);
28
        }
29
        $this->value = $value;
30
        $this->format = $format;
31
    }
32
33
    public function getValue(): ?string
34
    {
35
        if ($this->value === null) {
36
            return null;
37
        }
38
        return $this->value->format($this->format);
39
    }
40
41
    public function equals(DateFormatValueObjectInterface $other): bool
42
    {
43
        if (static::class !== get_class($other)) {
44
            return false;
45
        }
46
        if ($this->getValue() === null xor $other->getValue() === null) {
47
            return false;
48
        }
49
        if ($this->getValue() === $other->getValue()) {
50
            return true;
51
        }
52
        /** @var DateTimeImmutable $dateTime */
53
        $dateTime = $this->getDateTime();
54
        /** @var DateTimeImmutable $otherDateTime */
55
        $otherDateTime = $other->getDateTime();
56
        return $dateTime->getTimestamp() === $otherDateTime->getTimestamp();
57
    }
58
59
    public function getDateTime(): ?DateTimeImmutable
60
    {
61
        return $this->value;
62
    }
63
64
    /**
65
     * @throws Throwable if value is invalid
66
     */
67
    abstract protected function guard(?DateTimeImmutable $value): void;
68
69
    abstract protected function throwException(?DateTimeImmutable $value, Throwable $e): Exception;
70
}
71