Computer::asFilesize()   A
last analyzed

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 0
Metric Value
c 0
b 0
f 0
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
 * Provides formatters related to computer related data such as filesizes
9
 *
10
 * @package Benrowe\Formatter
11
 */
12
class Computer extends AbstractFormatterProvider
13
{
14
    private $fileUnits = [
15
        'B', 'kB', 'Mb', 'Gb', 'Tb'
16
    ];
17
18
    /**
19
     * Express the size of a file (as bytes) as a human readable.
20
     * The value is returned as the most appropriate size
21
     *
22
     * @param  int $bytes
23
     * @return string
24
     */
25 12
    public function asFilesize($bytes)
26
    {
27 12
        if ($bytes === null) {
28 1
            return $this->nullValue;
29
        }
30
31 11
        $bytes = (int)$bytes;
32 11
        if ($bytes < 0) {
33 1
            $bytes = 0;
34 1
        }
35
36 11
        $factor = floor(strlen($bytes - 1) / 3);
37 11
        $decimals = 2;
38
39 11
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . $this->fileUnits[$factor];
40
    }
41
}
42