Size   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 55
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A bytesToFormat() 0 4 2
A formatToBytes() 0 5 2
1
<?php
2
3
namespace Hyperized\Benchmark\Generic;
4
5
6
/**
7
 * Class Size
8
 * @package Hyperized\Benchmark\Generic
9
 */
10
class Size
11
{
12
    /**
13
     * @var array
14
     */
15
    private static $units = [
16
        'B',
17
        'KB',
18
        'MB',
19
        'GB',
20
        'TB',
21
        'PB',
22
        'EB',
23
        'ZB',
24
        'YB'
25
    ];
26
27
    /**
28
     * @var string
29
     */
30
    private static $unitsPattern = 'bkmgtpezy';
31
    /**
32
     * @var string
33
     */
34
    private static $unitsRegexPattern = '/[^bkmgtpezy]/i';
35
    /**
36
     * @var string
37
     */
38
    private static $numberRegex = '/[^0-9\.]/';
39
40
    /**
41
     * @param int $bytes
42
     *
43
     * @return string
44
     *
45
     * https://stackoverflow.com/a/11860664/1757763
46
     */
47
    public static function bytesToFormat(int $bytes): string
48
    {
49
        $power = $bytes > 0 ? \floor(\log($bytes, 1024)) : 0;
50
        return \number_format($bytes / (1024 ** $power), 2, '.', ',') . ' ' . self::$units[$power];
51
    }
52
53
    /**
54
     * @param string $format
55
     *
56
     * @return float
57
     *
58
     * https://stackoverflow.com/a/25370978/1757763
59
     */
60
    public static function formatToBytes(string $format): float
61
    {
62
        $unit = \preg_replace(self::$unitsRegexPattern, '', $format);
63
        $format = \preg_replace(self::$numberRegex, '', $format);
64
        return $unit ? \round($format * (1024 ** \stripos(self::$unitsPattern, $unit[0]))) : \round($format);
0 ignored issues
show
Bug introduced by
$format of type string is incompatible with the type double expected by parameter $val of round(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

64
        return $unit ? \round($format * (1024 ** \stripos(self::$unitsPattern, $unit[0]))) : \round(/** @scrutinizer ignore-type */ $format);
Loading history...
65
    }
66
}