Passed
Push — master ( 33e582...680f77 )
by Mr
02:06
created

Date::isEmpty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of the daikon-cqrs/value-object project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Daikon\ValueObject;
10
11
use Daikon\Interop\Assertion;
12
use Daikon\Interop\InvalidArgumentException;
13
use Daikon\Interop\MakeEmptyInterface;
14
use DateTimeImmutable;
15
16
final class Date implements MakeEmptyInterface, ValueObjectInterface
17
{
18
    public const NATIVE_FORMAT = 'Y-m-d';
19
20
    private ?DateTimeImmutable $value;
21
22
    public static function today(): self
23
    {
24
        return new self(new DateTimeImmutable);
25
    }
26
27 12
    public static function fromString(string $value, string $format = self::NATIVE_FORMAT): self
28
    {
29 12
        Assertion::date($value, $format);
30 12
        if (!$date = DateTimeImmutable::createFromFormat($format, $value)) {
31
            throw new InvalidArgumentException('Invalid date string given to '.self::class);
32
        }
33 12
        return new self($date);
34
    }
35
36
    /** @param string|null $value */
37 4
    public static function fromNative($value): self
38
    {
39 4
        Assertion::nullOrString($value, 'Trying to create Date VO from unsupported value type.');
40 4
        return empty($value) ? new self : self::fromString($value);
41
    }
42
43
    public static function makeEmpty(): self
44
    {
45
        return new self;
46
    }
47
48 9
    public function toNative(): ?string
49
    {
50 9
        return is_null($this->value) ? null : $this->value->format(static::NATIVE_FORMAT);
51
    }
52
53
    /** @param self $comparator */
54 5
    public function equals($comparator): bool
55
    {
56 5
        Assertion::isInstanceOf($comparator, self::class);
57 5
        return $this->toNative() === $comparator->toNative();
58
    }
59
60
    public function isEmpty(): bool
61
    {
62
        return $this->value === null;
63
    }
64
65 3
    public function __toString(): string
66
    {
67 3
        return $this->toNative() ?? '';
68
    }
69
70 12
    private function __construct(DateTimeImmutable $value = null)
71
    {
72 12
        $this->value = $value ? $value->setTime(0, 0, 0) : null;
73 12
    }
74
}
75