BytesToHumanTrait   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 3
lcom 0
cbo 0
dl 0
loc 31
c 0
b 0
f 0
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A bytesToHuman() 0 19 3
1
<?php
2
3
/**
4
 * Tack Tracker - A library for tracking long-running task progress
5
 *
6
 * @license http://opensource.org/licenses/MIT
7
 * @link https://github.com/caseyamcl/tasktracker
8
 * @version 2.0
9
 * @package caseyamcl/tasktracker
10
 * @author Casey McLaughlin <[email protected]>
11
 *
12
 * For the full copyright and license information, please view the LICENSE
13
 * file that was distributed with this source code.
14
 *
15
 * ------------------------------------------------------------------
16
 */
17
18
namespace TaskTracker\Helper;
19
20
/**
21
 * Trait for converting bytes into a human-readable format
22
 *
23
 * @author Casey McLaughlin <[email protected]>
24
 */
25
trait BytesToHumanTrait
26
{
27
    /**
28
     * Convert bytes to a human-readable format
29
     *
30
     * For example (int) 1024 becomes (string) "1.02KB"
31
     *
32
     * @param int $bytes
33
     * @param int $decimals
34
     * @return string
35
     */
36
    protected function bytesToHuman($bytes, $decimals = 2)
37
    {
38
        $map = [
39
            1000000000000 => 'TB',
40
            1000000000    => 'GB',
41
            1000000       => 'MB',
42
            1000          => 'KB',
43
            1             => 'B'
44
        ];
45
46
        foreach ($map as $val => $suffix) {
47
            if ($bytes >= $val) {
48
                return number_format($bytes / $val, $decimals) . $suffix;
49
            }
50
        }
51
52
        // Will make it here only if $bytes is < 1
53
        return number_format($bytes, $decimals) . 'B';
54
    }
55
}
56