-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBigHex.php
89 lines (74 loc) · 2.15 KB
/
BigHex.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
namespace Enjin\BlockchainTools;
use InvalidArgumentException;
use phpseclib3\Math\BigInteger;
class BigHex
{
protected $value;
/**
* Hexadecimal constructor.
*
* @param $value string|BigInteger|static
*/
public function __construct($value)
{
if (is_string($value)) {
$value = HexConverter::unPrefix($value);
if (!self::isValidHex($value)) {
throw new InvalidArgumentException("BigHex constructor input is not a valid hexadecimal string: \"{$value}\"");
}
} elseif ($value instanceof self) {
$value = $value->toStringUnPrefixed();
} else {
$value = $this->valueToErrorString($value);
throw new InvalidArgumentException('BigHex constructor input is not valid: ' . $value);
}
$this->value = $value;
}
public function __toString()
{
return $this->toStringUnPrefixed();
}
public static function create(string $value): self
{
return new self($value);
}
public static function isValidHex(string $str): bool
{
return ctype_xdigit($str);
}
public function toBigInt(): BigInteger
{
return new BigInteger($this->value, 16);
}
public function toStringUnPrefixed(): string
{
return $this->value;
}
public function toStringPrefixed(): string
{
return '0x' . $this->value;
}
private function valueToErrorString($value)
{
$normalized = '';
if (is_object($value)) {
$normalized = get_class($value);
} elseif ($value === null) {
$normalized = 'null';
} elseif (is_bool($value)) {
$normalized = $value ? 'true' : 'false';
} elseif (is_array($value)) {
$normalized = 'Array';
} elseif (is_int($value)) {
$normalized = (string) $value;
} elseif (is_float($value)) {
$normalized = (string) $value;
}
$type = gettype($value);
if ($type === 'double') {
$type = 'float';
}
return $normalized . ' (type: ' . $type . ')';
}
}