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