Passed
Push — configuration ( efba55...1fb2fd )
by Arnaud
15:16 queued 10:46
created

AbstractCommand::locateAdditionalConfigFiles()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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