Completed
Push — master ( b1adff...449a59 )
by Théo
02:23
created

AddPrefixCommand::makeAbsolutePath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 3
Ratio 37.5 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 3
loc 8
ccs 4
cts 4
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the humbug/php-scoper package.
7
 *
8
 * Copyright (c) 2017 Théo FIDRY <[email protected]>,
9
 *                    Pádraic Brady <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Humbug\PhpScoper\Console\Command;
16
17
use Humbug\PhpScoper\Handler\HandleAddPrefix;
18
use Humbug\PhpScoper\Logger\ConsoleLogger;
19
use Symfony\Component\Console\Command\Command;
20
use Symfony\Component\Console\Exception\RuntimeException;
21
use Symfony\Component\Console\Input\InputArgument;
22
use Symfony\Component\Console\Input\InputInterface;
23
use Symfony\Component\Console\Input\InputOption;
24
use Symfony\Component\Console\Output\OutputInterface;
25
use Symfony\Component\Console\Style\OutputStyle;
26
use Symfony\Component\Console\Style\SymfonyStyle;
27
use Symfony\Component\Filesystem\Filesystem;
28
use Throwable;
29
30
final class AddPrefixCommand extends Command
31
{
32
    /** @internal */
33
    const PATH_ARG = 'paths';
34
    /** @internal */
35
    const PREFIX_OPT = 'prefix';
36
    /** @internal */
37
    const OUTPUT_DIR_OPT = 'output-dir';
38
    /** @internal */
39
    const FORCE_OPT = 'force';
40
    /** @internal */
41
    const PATCH_FILE = 'patch-file';
42
    /** @internal */
43
    const PATCH_FILE_DEFAULT = 'scoper.inc.php';
44
45
    private $fileSystem;
46
    private $handle;
47
48
    /**
49
     * @inheritdoc
50
     */
51 20
    public function __construct(Filesystem $fileSystem, HandleAddPrefix $handle)
52
    {
53 20
        parent::__construct();
54
55 20
        $this->fileSystem = $fileSystem;
56 20
        $this->handle = $handle;
57 20
    }
58
59
    /**
60
     * @inheritdoc
61
     */
62 20
    protected function configure()
63
    {
64
        $this
65 20
            ->setName('add-prefix')
66 20
            ->setDescription('Goes through all the PHP files found in the given paths to apply the given prefix to namespaces & FQNs.')
67 20
            ->addArgument(
68 20
                self::PATH_ARG,
69 20
                InputArgument::IS_ARRAY,
70 20
                'The path(s) to process.'
71
            )
72 20
            ->addOption(
73 20
                self::PREFIX_OPT,
74 20
                'p',
75 20
                InputOption::VALUE_REQUIRED,
76 20
                'The namespace prefix to add.'
77
            )
78 20
            ->addOption(
79 20
                self::OUTPUT_DIR_OPT,
80 20
                'o',
81 20
                InputOption::VALUE_REQUIRED,
82 20
                'The output directory in which the prefixed code will be dumped.',
83 20
                'build'
84
            )
85 20
            ->addOption(
86 20
                self::FORCE_OPT,
87 20
                'f',
88 20
                InputOption::VALUE_NONE,
89 20
                'Deletes any existing content in the output directory without any warning.'
90
            )
91 20
            ->addOption(
92 20
                self::PATCH_FILE,
93 20
                'c',
94 20
                InputOption::VALUE_REQUIRED,
95 20
                sprintf(
96 20
                    'Configuration file for the patchers. Will use "%s" if found by default',
97 20
                    self::PATCH_FILE_DEFAULT
98
                ),
99 20
                null
100
            )
101
        ;
102 20
    }
103
104
    /**
105
     * @inheritdoc
106
     */
107 18
    protected function execute(InputInterface $input, OutputInterface $output)
108
    {
109 18
        $io = new SymfonyStyle($input, $output);
110
111 18
        $this->validatePrefix($input);
112 13
        $this->validatePaths($input);
113 13
        $this->validateOutputDir($input, $io);
114 13
        $patchers = $this->validatePatchers($input, $io);
115
116 11
        $logger = new ConsoleLogger(
117 11
            $this->getApplication(),
118 11
            $io
119
        );
120
121 11
        $logger->outputScopingStart(
122 11
            $input->getOption(self::PREFIX_OPT),
123 11
            $input->getArgument(self::PATH_ARG)
124
        );
125
126
        try {
127 11
            $this->handle->__invoke(
128 11
                $input->getOption(self::PREFIX_OPT),
129 11
                $input->getArgument(self::PATH_ARG),
130 11
                $input->getOption(self::OUTPUT_DIR_OPT),
131 11
                $patchers,
132 11
                $logger
133
            );
134 1
        } catch (Throwable $throwable) {
135 1
            $logger->outputScopingEndWithFailure();
136
137 1
            throw $throwable;
138
        }
139
140 10
        $logger->outputScopingEnd();
141 10
    }
142
143 18
    private function validatePrefix(InputInterface $input)
144
    {
145 18
        $prefix = $input->getOption(self::PREFIX_OPT);
146
147 18
        if (null === $prefix) {
148 1
            $prefix = uniqid('PhpScoper');
149
        } else {
150 17
            $prefix = trim($prefix);
151
        }
152
153 18
        if (1 === preg_match('/(?<prefix>.*?)\\\\*$/', $prefix, $matches)) {
154 18
            $prefix = $matches['prefix'];
155
        }
156
157 18
        if ('' === $prefix) {
158 5
            throw new RuntimeException(
159 5
                sprintf(
160 5
                    'Expected "%s" argument to be a non empty string.',
161 5
                    self::PREFIX_OPT
162
                )
163
            );
164
        }
165
166 13
        $input->setOption(self::PREFIX_OPT, $prefix);
167 13
    }
168
169 13
    private function validatePaths(InputInterface $input)
170
    {
171 13
        $cwd = getcwd();
172 13
        $fileSystem = $this->fileSystem;
173
174 13
        $paths = array_map(
175 13
            function (string $path) use ($cwd, $fileSystem) {
176 12
                if (false === $fileSystem->isAbsolutePath($path)) {
177 1
                    return $cwd.DIRECTORY_SEPARATOR.$path;
178
                }
179
180 12
                return $path;
181 13
            },
182 13
            $input->getArgument(self::PATH_ARG)
183
        );
184
185 13
        if (0 === count($paths)) {
186 1
            $paths[] = $cwd;
187
        }
188
189 13
        $input->setArgument(self::PATH_ARG, $paths);
190 13
    }
191
192 13
    private function validateOutputDir(InputInterface $input, OutputStyle $io)
193
    {
194 13
        $outputDir = $input->getOption(self::OUTPUT_DIR_OPT);
195
196 13 View Code Duplication
        if (false === $this->fileSystem->isAbsolutePath($outputDir)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
197 1
            $outputDir = getcwd().DIRECTORY_SEPARATOR.$outputDir;
198
        }
199
200 13
        $input->setOption(self::OUTPUT_DIR_OPT, $outputDir);
201
202 13
        if (false === $this->fileSystem->exists($outputDir)) {
203 13
            return;
204
        }
205
206
        if (false === is_writable($outputDir)) {
207
            throw new RuntimeException(
208
                sprintf(
209
                    'Expected "<comment>%s</comment>" to be writeable.',
210
                    $outputDir
211
                )
212
            );
213
        }
214
215
        if ($input->getOption(self::FORCE_OPT)) {
216
            $this->fileSystem->remove($outputDir);
217
218
            return;
219
        }
220
221
        if (false === is_dir($outputDir)) {
222
            $canDeleteFile = $io->confirm(
223
                sprintf(
224
                    'Expected "<comment>%s</comment>" to be a directory but found a file instead. It will be '
225
                    .'removed, do you wish to proceed?',
226
                    $outputDir
227
                ),
228
                false
229
            );
230
231
            if (false === $canDeleteFile) {
232
                return;
233
            }
234
235
            $this->fileSystem->remove($outputDir);
236
        } else {
237
            $canDeleteFile = $io->confirm(
238
                sprintf(
239
                    'The output directory "<comment>%s</comment>" already exists. Continuing will erase its'
240
                    .' content, do you wish to proceed?',
241
                    $outputDir
242
                ),
243
                false
244
            );
245
246
            if (false === $canDeleteFile) {
247
                return;
248
            }
249
250
            $this->fileSystem->remove($outputDir);
251
        }
252
    }
253
254
    /**
255
     * @param InputInterface $input
256
     * @param OutputStyle    $io
257
     *
258
     * @return callable[]
259
     */
260 13
    private function validatePatchers(InputInterface $input, OutputStyle $io): array
261
    {
262 13
        $patchFile = $input->getOption(self::PATCH_FILE);
263
264 13
        if (null === $patchFile) {
265 12
            $patchFile = $this->makeAbsolutePath(self::PATCH_FILE_DEFAULT);
266
267 12
            if (false === file_exists($patchFile)) {
268 2
                $io->writeln(
269 2
                    sprintf(
270 2
                        'Patch file "%s" not found. Skipping.',
271 2
                        $patchFile
272
                    ),
273 2
                    OutputStyle::VERBOSITY_DEBUG
274
                );
275
276 12
                return [];
277
            }
278
        } else {
279 1
            $patchFile = $this->makeAbsolutePath($patchFile);
280
        }
281
282 11
        if (false === file_exists($patchFile)) {
283 1
            throw new RuntimeException(
284 1
                sprintf(
285 1
                    'Could not find the file "%s".',
286 1
                    $patchFile
287
                )
288
            );
289
        }
290
291 10
        $io->writeln(
292 10
            sprintf(
293 10
                'Using the configuration file "%s".',
294 10
                $patchFile
295
            ),
296 10
            OutputStyle::VERBOSITY_DEBUG
297
        );
298
299 10
        $patchers = include $patchFile;
300
301 10
        if (false === is_array($patchers)) {
302
            throw new RuntimeException(
303
                sprintf(
304
                    'Expected patchers to be an array of callables, found "%s" instead.',
305
                    gettype($patchers)
306
                )
307
            );
308
        }
309
310 10
        foreach ($patchers as $index => $patcher) {
311 10
            if (false === is_callable($patcher)) {
312 1
                throw new RuntimeException(
313 1
                    sprintf(
314 1
                        'Expected patchers to be an array of callables, the "%d" element is not.',
315 10
                        $index
316
                    )
317
                );
318
            }
319
        }
320
321 9
        return $patchers;
322
    }
323
324 13
    private function makeAbsolutePath(string $path): string
325
    {
326 13 View Code Duplication
        if (false === $this->fileSystem->isAbsolutePath($path)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
327 10
            $path = getcwd().DIRECTORY_SEPARATOR.$path;
328
        }
329
330 13
        return $path;
331
    }
332
}
333