LocalFilesystem::fileSizeBytes()   B
last analyzed

Complexity

Conditions 9
Paths 13

Size

Total Lines 44
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 17.9579

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 24
c 1
b 0
f 0
nc 13
nop 1
dl 0
loc 44
ccs 13
cts 25
cp 0.52
crap 17.9579
rs 8.0555
1
<?php
2
3
namespace ThinKit\Helpers;
4
5
class LocalFilesystem
6
{
7 1
    public static function fileSizeBytes($dir): int
8
    {
9
        // Normalise
10 1
        $dir = rtrim(str_replace('\\', '/', $dir), '/');
11
12 1
        if (is_dir($dir) === true) {
13 1
            $totalSize = 0;
14 1
            $os        = strtoupper(substr(PHP_OS, 0, 3));
15
            // If on a Unix Host (Linux, Mac OS)
16 1
            if ($os !== 'WIN') {
17 1
                $io = popen('/usr/bin/du -sb ' . $dir, 'r');
18 1
                if ($io !== false) {
19 1
                    $totalSize = intval(fgets($io, 80));
20 1
                    pclose($io);
21
22 1
                    return (int)$totalSize;
23
                }
24
            }
25
            // If on a Windows Host (WIN32, WINNT, Windows)
26
            if ($os === 'WIN' && extension_loaded('com_dotnet')) {
27
                $obj = new \COM('scripting.filesystemobject');
28
                if (is_object($obj)) {
29
                    $ref       = $obj->getfolder($dir);
30
                    $totalSize = $ref->size;
31
                    $obj       = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $obj is dead and can be removed.
Loading history...
32
33
                    return (int)$totalSize;
34
                }
35
            }
36
37
            // If System calls did't work, use slower PHP approach
38
            $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir));
39
            foreach ($files as $file) {
40
                $totalSize += $file->getSize();
41
            }
42
43
            return $totalSize;
44
        }
45
46 1
        if (is_file($dir) === true) {
47 1
            return (int) filesize($dir);
48
        }
49
50
        return 0;
51
    }
52
}
53