Passed
Pull Request — master (#69)
by Sergei
13:12
created

Aliases::joinPathAndSubpath()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 2
nop 2
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Aliases;
6
7
use InvalidArgumentException;
8
9
use function array_key_exists;
10
use function is_array;
11
use function is_string;
12
use function strlen;
13
14
final class Aliases
15
{
16
    /**
17
     * @var array
18
     * @psalm-var array<string, string|array<string, string>>
19
     */
20
    private array $aliases = [];
21
22
    /**
23
     * @psalm-param array<string, string> $config
24
     *
25
     * @throws InvalidArgumentException if $path is an invalid alias.
26
     *
27
     * @see set()
28
     * @see get()
29
     */
30 36
    public function __construct(array $config = [])
31
    {
32 36
        foreach ($config as $alias => $path) {
33 29
            $this->set($alias, $path);
34
        }
35
    }
36
37
    /**
38
     * Registers a path alias.
39
     *
40
     * A path alias is a short name representing a long path (a file path, a URL, etc.)
41
     *
42
     * For example, `@vendor` may store path to `vendor` directory.
43
     *
44
     * A path alias must start with the character '@' so that it can be easily differentiated
45
     * from non-alias paths.
46
     *
47
     * Note that this method does not check if the given path exists or not. All it does is
48
     * to associate the alias with the path.
49
     *
50
     * Any trailing '/' and '\' characters in the given path will be trimmed.
51
     *
52
     * @param string $alias the alias name (e.g. "@vendor"). It must start with a '@' character.
53
     * It may contain the forward slash '/' which serves as boundary character when performing
54
     * alias translation by {@see get()}.
55
     * @param string $path the path corresponding to the alias.
56
     * Trailing '/' and '\' characters will be trimmed. This can be
57
     *
58
     * - a directory or a file path (e.g. `/tmp`, `/tmp/main.txt`)
59
     * - a URL (e.g. `http://www.yiiframework.com`)
60
     * - a path alias (e.g. `@vendor/yiisoft`). It will be resolved on {@see get()} call.
61
     *
62
     * @see get()
63
     */
64 33
    public function set(string $alias, string $path): void
65
    {
66 33
        if (!$this->isAlias($alias)) {
67 1
            $alias = '@' . $alias;
68
        }
69 33
        $pos = strpos($alias, '/');
70
        /** @psalm-var string $root */
71 33
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
72
73 33
        if (!array_key_exists($root, $this->aliases)) {
74 33
            if ($pos === false) {
75 32
                $this->aliases[$root] = $path;
76
            } else {
77 33
                $this->aliases[$root] = [$alias => $path];
78
            }
79 4
        } elseif (is_string($this->aliases[$root])) {
80 4
            if ($pos === false) {
81 1
                $this->aliases[$root] = $path;
82
            } else {
83 4
                $this->aliases[$root] = [
84 4
                    $alias => $path,
85 4
                    $root => $this->aliases[$root],
86 4
                ];
87
            }
88
        } else {
89 2
            $this->aliases[$root][$alias] = $path;
90 2
            krsort($this->aliases[$root]);
91
        }
92
    }
93
94
    /**
95
     * Remove alias.
96
     *
97
     * @param string $alias Alias to be removed.
98
     */
99 2
    public function remove(string $alias): void
100
    {
101 2
        if (!$this->isAlias($alias)) {
102 1
            $alias = '@' . $alias;
103
        }
104 2
        $pos = strpos($alias, '/');
105 2
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
106
107 2
        if (array_key_exists($root, $this->aliases)) {
108 2
            if (is_array($this->aliases[$root])) {
109 1
                unset($this->aliases[$root][$alias]);
110 1
            } elseif ($pos === false) {
111 1
                unset($this->aliases[$root]);
112
            }
113
        }
114
    }
115
116
    /**
117
     * Translates a path alias into an actual path.
118
     *
119
     * The translation is done according to the following procedure:
120
     *
121
     * 1. If the given alias does not start with '@', it is returned back without change;
122
     * 2. Otherwise, look for the longest registered alias that matches the beginning part
123
     *    of the given alias. If it exists, replace the matching part of the given alias with
124
     *    the corresponding registered path.
125
     * 3. Throw an exception if path alias cannot be resolved.
126
     *
127
     * For example, if '@vendor' is registered as the alias to the vendor directory,
128
     * say '/path/to/vendor'. The alias '@vendor/yiisoft' would then be translated into '/path/to/vendor/yiisoft'.
129
     *
130
     * If you have registered two aliases '@foo' and '@foo/bar'. Then translating '@foo/bar/config'
131
     * would replace the part '@foo/bar' (instead of '@foo') with the corresponding registered path.
132
     * This is because the longest alias takes precedence.
133
     *
134
     * However, if the alias to be translated is '@foo/barbar/config', then '@foo' will be replaced
135
     * instead of '@foo/bar', because '/' serves as the boundary character.
136
     *
137
     * Note, this method does not check if the returned path exists or not.
138
     *
139
     * @param string $alias The alias to be translated.
140
     *
141
     * @throws InvalidArgumentException If the root alias is not previously registered.
142
     *
143
     * @return string The path corresponding to the alias.
144
     *
145
     * @see setAlias()
146
     */
147 34
    public function get(string $alias): string
148
    {
149 34
        if (!$this->isAlias($alias)) {
150 6
            return $alias;
151
        }
152
153 32
        $foundAlias = $this->findAlias($alias);
154
155 32
        if ($foundAlias === null) {
156 2
            throw new InvalidArgumentException("Invalid path alias: $alias");
157
        }
158
159 30
        $foundSubAlias = $this->findAlias($foundAlias);
160 30
        if ($foundSubAlias === null) {
161 29
            return $foundAlias;
162
        }
163
164 3
        return $this->get($foundSubAlias);
165
    }
166
167
    /**
168
     * Bulk translates path aliases into actual paths.
169
     *
170
     * @param string[] $aliases Aliases to be translated.
171
     *
172
     * @throws InvalidArgumentException If the root alias was not previously registered.
173
     *
174
     * @return string[] The paths corresponding to the aliases.
175
     */
176 2
    public function getArray(array $aliases): array
177
    {
178 2
        return array_map(
179 2
            fn (string $alias) => $this->get($alias),
180 2
            $aliases,
181 2
        );
182
    }
183
184
    /**
185
     * Returns all path aliases translated into an actual paths.
186
     *
187
     * @return array Actual paths indexed by alias name.
188
     */
189 3
    public function getAll(): array
190
    {
191 3
        $result = [];
192 3
        foreach ($this->aliases as $name => $path) {
193 2
            if (is_array($path)) {
194 1
                foreach ($path as $innerName => $innerPath) {
195 1
                    $result[$innerName] = $innerPath;
196
                }
197
            } else {
198 2
                $result[$name] = $this->get($path);
199
            }
200
        }
201
202 3
        return $result;
203
    }
204
205 32
    private function findAlias(string $alias): ?string
206
    {
207 32
        $pos = strpos($alias, '/');
208 32
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
209
210 32
        if (array_key_exists($root, $this->aliases)) {
211 30
            if (is_string($this->aliases[$root])) {
212 27
                return $pos === false
213 10
                    ? $this->aliases[$root]
214 27
                    : $this->joinPathAndSubpath($this->aliases[$root], substr($alias, $pos));
215
            }
216
217 3
            foreach ($this->aliases[$root] as $name => $path) {
218 3
                if (strpos($alias . '/', $name . '/') === 0) {
219 3
                    return $this->joinPathAndSubpath($path, substr($alias, strlen($name)));
220
                }
221
            }
222
        }
223
224 31
        return null;
225
    }
226
227 22
    private function joinPathAndSubpath(string $path, string $subpath): string
228
    {
229 22
        if ($path === '/' || $path === '\\') {
230 2
            $subpath = ltrim($subpath, '\\/');
231
        } else {
232 20
            $path = rtrim($path, '\\/');
233
        }
234 22
        return $path . $subpath;
235
    }
236
237 35
    private function isAlias(string $alias): bool
238
    {
239 35
        return !strncmp($alias, '@', 1);
240
    }
241
}
242