Aliases   A
last analyzed

Complexity

Total Complexity 32

Size/Duplication

Total Lines 215
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 32
eloc 62
c 6
b 0
f 0
dl 0
loc 215
ccs 67
cts 67
cp 1
rs 9.84

8 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 18 4
A remove() 0 13 6
A isAlias() 0 3 1
B findAlias() 0 18 7
A getAll() 0 14 4
A __construct() 0 4 2
A getArray() 0 5 1
B set() 0 28 7
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
13
final class Aliases
14
{
15
    /**
16
     * @var array
17
     * @psalm-var array<string, string|array<string, string>>
18
     */
19
    private array $aliases = [];
20
21
    /**
22
     * @psalm-param array<string, string> $config
23
     *
24
     * @throws InvalidArgumentException if $path is an invalid alias.
25
     *
26
     * @see set()
27
     * @see get()
28
     */
29 18
    public function __construct(array $config = [])
30
    {
31 18
        foreach ($config as $alias => $path) {
32 11
            $this->set($alias, $path);
33
        }
34
    }
35
36
    /**
37
     * Registers a path alias.
38
     *
39
     * A path alias is a short name representing a long path (a file path, a URL, etc.)
40
     *
41
     * For example, `@vendor` may store path to `vendor` directory.
42
     *
43
     * A path alias must start with the character '@' so that it can be easily differentiated
44
     * from non-alias paths.
45
     *
46
     * Note that this method does not check if the given path exists or not. All it does is
47
     * to associate the alias with the path.
48
     *
49
     * Any trailing '/' and '\' characters in the given path will be trimmed.
50
     *
51
     * @param string $alias the alias name (e.g. "@vendor"). It must start with a '@' character.
52
     * It may contain the forward slash '/' which serves as boundary character when performing
53
     * alias translation by {@see get()}.
54
     * @param string $path the path corresponding to the alias.
55
     * Trailing '/' and '\' characters will be trimmed. This can be
56
     *
57
     * - a directory or a file path (e.g. `/tmp`, `/tmp/main.txt`)
58
     * - a URL (e.g. `https://www.yiiframework.com`)
59
     * - a path alias (e.g. `@vendor/yiisoft`). It will be resolved on {@see get()} call.
60
     *
61
     * @see get()
62
     */
63 15
    public function set(string $alias, string $path): void
64
    {
65 15
        if (!$this->isAlias($alias)) {
66 1
            $alias = '@' . $alias;
67
        }
68 15
        $pos = strpos($alias, '/');
69
        /** @psalm-var string $root */
70 15
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
71
72 15
        $path = rtrim($path, '\\/');
73 15
        if (!array_key_exists($root, $this->aliases)) {
74 15
            if ($pos === false) {
75 14
                $this->aliases[$root] = $path;
76
            } else {
77 15
                $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 16
    public function get(string $alias): string
148
    {
149 16
        if (!$this->isAlias($alias)) {
150 6
            return $alias;
151
        }
152
153 14
        $foundAlias = $this->findAlias($alias);
154
155 14
        if ($foundAlias === null) {
156 2
            throw new InvalidArgumentException("Invalid path alias: $alias");
157
        }
158
159 12
        $foundSubAlias = $this->findAlias($foundAlias);
160 12
        if ($foundSubAlias === null) {
161 11
            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 14
    private function findAlias(string $alias): ?string
206
    {
207 14
        $pos = strpos($alias, '/');
208 14
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
209
210 14
        if (array_key_exists($root, $this->aliases)) {
211 12
            if (is_string($this->aliases[$root])) {
212 9
                return $pos === false ? $this->aliases[$root] : $this->aliases[$root] . substr($alias, $pos);
213
            }
214
215 3
            foreach ($this->aliases[$root] as $name => $path) {
216 3
                if (strpos($alias . '/', $name . '/') === 0) {
217 3
                    return $path . substr($alias, strlen($name));
218
                }
219
            }
220
        }
221
222 13
        return null;
223
    }
224
225 17
    private function isAlias(string $alias): bool
226
    {
227 17
        return !strncmp($alias, '@', 1);
228
    }
229
}
230