Passed
Pull Request — master (#2148)
by Arnaud
13:00 queued 05:53
created

AbstractCommand::locateConfigFile()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 2
b 0
f 0
nc 3
nop 1
dl 0
loc 16
rs 9.9666
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 simplified 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
            $this->io->error($e->getMessage());
114
115
            exit(1);
116
        }
117
    }
118
119
    /**
120
     * Returns the working path.
121
     */
122
    protected function getPath(bool $exist = true): ?string
123
    {
124
        if ($this->path === null) {
125
            try {
126
                // get working directory by default
127
                if (false === $this->path = getcwd()) {
128
                    throw new \Exception('Can\'t get current working directory.');
129
                }
130
                // ... or path
131
                if ($this->input->getArgument('path') !== null) {
132
                    $this->path = Path::canonicalize($this->input->getArgument('path'));
133
                }
134
                // try to get canonicalized absolute path
135
                if ($exist) {
136
                    if (realpath($this->path) === false) {
137
                        throw new \Exception(\sprintf('The given path "%s" is not valid.', $this->path));
138
                    }
139
                    $this->path = realpath($this->path);
140
                }
141
            } catch (\Exception $e) {
142
                throw new \Exception($e->getMessage());
143
            }
144
        }
145
146
        return $this->path;
147
    }
148
149
    /**
150
     * Returns config file(s) path.
151
     */
152
    protected function getConfigFiles(): array
153
    {
154
        return $this->configFiles ?? [];
155
    }
156
157
    /**
158
     * Creates or returns a Builder instance.
159
     *
160
     * @throws RuntimeException
161
     */
162
    protected function getBuilder(array $config = []): Builder
163
    {
164
        try {
165
            // loads configuration files if not already done
166
            if ($this->config === null) {
167
                $this->config = new Config();
168
                // loads and merges configuration files
169
                foreach ($this->getConfigFiles() as $filePath) {
170
                    $this->config->import($this->config::loadFile($filePath), Config::MERGE);
171
                }
172
                // merges configuration from $config parameter
173
                $this->config->import($config, Config::MERGE);
174
            }
175
            // creates builder instance if not already done
176
            if ($this->builder === null) {
177
                $this->builder = (new Builder($this->config, new ConsoleLogger($this->output)))
178
                    ->setSourceDir($this->getPath())
179
                    ->setDestinationDir($this->getPath());
180
            }
181
        } catch (\Exception $e) {
182
            throw new RuntimeException($e->getMessage());
183
        }
184
185
        return $this->builder;
186
    }
187
188
    /**
189
     * Locates the configuration in the given path, as an array of the file name and path, if file exists, otherwise default name and false.
190
     */
191
    protected function locateConfigFile(string $path): array
192
    {
193
        $config = [
194
            'name' => self::CONFIG_FILE[0],
195
            'path' => false,
196
        ];
197
        foreach (self::CONFIG_FILE as $configFileName) {
198
            if (($configFilePath = realpath(Util::joinFile($path, $configFileName))) !== false) {
199
                $config = [
200
                    'name' => $configFileName,
201
                    'path' => $configFilePath,
202
                ];
203
            }
204
        }
205
206
        return $config;
207
    }
208
209
    /**
210
     * Locates additional configuration file(s) from the given list of files, relative to the given path or absolute.
211
     */
212
    protected function locateAdditionalConfigFiles(string $path, string $configFilesList): array
213
    {
214
        foreach (explode(',', $configFilesList) as $filename) {
215
            // absolute path
216
            $config[$filename] = realpath($filename);
217
            // relative path
218
            if (!Util\File::getFS()->isAbsolutePath($filename)) {
219
                $config[$filename] = realpath(Util::joinFile($path, $filename));
220
            }
221
        }
222
223
        return $config;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $config seems to be defined by a foreach iteration on line 214. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
224
    }
225
226
    /**
227
     * Opens path with editor.
228
     *
229
     * @throws RuntimeException
230
     */
231
    protected function openEditor(string $path, string $editor): void
232
    {
233
        $command = \sprintf('%s "%s"', $editor, $path);
234
        switch (Util\Platform::getOS()) {
235
            case Util\Platform::OS_WIN:
236
                $command = \sprintf('start /B "" %s "%s"', $editor, $path);
237
                break;
238
            case Util\Platform::OS_OSX:
239
                // Typora on macOS
240
                if ($editor == 'typora') {
241
                    $command = \sprintf('open -a typora "%s"', $path);
242
                }
243
                break;
244
        }
245
        $process = Process::fromShellCommandline($command);
246
        $process->run();
247
        if (!$process->isSuccessful()) {
248
            throw new RuntimeException(\sprintf('Can\'t use "%s" editor.', $editor));
249
        }
250
    }
251
252
    /**
253
     * Validate URL.
254
     *
255
     * @throws RuntimeException
256
     */
257
    public static function validateUrl(string $url): string
258
    {
259
        $validator = Validation::createValidator();
260
        $violations = $validator->validate($url, new Url());
261
        if (\count($violations) > 0) {
262
            foreach ($violations as $violation) {
263
                throw new RuntimeException($violation->getMessage());
264
            }
265
        }
266
        return rtrim($url, '/') . '/';
267
    }
268
269
    /**
270
     * Returns the "binary name" in the console context.
271
     */
272
    protected function binName(): string
273
    {
274
        return basename($_SERVER['argv'][0]);
275
    }
276
277
    /**
278
     * Override default help message.
279
     *
280
     * @return string
281
     */
282
    public function getProcessedHelp(): string
283
    {
284
        $name = $this->getName();
285
        $placeholders = [
286
            '%command.name%',
287
            '%command.full_name%',
288
        ];
289
        $replacements = [
290
            $name,
291
            $this->binName() . ' ' . $name,
292
        ];
293
294
        return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
295
    }
296
}
297