|
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\MakeEmptyInterface; |
|
13
|
|
|
use Daikon\ValueObject\ValueObjectInterface; |
|
14
|
|
|
|
|
15
|
|
|
final class Sha256 implements MakeEmptyInterface, ValueObjectInterface |
|
16
|
|
|
{ |
|
17
|
|
|
private ?string $hash; |
|
18
|
|
|
|
|
19
|
|
|
public static function generate(): self |
|
20
|
|
|
{ |
|
21
|
|
|
return new self(hash( |
|
22
|
|
|
'sha256', |
|
23
|
|
|
sprintf( |
|
24
|
|
|
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x', |
|
25
|
|
|
mt_rand(0, 0xffff), |
|
26
|
|
|
mt_rand(0, 0xffff), |
|
27
|
|
|
mt_rand(0, 0xffff), |
|
28
|
|
|
mt_rand(0, 0x0fff) | 0x4000, |
|
29
|
|
|
mt_rand(0, 0x3fff) | 0x8000, |
|
30
|
|
|
mt_rand(0, 0xffff), |
|
31
|
|
|
mt_rand(0, 0xffff), |
|
32
|
|
|
mt_rand(0, 0xffff) |
|
33
|
|
|
) |
|
34
|
|
|
)); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** @param null|string $state */ |
|
38
|
|
|
public static function fromNative($state): self |
|
39
|
|
|
{ |
|
40
|
|
|
return new self($state); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public static function makeEmpty(): self |
|
44
|
|
|
{ |
|
45
|
|
|
return new self; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
public function toNative() |
|
49
|
|
|
{ |
|
50
|
|
|
return $this->hash; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** @param self $comparator */ |
|
54
|
|
|
public function equals($comparator): bool |
|
55
|
|
|
{ |
|
56
|
|
|
Assertion::isInstanceOf($comparator, self::class); |
|
57
|
|
|
return $this->toNative() === $comparator->toNative(); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
public function isEmpty(): bool |
|
61
|
|
|
{ |
|
62
|
|
|
return empty($this->hash); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
public function __toString(): string |
|
66
|
|
|
{ |
|
67
|
|
|
return (string)$this->hash; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
private function __construct(?string $hash = null) |
|
71
|
|
|
{ |
|
72
|
|
|
Assertion::nullOrRegex($hash, '/^[a-f0-9]{64}$/', 'Invalid format.'); |
|
73
|
|
|
$this->hash = $hash; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|