Passed
Push — master ( 819f30...8ceff2 )
by Thorsten
02:22
created

Date::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Daikon\Entity\ValueObject;
4
5
use Daikon\Entity\Assert\Assertion;
6
use DateTimeImmutable;
7
8
final class Date implements ValueObjectInterface
9
{
10
    /**
11
     * @var string
12
     */
13
    public const NATIVE_FORMAT = "Y-m-d";
14
15
    /**
16
     * @var null
17
     */
18
    private const NIL = null;
19
20
    /**
21
     * @var DateTimeImmutable|null
22
     */
23
    private $value;
24
25
    public static function today(): self
26
    {
27
        return new static(new DateTimeImmutable);
28
    }
29
30 16
    public static function createFromString(string $value, string $format = self::NATIVE_FORMAT): self
31
    {
32 16
        Assertion::date($value, $format);
33 16
        return new self(DateTimeImmutable::createFromFormat($format, $value));
34
    }
35
36
    /**
37
     * @param string|null $nativeValue
38
     * @return self
39
     */
40 16
    public static function fromNative($nativeValue): self
41
    {
42 16
        Assertion::nullOrString($nativeValue);
43 16
        return empty($nativeValue) ? new self : self::createFromString($nativeValue);
44
    }
45
46 4
    public function toNative(): ?string
47
    {
48 4
        return $this->value === self::NIL ? self::NIL : $this->value->format(self::NATIVE_FORMAT);
49
    }
50
51 1
    public function equals(ValueObjectInterface $otherValue): bool
52
    {
53 1
        return $otherValue instanceof self && $this->toNative() === $otherValue->toNative();
54
    }
55
56 1
    public function __toString(): string
57
    {
58 1
        return $this->toNative() ?? '';
59
    }
60
61 16
    private function __construct(DateTimeImmutable $value = self::NIL)
62
    {
63 16
        $this->value = $value ? $value->setTime(0, 0, 0) : $value;
64 16
    }
65
}
66