Passed
Pull Request — master (#22)
by Dmitriy
37:40 queued 22:25
created

Config::substitutePath()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 16
c 0
b 0
f 0
rs 9.6111
cc 5
nc 12
nop 3
1
<?php
2
3
namespace Yiisoft\Composer\Config\Config;
4
5
use Yiisoft\Composer\Config\Builder;
6
use Yiisoft\Composer\Config\ContentWriter;
7
use Yiisoft\Composer\Config\Reader\ReaderFactory;
8
use Yiisoft\Composer\Config\Util\Helper;
9
10
/**
11
 * Config class represents output configuration file.
12
 */
13
class Config
14
{
15
    private const BASE_DIR_MARKER = '<<<base-dir>>>';
16
17
    /**
18
     * @var string config name
19
     */
20
    private string $name;
21
22
    /**
23
     * @var array sources - paths to config source files
24
     */
25
    private array $sources = [];
26
27
    /**
28
     * @var array config value
29
     */
30
    protected array $values = [];
31
32
    protected Builder $builder;
33
34
    protected ContentWriter $contentWriter;
35
36
    public function __construct(Builder $builder, string $name)
37
    {
38
        $this->builder = $builder;
39
        $this->name = $name;
40
        $this->contentWriter = new ContentWriter();
41
    }
42
43
    public function clone(Builder $builder): self
44
    {
45
        $config = new Config($builder, $this->name);
46
        $config->sources = $this->sources;
47
        $config->values = $this->values;
48
49
        return $config;
50
    }
51
52
    public function getValues(): array
53
    {
54
        return $this->values;
55
    }
56
57
    public function load(array $paths = []): self
58
    {
59
        $this->sources = $this->loadFiles($paths);
60
61
        return $this;
62
    }
63
64
    private function loadFiles(array $paths): array
65
    {
66
        switch (count($paths)) {
67
            case 0:
68
                return [];
69
            case 1:
70
                return [$this->loadFile(reset($paths))];
71
        }
72
73
        $configs = [];
74
        foreach ($paths as $path) {
75
            $cs = $this->loadFiles($this->glob($path));
76
            foreach ($cs as $config) {
77
                if (!empty($config)) {
78
                    $configs[] = $config;
79
                }
80
            }
81
        }
82
83
        return $configs;
84
    }
85
86
    private function glob(string $path): array
87
    {
88
        if (strpos($path, '*') === false) {
89
            return [$path];
90
        }
91
92
        return glob($path);
0 ignored issues
show
Bug Best Practice introduced by
The expression return glob($path) could return the type false which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
93
    }
94
95
    /**
96
     * Reads config file.
97
     *
98
     * @param string $path
99
     * @return array configuration read from file
100
     */
101
    protected function loadFile($path): array
102
    {
103
        $reader = ReaderFactory::get($this->builder, $path);
104
105
        return $reader->read($path);
106
    }
107
108
    /**
109
     * Merges given configs and writes at given name.
110
     *
111
     * @return Config
112
     */
113
    public function build(): self
114
    {
115
        $this->values = $this->calcValues($this->sources);
116
117
        return $this;
118
    }
119
120
    public function write(): self
121
    {
122
        $this->writeFile($this->getOutputPath(), $this->values);
123
124
        return $this;
125
    }
126
127
    protected function calcValues(array $sources): array
128
    {
129
        $values = call_user_func_array([Helper::class, 'mergeConfig'], $sources);
130
        $values = Helper::fixConfig($values);
131
132
        return $this->substituteOutputDirs($values);
133
    }
134
135
    protected function writeFile(string $path, array $data): void
136
    {
137
        $depth = $this->findDepth();
138
        $baseDir = $depth > 0 ? "dirname(__DIR__, $depth)" : '__DIR__';
139
140
        $params = $this->paramsRequired() ? "(array) require __DIR__ . '/params.php'" : '[]';
141
        $constants = $this->constantsRequired() ? $this->builder->getConfig('constants')->buildRequires() : '';
142
        $envs = $this->envsRequired() ? "\$_ENV = array_merge((array) require __DIR__ . '/envs.php', \$_ENV);" : '';
143
        $variables = Helper::exportVar($data);
144
145
        $content = <<<PHP
146
<?php
147
\$baseDir = {$baseDir};
148
\$params = {$params};
149
{$constants}
150
{$envs}
151
return {$variables};
152
PHP;
153
154
        $this->contentWriter->write($path, $this->replaceMarkers($content) . "\n");
155
    }
156
157
    public function envsRequired(): bool
158
    {
159
        return true;
160
    }
161
162
    public function constantsRequired(): bool
163
    {
164
        return true;
165
    }
166
167
    public function paramsRequired(): bool
168
    {
169
        return true;
170
    }
171
172
    private function findDepth(): int
173
    {
174
        $outDir = realpath(dirname($this->normalizePath($this->getOutputPath())));
175
        $diff = substr($outDir, strlen(realpath($this->getBaseDir())));
176
177
        return substr_count($diff, '/');
178
    }
179
180
    private function replaceMarkers(string $content): string
181
    {
182
        return str_replace(
183
            ["'" . self::BASE_DIR_MARKER, "'?" . self::BASE_DIR_MARKER],
184
            ["\$baseDir . '", "'?' . \$baseDir . '"],
185
            $content
186
        );
187
    }
188
189
    /**
190
     * Substitute output paths in given data array recursively with marker.
191
     *
192
     * @param array $data
193
     * @return array
194
     */
195
    protected function substituteOutputDirs(array $data): array
196
    {
197
        $dir = $this->normalizePath($this->getBaseDir());
198
199
        return $this->substitutePaths($data, $dir, self::BASE_DIR_MARKER);
200
    }
201
202
    /**
203
     * Normalizes given path with given directory separator.
204
     * Default forced to Unix directory separator for substitutePaths to work properly in Windows.
205
     *
206
     * @param string $path path to be normalized
207
     * @param string $ds directory separator
208
     * @return string
209
     */
210
    private function normalizePath($path): string
211
    {
212
        return rtrim(strtr($path, '/\\', '//'), '/');
213
    }
214
215
    /**
216
     * Substitute all paths in given array recursively with alias if applicable.
217
     *
218
     * @param array $data
219
     * @param string $dir
220
     * @param string $alias
221
     * @return array
222
     */
223
    private function substitutePaths($data, $dir, $alias): array
224
    {
225
        foreach ($data as &$value) {
226
            if (is_string($value)) {
227
                $value = $this->substitutePath($value, $dir, $alias);
228
            } elseif (is_array($value)) {
229
                $value = $this->substitutePaths($value, $dir, $alias);
230
            }
231
        }
232
233
        return $data;
234
    }
235
236
    /**
237
     * Substitute path with alias if applicable.
238
     *
239
     * @param string $path
240
     * @param string $dir
241
     * @param string $alias
242
     * @return string
243
     */
244
    private function substitutePath($path, $dir, $alias): string
245
    {
246
        $end = $dir . '/';
247
        $skippable = 0 === strncmp($path, '?', 1);
248
        if ($skippable) {
249
            $path = substr($path, 1);
250
        }
251
        if ($path === $dir) {
252
            $result = $alias;
253
        } elseif (strpos($path, $end) === 0) {
254
            $result = $alias . substr($path, strlen($end) - 1);
255
        } else {
256
            $result = $path;
257
        }
258
259
        return ($skippable ? '?' : '') . $result;
260
    }
261
262
    private function getBaseDir(): string
263
    {
264
        return $this->builder->getBaseDir();
265
    }
266
267
    protected function getOutputPath(string $name = null): string
268
    {
269
        return $this->builder->getOutputPath($name ?: $this->name);
270
    }
271
}
272