-
Notifications
You must be signed in to change notification settings - Fork 22
/
Unit.php
106 lines (83 loc) · 2.42 KB
/
Unit.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
declare(strict_types=1);
namespace Flow\ETL\Monitoring\Memory;
use Flow\ETL\Exception\InvalidArgumentException;
final class Unit
{
private function __construct(private readonly int $bytes)
{
}
public static function fromBytes(int $bytes) : self
{
return new self($bytes);
}
public static function fromGb(int $gb) : self
{
return new self($gb * 1000 * 1000 * 1000);
}
public static function fromKb(int $kb) : self
{
return new self($kb * 1000);
}
public static function fromMb(int $mb) : self
{
return new self($mb * 1000 * 1000);
}
/**
* @throws InvalidArgumentException
*/
public static function fromString(string $memoryString) : self
{
$limit = \str_replace(' ', '', $memoryString);
$unit = \substr($limit, -1);
switch (\strtoupper($unit)) {
case 'K':
return self::fromKb((int) \substr($limit, 0, -1));
case 'M':
return self::fromMb((int) \substr($limit, 0, -1));
case 'G':
return self::fromGb((int) \substr($limit, 0, -1));
default:
if (\ctype_digit($limit)) {
return self::fromBytes((int) $limit);
}
throw new InvalidArgumentException("Can't extract memory limit in bytes from php ini value: {$limit}");
}
}
public function absolute() : self
{
return new self(\abs($this->bytes));
}
public function diff(self $unit) : self
{
return new self($this->bytes - $unit->bytes);
}
public function inBytes() : int
{
return $this->bytes;
}
public function inGb(int $precision = 2) : float
{
return \round($this->inMb($precision) / 1000, $precision);
}
public function inKb(int $precision = 2) : float
{
return \round($this->bytes / 1000, $precision);
}
public function inMb(int $precision = 2) : float
{
return \round($this->inKb($precision) / 1000, $precision);
}
public function isGreaterThan(self $unit) : bool
{
return $this->bytes > $unit->bytes;
}
public function isLowerThan(self $unit) : bool
{
return $this->bytes < $unit->bytes;
}
public function percentage(int $value) : self
{
return new self((int) \round(($value / 100) * $this->bytes));
}
}