Completed
Pull Request — master (#68)
by Björn
03:48
created

CheckCommand::execute()   B

Complexity

Conditions 8
Paths 22

Size

Total Lines 65
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 10.0406

Importance

Changes 0
Metric Value
eloc 40
dl 0
loc 65
ccs 28
cts 41
cp 0.6828
rs 8.0355
c 0
b 0
f 0
cc 8
nc 22
nop 2
crap 10.0406

How to fix   Long Method   

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
namespace ComposerRequireChecker\Cli;
4
5
use ComposerRequireChecker\ASTLocator\LocateASTFromFiles;
6
use ComposerRequireChecker\DefinedExtensionsResolver\DefinedExtensionsResolver;
7
use ComposerRequireChecker\DefinedSymbolsLocator\LocateDefinedSymbolsFromASTRoots;
8
use ComposerRequireChecker\DefinedSymbolsLocator\LocateDefinedSymbolsFromExtensions;
9
use ComposerRequireChecker\DependencyGuesser\DependencyGuesser;
10
use ComposerRequireChecker\FileLocator\LocateComposerPackageDirectDependenciesSourceFiles;
11
use ComposerRequireChecker\FileLocator\LocateComposerPackageSourceFiles;
12
use ComposerRequireChecker\GeneratorUtil\ComposeGenerators;
13
use ComposerRequireChecker\JsonLoader;
14
use ComposerRequireChecker\UsedSymbolsLocator\LocateUsedSymbolsFromASTRoots;
15
use PhpParser\ErrorHandler\Collecting as CollectingErrorHandler;
16
use PhpParser\ParserFactory;
17
use Symfony\Component\Console\Command\Command;
18
use Symfony\Component\Console\Helper\Table;
19
use Symfony\Component\Console\Input\InputArgument;
20
use Symfony\Component\Console\Input\InputInterface;
21
use Symfony\Component\Console\Input\InputOption;
22
use Symfony\Component\Console\Output\OutputInterface;
23
24
class CheckCommand extends Command
25
{
26 3
    protected function configure()
27
    {
28
        $this
29 3
            ->setName('check')
30 3
            ->setDescription('check the defined dependencies against your code')
31 3
            ->addOption(
32 3
                'config-file',
33 3
                null,
34 3
                InputOption::VALUE_REQUIRED,
35 3
                'the config.json file to configure the checking options'
36
            )
37 3
            ->addArgument(
38 3
                'composer-json',
39 3
                InputArgument::OPTIONAL,
40 3
                'the composer.json of your package, that should be checked',
41 3
                './composer.json'
42
            )
43 3
        ->addOption(
44 3
                'ignore-parse-errors',
45 3
                null,
46 3
                InputOption::VALUE_NONE,
47
                'this will cause ComposerRequireChecker to ignore errors when files cannot be parsed, otherwise'
48 3
                . ' errors will be thrown'
49
            );
50 3
    }
51
52 2
    protected function execute(InputInterface $input, OutputInterface $output): int
53
    {
54 2
        if (!$output->isQuiet()) {
55 2
            $output->writeln($this->getApplication()->getLongVersion());
56
        }
57
58 2
        $composerJson = realpath($input->getArgument('composer-json'));
59 2
        if (false === $composerJson) {
60 1
            throw new \InvalidArgumentException('file not found: [' . $input->getArgument('composer-json') . ']');
61
        }
62 1
        $this->checkJsonFile($composerJson);
63
64 1
        $options = $this->getCheckOptions($input);
65
66 1
        $getPackageSourceFiles = new LocateComposerPackageSourceFiles();
67
68 1
        $sourcesASTs = $this->getASTFromFilesLocator($input);
69
70 1
        $definedVendorSymbols = (new LocateDefinedSymbolsFromASTRoots())->__invoke($sourcesASTs(
71 1
            (new ComposeGenerators())->__invoke(
72 1
                $getPackageSourceFiles($composerJson),
73 1
                (new LocateComposerPackageDirectDependenciesSourceFiles())->__invoke($composerJson)
74
            )
75
        ));
76 1
        while (count($definedVendorSymbols->getIncludes())) {
77
            (new LocateDefinedSymbolsFromASTRoots())->__invoke($sourcesASTs($definedVendorSymbols->getIncludes()), $definedVendorSymbols);
78
        }
79
80 1
        $definedExtensionSymbols = (new LocateDefinedSymbolsFromExtensions())->__invoke(
81 1
            (new DefinedExtensionsResolver())->__invoke($composerJson, $options->getPhpCoreExtensions())
82
        );
83
84 1
        $usedSymbols = (new LocateUsedSymbolsFromASTRoots())
85 1
            ->__invoke($sourcesASTs($getPackageSourceFiles($composerJson)));
86
87 1
        if (!count($usedSymbols)) {
88
            throw new \LogicException('There were no symbols found, please check your configuration.');
89
        }
90
91 1
        $unknownSymbols = array_diff(
92 1
            $usedSymbols,
93 1
            $definedVendorSymbols->getSymbols(),
94 1
            $definedExtensionSymbols,
95 1
            $options->getSymbolWhitelist()
96
        );
97
98 1
        if (!$unknownSymbols) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $unknownSymbols of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
99 1
            $output->writeln("There were no unknown symbols found.");
100 1
            return 0;
101
        }
102
103
        $output->writeln("The following unknown symbols were found:");
104
        $table = new Table($output);
105
        $table->setHeaders(['unknown symbol', 'guessed dependency']);
106
        $guesser = new DependencyGuesser();
107
        foreach ($unknownSymbols as $unknownSymbol) {
108
            $guessedDependencies = [];
109
            foreach ($guesser($unknownSymbol) as $guessedDependency) {
110
                $guessedDependencies[] = $guessedDependency;
111
            }
112
            $table->addRow([$unknownSymbol, implode("\n", $guessedDependencies)]);
113
        }
114
        $table->render();
115
116
        return ((int)(bool)$unknownSymbols);
117
    }
118
119 1
    private function getCheckOptions(InputInterface $input): Options
120
    {
121 1
        $fileName = $input->getOption('config-file');
122 1
        if (!$fileName) {
123 1
            return new Options();
124
        }
125
        return new Options((new JsonLoader($fileName))->getData());
126
    }
127
128
    /**
129
     * @param string $jsonFile
130
     * @throws \ComposerRequireChecker\Exception\InvalidJsonException
131
     * @throws \ComposerRequireChecker\Exception\NotReadableException
132
     * @internal param string $composerJson the path to composer.json
133
     */
134 1
    private function checkJsonFile(string $jsonFile)
135
    {
136
        // JsonLoader throws an exception if it cannot load the file
137 1
        new JsonLoader($jsonFile);
138 1
    }
139
140
    /**
141
     * @param InputInterface $input
142
     * @return LocateASTFromFiles
143
     */
144 1
    private function getASTFromFilesLocator(InputInterface $input): LocateASTFromFiles
145
    {
146 1
        $errorHandler = $input->getOption('ignore-parse-errors') ? new CollectingErrorHandler() : null;
147 1
        $sourcesASTs = new LocateASTFromFiles((new ParserFactory())->create(ParserFactory::PREFER_PHP7), $errorHandler);
148 1
        return $sourcesASTs;
149
    }
150
151
}
152