Completed
Push — master ( d9d319...1b8938 )
by Ben
02:30
created

Computer::asFilesize()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 16
ccs 10
cts 10
cp 1
rs 9.4285
cc 3
eloc 9
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Benrowe\Formatter\Providers;
4
5
use Benrowe\Formatter\AbstractFormatterProvider;
6
7
/**
8
 * @package Benrowe\Formatter
9
 */
10
class Computer extends AbstractFormatterProvider
11
{
12
    private $fileUnits = [
13
        'B', 'kB', 'Mb', 'Gb', 'Tb'
14
    ];
15
16
    /**
17
     * Express the size of a file (as bytes) as a human readable.
18
     * The value is returned as the most appropriate size
19
     *
20
     * @param  int $bytes
21
     * @return string
22
     */
23 12
    public function asFilesize($bytes)
24
    {
25 12
        if ($bytes === null) {
26 1
            return $this->nullValue;
27
        }
28
29 11
        $bytes = (int)$bytes;
30 11
        if ($bytes < 0) {
31 1
            $bytes = 0;
32 1
        }
33
34 11
        $factor = floor(strlen($bytes - 1) / 3);
35 11
        $decimals = 2;
36
37 11
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . $this->fileUnits[$factor];
38
    }
39
}
40