Passed
Push — master ( 365cfc...8e997c )
by Mr
04:36
created

Hash::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
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 (string)$this->hash;
61
    }
62
63
    private function __construct(string $hash = '')
64
    {
65
        $this->hash = $hash;
66
    }
67
}
68