Completed
Push — master ( 1f3ae1...7a77f2 )
by Nikola
02:24
created

Filesize::getBytes()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 4
Bugs 0 Features 2
Metric Value
c 4
b 0
f 2
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.4286
cc 3
eloc 9
nc 3
nop 1
crap 3
1
<?php
2
/*
3
 * This file is part of the Backup package, an RunOpenCode project.
4
 *
5
 * (c) 2015 RunOpenCode
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * This project is fork of "kbond/php-backup", for full credits info, please
11
 * view CREDITS file that was distributed with this source code.
12
 */
13
namespace RunOpenCode\Backup\Utils;
14
15
/**
16
 * Class Filesize
17
 *
18
 * File size utilities
19
 *
20
 * @package RunOpenCode\Backup\Utils
21
 */
22
final class Filesize
23
{
24
    private function __construct() {}
25
26
    private static $units = array(
27
        't' => 8796093022208,
28
        'tb' => 8796093022208,
29
        'g' => 8589934592,
30
        'gb' => 8589934592,
31
        'm' => 8388608,
32
        'mb' => 8388608
33
    );
34
35
    /**
36
     * Get bytes from formatted string size.
37
     *
38
     * E.g:
39
     *
40
     * 1m, 1mb => megabytes
41
     * 1g, 1gb => gigabytes
42
     * 1t, 1tb => terabytes
43
     *
44
     * Note: size format is case insensitive.
45
     *
46
     * @param $size
47
     * @return int
48
     */
49 12
    public static function getBytes($size)
50
    {
51 12
        if (is_numeric($size)) {
52 10
            return intval($size);
53
        }
54
55 4
        $size = strtolower(trim($size));
56
57 4
        $numeric = preg_replace('/[^0-9]/', '', $size);
58 4
        $unit = str_replace($numeric, '', $size);
59
60 4
        if (isset(self::$units[$unit])) {
61 2
            return $numeric * self::$units[$unit];
62
        }
63
64 2
        throw new \InvalidArgumentException(sprintf('Unknown size format: "%s"', $size));
65
    }
66
}
67