Passed
Pull Request — master (#2148)
by Arnaud
10:03 queued 04:53
created

AbstractCommand::locateConfigFile()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
nc 3
nop 1
dl 0
loc 16
rs 9.9666
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Command;
15
16
use Cecil\Builder;
17
use Cecil\Config;
18
use Cecil\Exception\ConfigException;
19
use Cecil\Exception\RuntimeException;
20
use Cecil\Logger\ConsoleLogger;
21
use Cecil\Util;
22
use Symfony\Component\Console\Command\Command;
23
use Symfony\Component\Console\Input\InputInterface;
24
use Symfony\Component\Console\Output\OutputInterface;
25
use Symfony\Component\Console\Style\SymfonyStyle;
26
use Symfony\Component\Filesystem\Path;
27
use Symfony\Component\Process\Process;
28
use Symfony\Component\Validator\Constraints\Url;
29
use Symfony\Component\Validator\Validation;
30
use Symfony\Component\Yaml\Exception\ParseException;
31
use Symfony\Component\Yaml\Yaml;
32
33
class AbstractCommand extends Command
34
{
35
    public const CONFIG_FILE = ['cecil.yml', 'config.yml'];
36
    public const TMP_DIR = '.cecil';
37
    public const THEME_CONFIG_FILE = 'config.yml';
38
    public const EXCLUDED_CMD = ['about', 'new:site', 'self-update'];
39
40
    /** @var InputInterface */
41
    protected $input;
42
43
    /** @var OutputInterface */
44
    protected $output;
45
46
    /** @var SymfonyStyle */
47
    protected $io;
48
49
    /** @var null|string */
50
    private $path = null;
51
52
    /** @var array */
53
    private $configFiles = [];
54
55
    /** @var array */
56
    private $config;
57
58
    /** @var Builder */
59
    private $builder;
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    protected function initialize(InputInterface $input, OutputInterface $output)
65
    {
66
        $this->input = $input;
67
        $this->output = $output;
68
        $this->io = new SymfonyStyle($input, $output);
69
70
        // prepare configuration files list
71
        if (!\in_array($this->getName(), self::EXCLUDED_CMD)) {
72
            // site config file
73
            $this->configFiles[$this->locateConfigFile($this->getPath())['name']] = $this->locateConfigFile($this->getPath())['path'];
74
            // additional config file(s) from --config=<file>
75
            if ($input->hasOption('config') && $input->getOption('config') !== null) {
76
                $this->configFiles += $this->locateAdditionalConfigFiles($this->getPath(), (string) $input->getOption('config'));
77
            }
78
            // checks file(s)
79
            $this->configFiles = array_unique($this->configFiles);
80
            foreach ($this->configFiles as $fileName => $filePath) {
81
                if ($filePath === false) {
82
                    unset($this->configFiles[$fileName]);
83
                    $this->io->warning(\sprintf('Could not find configuration file "%s".', $fileName));
84
                }
85
            }
86
        }
87
88
        parent::initialize($input, $output);
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     */
94
    public function run(InputInterface $input, OutputInterface $output): int
95
    {
96
        // disable debug mode if a verbosity level is specified
97
        if ($output->getVerbosity() != OutputInterface::VERBOSITY_NORMAL) {
98
            putenv('CECIL_DEBUG=false');
99
        }
100
        // force verbosity level to "debug" in debug mode
101
        if (getenv('CECIL_DEBUG') == 'true') {
102
            $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
103
        }
104
        if ($output->isDebug()) {
105
            // set env. variable in debug mode
106
            putenv('CECIL_DEBUG=true');
107
108
            return parent::run($input, $output);
109
        }
110
        // run with simplified error message
111
        try {
112
            return parent::run($input, $output);
113
        } catch (\Exception $e) {
114
            if ($this->io === null) {
115
                $this->io = new SymfonyStyle($input, $output);
116
            }
117
            $this->io->error($e->getMessage());
118
119
            exit(1);
120
        }
121
    }
122
123
    /**
124
     * Returns the working path.
125
     */
126
    protected function getPath(bool $exist = true): ?string
127
    {
128
        if ($this->path === null) {
129
            try {
130
                // get working directory by default
131
                if (false === $this->path = getcwd()) {
132
                    throw new \Exception('Can\'t get current working directory.');
133
                }
134
                // ... or path
135
                if ($this->input->getArgument('path') !== null) {
136
                    $this->path = Path::canonicalize($this->input->getArgument('path'));
137
                }
138
                // try to get canonicalized absolute path
139
                if ($exist) {
140
                    if (realpath($this->path) === false) {
141
                        throw new \Exception(\sprintf('The given path "%s" is not valid.', $this->path));
142
                    }
143
                    $this->path = realpath($this->path);
144
                }
145
            } catch (\Exception $e) {
146
                throw new \Exception($e->getMessage());
147
            }
148
        }
149
150
        return $this->path;
151
    }
152
153
    /**
154
     * Returns config file(s) path.
155
     */
156
    protected function getConfigFiles(): array
157
    {
158
        return $this->configFiles ?? [];
159
    }
160
161
    /**
162
     * Creates or returns a Builder instance.
163
     *
164
     * @throws RuntimeException
165
     */
166
    protected function getBuilder(array $config = []): Builder
167
    {
168
        try {
169
            // loads configuration files if not already done
170
            if ($this->config === null) {
171
                // loads and merges configuration files
172
                $configFromFiles = [];
173
                foreach ($this->getConfigFiles() as $fileName => $filePath) {
174
                    if (false === $fileContent = Util\File::fileGetContents($filePath)) {
175
                        throw new RuntimeException(\sprintf('Can\'t read configuration file "%s".', $fileName));
176
                    }
177
                    try {
178
                        $configFromFiles = array_replace_recursive($configFromFiles, (array) Yaml::parse($fileContent, Yaml::PARSE_DATETIME));
179
                    } catch (ParseException $e) {
180
                        throw new RuntimeException(\sprintf('"%s" parsing error: %s', $filePath, $e->getMessage()));
181
                    }
182
                }
183
                // merges configuration from $config parameter
184
                $this->config = array_replace_recursive($configFromFiles, $config);
185
            }
186
            // creates builder instance if not already done
187
            if ($this->builder === null) {
188
                $this->builder = (new Builder($this->config, new ConsoleLogger($this->output)))
189
                    ->setSourceDir($this->getPath())
190
                    ->setDestinationDir($this->getPath());
191
                // import themes config
192
                // @todo Move this to Config class
193
                $themes = (array) $this->builder->getConfig()->getTheme();
194
                foreach ($themes as $theme) {
195
                    $themeConfigFile = Util::joinFile($this->builder->getConfig()->getThemesPath(), $theme, self::THEME_CONFIG_FILE);
196
                    if (Util\File::getFS()->exists($themeConfigFile)) {
197
                        if (false === $themeFileContent = Util\File::fileGetContents($themeConfigFile)) {
198
                            throw new ConfigException(\sprintf('Can\'t read file "themes/%s/%s".', $theme, self::THEME_CONFIG_FILE));
199
                        }
200
                        $themeConfig = Yaml::parse($themeFileContent, Yaml::PARSE_DATETIME);
201
                        $this->builder->getConfig()->import($themeConfig ?? [], Config::PRESERVE);
202
                    }
203
                }
204
            }
205
        } catch (\Exception $e) {
206
            throw new RuntimeException($e->getMessage());
207
        }
208
209
        return $this->builder;
210
    }
211
212
    /**
213
     * Locates the configuration in the given path, as an array of the file name and path, if file exists, otherwise default name and false.
214
     */
215
    protected function locateConfigFile(string $path): array
216
    {
217
        $config = [
218
            'name' => self::CONFIG_FILE[0],
219
            'path' => false,
220
        ];
221
        foreach (self::CONFIG_FILE as $configFileName) {
222
            if (($configFilePath = realpath(Util::joinFile($path, $configFileName))) !== false) {
223
                $config = [
224
                    'name' => $configFileName,
225
                    'path' => $configFilePath,
226
                ];
227
            }
228
        }
229
230
        return $config;
231
    }
232
233
    /**
234
     * Locates additional configuration file(s) from the given list of files, relative to the given path or absolute.
235
     */
236
    protected function locateAdditionalConfigFiles(string $path, string $configFilesList): array
237
    {
238
        foreach (explode(',', $configFilesList) as $filename) {
239
            // absolute path
240
            $config[$filename] = realpath($filename);
241
            // relative path
242
            if (!Util\File::getFS()->isAbsolutePath($filename)) {
243
                $config[$filename] = realpath(Util::joinFile($path, $filename));
244
            }
245
        }
246
247
        return $config;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $config seems to be defined by a foreach iteration on line 238. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
248
    }
249
250
    /**
251
     * Opens path with editor.
252
     *
253
     * @throws RuntimeException
254
     */
255
    protected function openEditor(string $path, string $editor): void
256
    {
257
        $command = \sprintf('%s "%s"', $editor, $path);
258
        switch (Util\Platform::getOS()) {
259
            case Util\Platform::OS_WIN:
260
                $command = \sprintf('start /B "" %s "%s"', $editor, $path);
261
                break;
262
            case Util\Platform::OS_OSX:
263
                // Typora on macOS
264
                if ($editor == 'typora') {
265
                    $command = \sprintf('open -a typora "%s"', $path);
266
                }
267
                break;
268
        }
269
        $process = Process::fromShellCommandline($command);
270
        $process->run();
271
        if (!$process->isSuccessful()) {
272
            throw new RuntimeException(\sprintf('Can\'t use "%s" editor.', $editor));
273
        }
274
    }
275
276
    /**
277
     * Validate URL.
278
     *
279
     * @throws RuntimeException
280
     */
281
    public static function validateUrl(string $url): string
282
    {
283
        $validator = Validation::createValidator();
284
        $violations = $validator->validate($url, new Url());
285
        if (\count($violations) > 0) {
286
            foreach ($violations as $violation) {
287
                throw new RuntimeException($violation->getMessage());
288
            }
289
        }
290
        return rtrim($url, '/') . '/';
291
    }
292
293
    /**
294
     * Returns the "binary name" in the console context.
295
     */
296
    protected function binName(): string
297
    {
298
        return basename($_SERVER['argv'][0]);
299
    }
300
301
    /**
302
     * Override default help message.
303
     *
304
     * @return string
305
     */
306
    public function getProcessedHelp(): string
307
    {
308
        $name = $this->getName();
309
        $placeholders = [
310
            '%command.name%',
311
            '%command.full_name%',
312
        ];
313
        $replacements = [
314
            $name,
315
            $this->binName() . ' ' . $name,
316
        ];
317
318
        return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
319
    }
320
}
321