Completed
Pull Request — master (#91)
by Vladimir
02:42
created

FilesystemPath::buildPath()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 14
Ratio 100 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 14
loc 14
ccs 6
cts 6
cp 1
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 0
crap 3
1
<?php
2
3
/**
4
 * @copyright 2018 Vladimir Jimenez
5
 * @license   https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\Filesystem;
9
10
use allejo\stakx\Filesystem\FilesystemLoader as fs;
11
12
/**
13
 * A cross-platform filesystem path wrapper.
14
 *
15
 * This class is a wrapper for handling file paths in stakx in a cross-platform way. Give it a Windows path and append
16
 * a Unix style path and it'll just work.
17
 */
18
final class FilesystemPath
19
{
20
    /** @var string */
21
    private $absolutePath;
22
    /** @var string */
23
    private $originalPath;
24
    /** @var bool */
25
    private $isWindows;
26
27
    /**
28
     * @param FilesystemPath|string $filePath
29
     * @param string                $dirSep
30
     */
31 25
    public function __construct($filePath, $dirSep = DIRECTORY_SEPARATOR)
32
    {
33 25
        $filePath = (string)$filePath;
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $filePath. This often makes code more readable.
Loading history...
34
35 25
        $this->originalPath = $filePath;
36 25
        $this->isWindows = ($dirSep === '\\');
37
38 25
        if ($this->isWindows)
39
        {
40 2
            $filePath = $this->unixifyPath($filePath);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $filePath. This often makes code more readable.
Loading history...
41
        }
42
43 25
        $this->absolutePath = (fs::isAbsolutePath($filePath)) ? $filePath : fs::absolutePath($filePath);
0 ignored issues
show
Bug introduced by
The method isAbsolutePath() does not exist on allejo\stakx\Filesystem\FilesystemLoader. Did you maybe mean absolutePath()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
Documentation introduced by
$filePath is of type string, but the function expects a object<string>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation Bug introduced by
It seems like \allejo\stakx\Filesystem...absolutePath($filePath) can also be of type object<string>. However, the property $absolutePath is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
44 25
    }
45
46 13
    public function __toString()
47
    {
48 13
        return $this->getAbsolutePath();
49
    }
50
51
    /**
52
     * Append a path to a directory path.
53
     *
54
     * @param string $append The path to append
55
     *
56
     * @return self
57
     */
58 6
    public function appendToPath($append)
59
    {
60 6
        if ($this->isFile(false))
61
        {
62 1
            throw new \InvalidArgumentException("Appending to a file's path is not possible");
63
        }
64
65 5
        $this->absolutePath = $this->buildPath($this->absolutePath, $this->unixifyPath($append));
66
67 5
        return $this;
68
    }
69
70
    /**
71
     * Generate a path based off this file path.
72
     *
73
     * This method will not modify the existing file path of this instance, use FilesystemPath::appendToPath() for that.
74
     *
75
     * @param string $append
76
     *
77
     * @return string
78
     */
79 12
    public function generatePath($append)
80
    {
81 12
        return $this->buildPath($this->absolutePath, $this->unixifyPath($append));
82
    }
83
84
    /**
85
     * Get the absolute path of the file path.
86
     *
87
     * @return string
88
     */
89 13
    public function getAbsolutePath()
90
    {
91 13
        if ($this->isWindows)
92
        {
93 2
            return str_replace('/', '\\', $this->absolutePath);
94
        }
95
96 11
        return $this->absolutePath;
97
    }
98
99
    /**
100
     * Check whether the given path is a directory.
101
     *
102
     * @param bool $checkExistence When set to true, it will check the filesystem for the existence of the directory.
103
     *                             When set to false, this function will guess based on the path ending in a directory
104
     *                             separator.
105
     *
106
     * @return bool
107
     */
108 19
    public function isDir($checkExistence = true)
109
    {
110 19
        $absPath = $this->absolutePath;
111
112 19
        if ($checkExistence)
113
        {
114 13
            return file_exists($absPath) && is_dir($absPath);
115
        }
116
117 7
        return substr($absPath, -1, 1) == '/';
118
    }
119
120
    /**
121
     * Check whether the given path is a file.
122
     *
123
     * @param bool $checkExistence When set to true, it will check the filesystem for the existence of the file. When
124
     *                             set to false, this function will guess based on the path ending in a directory
125
     *                             separator.
126
     *
127
     * @return bool
128
     */
129 6
    public function isFile($checkExistence = true)
130
    {
131 6
        $absPath = $this->absolutePath;
132
133 6
        if ($checkExistence)
134
        {
135
            return file_exists($absPath) && is_file($absPath);
136
        }
137
138 6
        return !$this->isDir($checkExistence);
139
    }
140
141
    /**
142
     * Build a path from multiple strings.
143
     *
144
     * This function will _always_ use the '/' as the directory separator, because internal that's all stakx will use.
145
     * The FilesystemPath::getAbsolutePath() function will worry about Windows paths when necessary.
146
     *
147
     * @return string
148
     */
149 17 View Code Duplication
    private function buildPath()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
150
    {
151 17
        $paths = [];
152
153 17
        foreach (func_get_args() as $arg)
154
        {
155 17
            if ($arg !== '')
156
            {
157 17
                $paths[] = $arg;
158
            }
159
        }
160
161 17
        return preg_replace('#(?<!:)/+#', '/', join('/', $paths));
162
    }
163
164
    /**
165
     * Convert a Windows path into a blasphemous Unix path.
166
     *
167
     * @param string $filePath
168
     *
169
     * @return string
170
     */
171 17
    private function unixifyPath($filePath)
172
    {
173 17
        return str_replace('\\', '/', $filePath);
174
    }
175
}
176