MonitorTrait::fixPathSlashes()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
/*
3
 * This file is part of Dimsh\React\Filesystem\Monitor;
4
 *
5
 * (c) Abdulrahman Dimashki <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
12
namespace Dimsh\React\Filesystem\Monitor;
13
14
/**
15
 * Trait MonitorTrait
16
 *
17
 * Contains common methods used by MonitorConfigurator and Monitor
18
 *
19
 * @package Dimsh\React\Filesystem\Monitor
20
 */
21
trait MonitorTrait
22
{
23
24
    /**
25
     * Return path with trailing slash.
26
     *
27
     * @param string $path
28
     *
29
     * @return string
30
     */
31
    public function dirPath($path)
32
    {
33
        return rtrim($path, '/') . '/';
34
    }
35
36
    /**
37
     * Directories have trailing slash/
38
     *
39
     * @param string $path
40
     *
41
     * @return bool
42
     */
43
    public function hasTrailingSlash($path)
44
    {
45
        return substr($path, -1) === '/';
46
    }
47
48
    /**
49
     * Fix a Linux path (normalize).
50
     * - replace consecutive '/' with one
51
     * - replace '/./' with '/'
52
     * - replace '/../' at the begining with '/'
53
     * - remove backward pathes '??/../'
54
     *
55
     * @param string $path
56
     *
57
     * @return string
58
     */
59
    public function fixPathSlashes($path)
60
    {
61
        for ($i = 0; $i < 50; $i++) {
62
            $original_path = $path;
63
            $path          = preg_replace('@//+@', '/', $path);
64
            $path          = str_replace('/./', '/', $path);
65
            $path          = preg_replace('@^/\.\.(/|$)@', '/', $path, 1);
66
            $path          = preg_replace('@[^/]+/\.\.(/|$)@', '/', $path, 1);
67
68
            if ($path == $original_path) {
69
                break;
70
            }
71
        }
72
73
        return $path;
74
    }
75
}
76