Test Failed
Pull Request — master (#40)
by Alexander
02:24
created

Aliases::__set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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