|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the ngutech/bitcoin-interop 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 NGUtech\Bitcoin\ValueObject; |
|
10
|
|
|
|
|
11
|
|
|
use Daikon\Interop\Assertion; |
|
12
|
|
|
use Daikon\Interop\MakeEmptyInterface; |
|
13
|
|
|
use Daikon\ValueObject\ValueObjectInterface; |
|
14
|
|
|
|
|
15
|
|
|
final class Hash implements MakeEmptyInterface, ValueObjectInterface |
|
16
|
|
|
{ |
|
17
|
|
|
private string $hash; |
|
18
|
|
|
|
|
19
|
|
|
public static function sum(string $value): self |
|
20
|
|
|
{ |
|
21
|
|
|
return new self(hash('sha256', $value)); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** @param null|string $value */ |
|
25
|
|
|
public static function fromNative($value): self |
|
26
|
|
|
{ |
|
27
|
|
|
Assertion::nullOrRegex($value, '/^$|[a-f0-9]{64}/i', 'Must be 64 hex characters.'); |
|
28
|
|
|
return empty($value) ? new self : new self($value); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public static function makeEmpty(): self |
|
32
|
|
|
{ |
|
33
|
|
|
return new self; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public function isEmpty(): bool |
|
37
|
|
|
{ |
|
38
|
|
|
return empty($this->hash); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** @param self $comparator */ |
|
42
|
|
|
public function equals($comparator): bool |
|
43
|
|
|
{ |
|
44
|
|
|
Assertion::isInstanceOf($comparator, self::class); |
|
45
|
|
|
return $this->toNative() === $comparator->toNative(); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
public function toBinary(): string |
|
49
|
|
|
{ |
|
50
|
|
|
return hex2bin($this->hash); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
public function toNative(): string |
|
54
|
|
|
{ |
|
55
|
|
|
return $this->hash; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function __toString(): string |
|
59
|
|
|
{ |
|
60
|
|
|
return $this->hash; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
private function __construct(string $hash = '') |
|
64
|
|
|
{ |
|
65
|
|
|
$this->hash = $hash; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|