Passed
Push — master ( f5390f...ff2936 )
by Alexander
02:09
created

Config   A

Complexity

Total Complexity 40

Size/Duplication

Total Lines 262
Duplicated Lines 0 %

Test Coverage

Coverage 81.37%

Importance

Changes 0
Metric Value
wmc 40
eloc 91
c 0
b 0
f 0
dl 0
loc 262
ccs 83
cts 102
cp 0.8137
rs 9.2

22 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A glob() 0 7 2
A clone() 0 7 1
A getValues() 0 3 1
A loadFiles() 0 20 6
A loadFile() 0 5 1
A writeFile() 0 25 5
A envsRequired() 0 3 1
A substitutePath() 0 10 3
A replaceMarkers() 0 6 1
A load() 0 5 1
A paramsRequired() 0 3 1
A substituteOutputDirs() 0 5 1
A substitutePathInString() 0 16 5
A substitutePaths() 0 8 2
A calcValues() 0 5 1
A constantsRequired() 0 3 1
A build() 0 5 1
A write() 0 5 1
A findDepth() 0 6 1
A getBaseDir() 0 3 1
A getOutputPath() 0 3 2

How to fix   Complexity   

Complex Class

Complex classes like Config often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Config, and based on these observations, apply Extract Interface, too.

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