Passed
Pull Request — master (#83)
by Alexander
15:05
created

Builder::buildAllConfigs()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 1
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Composer\Config;
6
7
use JsonException;
8
use Yiisoft\Composer\Config\Config\Config;
9
use Yiisoft\Composer\Config\Config\ConfigFactory;
10
use Yiisoft\Composer\Config\Util\Resolver;
11
12
use function dirname;
13
14
/**
15
 * Builder assembles config files.
16
 */
17
class Builder
18
{
19
    private const OUTPUT_DIR_SUFFIX = '-output';
20
21
    /**
22
     * @var string path to the Composer project root
23
     */
24
    private string $baseDir;
25
26
    /**
27
     * @var string path to output assembled configs
28
     */
29
    private string $outputDir;
30
31
    /**
32
     * @var Config[] configurations
33
     */
34
    private array $configs = [];
35
36
    private ConfigFactory $configFactory;
37
38
    /**
39
     * Builder constructor.
40
     *
41
     * @param ConfigFactory $configFactory
42
     * @param string $baseDir path to the Composer project root
43
     */
44
    public function __construct(ConfigFactory $configFactory, string $baseDir)
45
    {
46
        $this->configFactory = $configFactory;
47
        $this->baseDir = $baseDir;
48
        $this->outputDir = self::findOutputDir($baseDir);
49
    }
50
51
    public function createAlternative($name): Builder
52
    {
53
        $alt = new static($this->configFactory, $this->baseDir);
54
        $alt->setOutputDir($this->outputDir . DIRECTORY_SEPARATOR . $name);
55
        $alt->configs['packages'] = $this->getConfig('packages')->clone($alt);
56
57
        return $alt;
58
    }
59
60
    public function setOutputDir(?string $outputDir): void
61
    {
62
        $this->outputDir = $outputDir
63
            ? static::buildAbsPath($this->getBaseDir(), $outputDir)
64
            : static::findOutputDir($this->getBaseDir());
65
    }
66
67
    public static function rebuild(?string $baseDir = null): void
68
    {
69
        Plugin::buildAllConfigs($baseDir ?? self::findBaseDir());
70
    }
71
72
    /**
73
     * Returns default output dir.
74
     *
75
     * @param string|null $baseDir path to the root Composer package. When `null`,
76
     * @return string
77
     * @throws JsonException
78
     */
79
    private static function findOutputDir(string $baseDir = null): string
80
    {
81 5
        if ($baseDir === null) {
82
            $baseDir = static::findBaseDir();
83 5
        }
84
        $path = $baseDir . DIRECTORY_SEPARATOR . 'composer.json';
85
        $data = @json_decode(file_get_contents($path), true);
86 5
        $dir = $data['extra'][Package::EXTRA_OUTPUT_DIR_OPTION_NAME] ?? null;
87 5
88 5
        return $dir ? static::buildAbsPath($baseDir, $dir) : static::defaultOutputDir($baseDir);
89
    }
90 5
91
    private static function findBaseDir(): string
92
    {
93
        $candidates = [
94
            // normal relative path
95
            dirname(__DIR__, 4),
96
            // console
97
            getcwd(),
98
            // symlinked web
99
            dirname(getcwd())
100
        ];
101
102
        foreach ($candidates as $baseDir) {
103
            if (file_exists($baseDir . DIRECTORY_SEPARATOR . 'composer.json')) {
104
                return $baseDir;
105
            }
106
        }
107
108
        throw new \RuntimeException('Cannot find directory that contains composer.json');
109
    }
110
111
    /**
112
     * Returns default output dir.
113
     *
114
     * @param string $baseDir path to base directory
115
     * @return string
116
     */
117
    private static function defaultOutputDir(string $baseDir = null): string
118
    {
119 5
        if ($baseDir) {
120
            $dir = $baseDir . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'yiisoft' . DIRECTORY_SEPARATOR . basename(dirname(__DIR__));
121 5
        } else {
122 5
            $dir = dirname(__DIR__);
123
        }
124
125
        return $dir . static::OUTPUT_DIR_SUFFIX;
126
    }
127 5
128
    /**
129
     * Returns full path to assembled config file.
130
     *
131
     * @param string $filename name of config
132
     * @param string $baseDir path to base dir
133
     * @return string absolute path
134
     * @throws JsonException
135
     */
136
    public static function path(string $filename, string $baseDir = null): string
137
    {
138 5
        return static::buildAbsPath(static::findOutputDir($baseDir), $filename . '.php');
139
    }
140 5
141
    private static function buildAbsPath(string $dir, string $file): string
142
    {
143 5
        return self::isAbsolutePath($file) ? $file : $dir . DIRECTORY_SEPARATOR . $file;
144
    }
145 5
146
    private static function isAbsolutePath(string $path): bool
147
    {
148 5
        return strpos($path, '/') === 0 || strpos($path, ':') === 1 || strpos($path, '\\\\') === 0;
149
    }
150 5
151
    /**
152
     * Builds all (user and system) configs by given files list.
153
     *
154
     * @param null|array $files files to process: config name => list of files
155
     */
156
    public function buildAllConfigs(array $files): void
157
    {
158
        $this->buildUserConfigs($files);
159
        $this->buildSystemConfigs();
160
    }
161
162
    /**
163
     * Builds configs by given files list.
164
     *
165
     * @param null|array $files files to process: config name => list of files
166
     * @return array
167
     */
168
    private function buildUserConfigs(array $files): array
169
    {
170
        $resolver = new Resolver($files);
171
        $files = $resolver->get();
172
        foreach ($files as $name => $paths) {
173
            $this->getConfig($name)->load($paths)->build()->write();
174
        }
175
176
        return $files;
177
    }
178
179
    private function buildSystemConfigs(): void
180
    {        
181
        $this->getConfig('packages')->build()->write();        
182
    }
183
184
    public function getOutputPath(string $name): string
185
    {
186
        return $this->outputDir . DIRECTORY_SEPARATOR . $name . '.php';
187
    }
188
189
    public function getConfig(string $name)
190
    {
191
        if (!array_key_exists($name, $this->configs)) {
192
            $this->configs[$name] = $this->configFactory->create($this, $name);
193
        }
194
195
        return $this->configs[$name];
196
    }
197
198
    public function getVars(): array
199
    {
200
        $vars = [];
201
        foreach ($this->configs as $name => $config) {
202
            $vars[$name] = $config->getValues();
203
        }
204
205
        return $vars;
206
    }
207
208
    public function setPackage(string $name, array $data): void
209
    {
210
        $this->getConfig('packages')->setValue($name, $data);
211
    }
212
213
    /**
214
     * @return string a full path to the project root
215
     */
216
    public function getBaseDir(): string
217
    {
218
        return $this->baseDir;
219
    }
220
}
221