Passed
Pull Request — master (#2148)
by Arnaud
11:34 queued 04:52
created

AbstractCommand::run()   B

Complexity

Conditions 11
Paths 32

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 11
eloc 22
c 3
b 1
f 0
nc 32
nop 2
dl 0
loc 36
rs 7.3166

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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