Passed
Push — master ( a25ac3...124ad0 )
by Misha
02:55
created

CommunibaseId::fromValidString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 6
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Communibase;
6
7
use Communibase\Exception\InvalidIdException;
8
9
/**
10
 * Communibase ID
11
 *
12
 * @author Kingsquare ([email protected])
13
 * @copyright Copyright (c) Kingsquare BV (http://www.kingsquare.nl)
14
 */
15
final class CommunibaseId implements \JsonSerializable
16
{
17
    /**
18
     * @var string
19
     */
20
    private $id;
21
22
    private function __construct(string $id = '')
23
    {
24
        $this->id = $id;
25
    }
26
27
    public static function create(): CommunibaseId
28
    {
29
        return new self();
30
    }
31
32
    /**
33
     * @throws InvalidIdException
34
     */
35
    public static function fromString(string $string = null): CommunibaseId
36
    {
37
        if ($string === null) {
38
            $string = '';
39
        }
40
        self::guardAgainstInvalidIdString($string);
41
        return new self($string);
42
    }
43
44
    /**
45
     * Assume the string is valid so we don't need to catch a possible exception.
46
     * CommunibaseId->isEmpty() === true if the string is invalid.
47
     */
48
    public static function fromValidString(string $string = null): CommunibaseId
49
    {
50
        try {
51
            return self::fromString($string);
52
        } catch (InvalidIdException $e) {
53
            return self::create();
54
        }
55
    }
56
57
    public function __toString(): string
58
    {
59
        return $this->id;
60
    }
61
62
    public function toString(): string
63
    {
64
        return $this->__toString();
65
    }
66
67
    public function isEmpty(): bool
68
    {
69
        return $this->id === '';
70
    }
71
72
    public function equals(CommunibaseId $id): bool
73
    {
74
        return $this->toString() === $id->toString();
75
    }
76
77
    /** @noinspection PhpUnhandledExceptionInspection */
78
    public function getCreateDate(): ?\DateTimeImmutable
79
    {
80
        if ($this->isEmpty()) {
81
            return null;
82
        }
83
        $timestamp = intval(substr($this->id, 0, 8), 16);
84
        return new \DateTimeImmutable('@' . $timestamp);
85
    }
86
87
    /**
88
     * @inheritDoc
89
     */
90
    public function jsonSerialize()
91
    {
92
        return $this->id;
93
    }
94
95
    /**
96
     * @throws InvalidIdException
97
     */
98
    private static function guardAgainstInvalidIdString(string $id): void
99
    {
100
        if ($id !== '' && !preg_match('/^[a-f0-9]{24}$/', $id)) {
101
            throw new InvalidIdException('Invalid ID (' . $id . ')');
102
        }
103
    }
104
}
105