ParsesNumValues::toBytes()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 0
loc 20
ccs 0
cts 12
cp 0
crap 20
rs 9.6
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Longman\LaravelLodash\SelfDiagnosis;
6
7
use function floor;
8
use function pow;
9
use function sprintf;
10
use function strlen;
11
use function strtolower;
12
use function trim;
13
14
trait ParsesNumValues
15
{
16
    private function toBytes(string $value): int
17
    {
18
        $value = trim($value);
19
        $last = strtolower($value[strlen($value) - 1]);
20
21
        $value = (int) $value;
22
        switch ($last) {
23
            case 'g':
24
                $value *= 1024;
25
            // no break
26
            case 'm':
27
                $value *= 1024;
28
            // no break
29
            case 'k':
30
                $value *= 1024;
31
            // no break
32
        }
33
34
        return $value;
35
    }
36
37
    private function fromBytes(int $bytes, int $decimals = 2): string
38
    {
39
        $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
40
        $factor = (int) floor((strlen((string) $bytes) - 1) / 3);
41
42
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . $size[$factor];
43
    }
44
}
45