Passed
Push — master ( 2b5d19...008e72 )
by Tomasz
01:35
created

DateFormatValueObject::getValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TimiTao\ValueObject\Beberlei\DateTime;
6
7
use DateTime;
8
use DateTimeImmutable;
9
use Exception;
10
use Throwable;
11
use TimiTao\ValueObject\Core\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
        return $this->value->format($this->format);
36
    }
37
38
    public function equals(DateFormatValueObjectInterface $other): bool
39
    {
40
        if (static::class !== get_class($other)) {
41
            return false;
42
        }
43
        return $this->getDateTime()->getTimestamp() === $other->getDateTime()->getTimestamp();
44
    }
45
46
    public function getDateTime(): DateTimeImmutable
47
    {
48
        return $this->value;
49
    }
50
51
    /**
52
     * @throws Throwable if value is invalid
53
     */
54
    abstract protected function guard(DateTimeImmutable $value): void;
55
56
    abstract protected function throwException(DateTimeImmutable $value, Throwable $e): Exception;
57
}
58