Normalize::diskPath()   B
last analyzed

Complexity

Conditions 7
Paths 6

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 16
nc 6
nop 1
dl 0
loc 29
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
namespace Ffcms\Core\Helper\FileSystem;
4
5
use Ffcms\Core\Helper\Type\Str;
6
7
/**
8
 * Class Normalize. Special system-based class who provide methods to make disk path readable and clean
9
 * @package Ffcms\Core\Helper\FileSystem
10
 */
11
class Normalize
12
{
13
    /**
14
     * Normalize local disk-based path. Ex: ../../dir/./dir/file.txt
15
     * @param string $path
16
     * @return string
17
     */
18
    public static function diskPath($path)
19
    {
20
        // its full-based path? Lets return real path
21
        if (Str::startsWith(root, $path)) {
0 ignored issues
show
Bug introduced by
The constant Ffcms\Core\Helper\FileSystem\root was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
22
            // fix path collisions if is not exist
23
            if (file_exists($path)) {
24
                return realpath($path);
25
            } else {
26
                return $path;
27
            }
28
        }
29
        // else - sounds like relative path
30
        $path = Str::replace('\\', '/', $path);
31
        $splitPath = explode('/', $path);
32
33
        $outputPath = [];
34
        foreach ($splitPath as $index => $part) {
35
            if ($part === '.' || Str::length(trim($part)) < 1) {
36
                continue;
37
            }
38
39
            if ($part === '..') { // level-up (:
40
                array_pop($outputPath);
41
                continue;
42
            }
43
44
            $outputPath[] = trim($part);
45
        }
46
        return implode(DIRECTORY_SEPARATOR, $outputPath);
47
    }
48
49
    /**
50
     * Normalize local disk-based ABSOLUTE path.
51
     * @param string $path
52
     * @return string
53
     */
54
    public static function diskFullPath($path)
55
    {
56
        $path = self::diskPath($path);
57
        if (!Str::startsWith(root, $path)) {
0 ignored issues
show
Bug introduced by
The constant Ffcms\Core\Helper\FileSystem\root was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
58
            $path = root . DIRECTORY_SEPARATOR . ltrim($path, '\\/');
59
        }
60
        return $path;
61
    }
62
}
63