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

Timestamp::createFromString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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