Failed Conditions
Pull Request — master (#38)
by Matthias
02:35
created

CheckCommand   B

Complexity

Total Complexity 13

Size/Duplication

Total Lines 126
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 17

Test Coverage

Coverage 27.54%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 13
c 1
b 0
f 0
lcom 2
cbo 17
dl 0
loc 126
ccs 19
cts 69
cp 0.2754
rs 7.8571

5 Methods

Rating   Name   Duplication   Size   Complexity  
B configure() 0 26 1
B execute() 0 63 7
A getCheckOptions() 0 8 2
A checkJsonFile() 0 5 1
A getASTFromFilesLocator() 0 6 2
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 1
    protected function configure()
27
    {
28
        $this
29 1
            ->setName('check')
30 1
            ->setDescription('check the defined dependencies against your code')
31 1
            ->addOption(
32 1
                'config-file',
33 1
                null,
34 1
                InputOption::VALUE_REQUIRED,
35 1
                'the config.json file to configure the checking options'
36
            )
37 1
            ->addArgument(
38 1
                'composer-json',
39 1
                InputArgument::OPTIONAL,
40 1
                'the composer.json of your package, that should be checked',
41 1
                './composer.json'
42
            )
43 1
            ->addOption(
44 1
                'ignore-parse-errors',
45 1
                null,
46 1
                InputOption::VALUE_NONE,
47
                'this will cause ComposerRequireChecker to ignore errors when files cannot be parsed, otherwise'
48 1
                . ' errors will be thrown'
49
            )
50
        ;
51 1
    }
52
53
    protected function execute(InputInterface $input, OutputInterface $output) : int
54
    {
55
56
        if(!$output->isQuiet()) {
57
            $output->writeln($this->getApplication()->getLongVersion());
58
        }
59
60
        $composerJson = realpath($input->getArgument('composer-json'));
61
        if(false === $composerJson) {
62
            throw new \InvalidArgumentException('file not found: [' . $input->getArgument('composer-json') . ']');
63
        }
64
        $this->checkJsonFile($composerJson);
65
66
        $options = $this->getCheckOptions($input);
67
68
        $getPackageSourceFiles = new LocateComposerPackageSourceFiles();
69
70
        $sourcesASTs = $this->getASTFromFilesLocator($input);
71
72
        $definedVendorSymbols = (new LocateDefinedSymbolsFromASTRoots())->__invoke($sourcesASTs(
73
            (new ComposeGenerators())->__invoke(
74
                $getPackageSourceFiles($composerJson),
75
                (new LocateComposerPackageDirectDependenciesSourceFiles())->__invoke($composerJson)
76
            )
77
        ));
78
79
        $definedExtensionSymbols = (new LocateDefinedSymbolsFromExtensions())->__invoke(
80
            (new DefinedExtensionsResolver())->__invoke($composerJson, $options->getPhpCoreExtensions())
81
        );
82
83
        $usedSymbols = (new LocateUsedSymbolsFromASTRoots())->__invoke($sourcesASTs($getPackageSourceFiles($composerJson)));
84
85
        if (!count($usedSymbols)) {
86
            throw new \LogicException('There were no symbols found, please check your configuration.');
87
        }
88
89
        $unknownSymbols = array_diff(
90
            $usedSymbols,
91
            $definedVendorSymbols,
92
            $definedExtensionSymbols,
93
            $options->getSymbolWhitelist()
94
        );
95
96
        if (!$unknownSymbols) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $unknownSymbols of type string[] 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...
97
            $output->writeln("There were no unknown symbols found.");
98
            return 0;
99
        }
100
101
        $output->writeln("The following unknown symbols were found:");
102
        $table = new Table($output);
103
        $table->setHeaders(['unknown symbol', 'guessed dependency']);
104
        $guesser = new DependencyGuesser();
105
        foreach ($unknownSymbols as $unknownSymbol) {
106
            $guessedDependencies = [];
107
            foreach($guesser($unknownSymbol) as $guessedDependency) {
108
                $guessedDependencies[] = $guessedDependency;
109
            }
110
            $table->addRow([$unknownSymbol, implode("\n", $guessedDependencies)]);
111
        }
112
        $table->render();
113
114
        return ((int) (bool) $unknownSymbols);
115
    }
116
117
    private function getCheckOptions(InputInterface $input) : Options
118
    {
119
        $fileName = $input->getOption('config-file');
120
        if(!$fileName) {
121
            return new Options();
122
        }
123
        return new Options((new JsonLoader($fileName))->getData());
124
    }
125
126
    /**
127
     * @param string $jsonFile
128
     * @throws \ComposerRequireChecker\Exception\InvalidJsonException
129
     * @throws \ComposerRequireChecker\Exception\NotReadableException
130
     * @internal param string $composerJson the path to composer.json
131
     */
132
    private function checkJsonFile(string $jsonFile)
133
    {
134
        // JsonLoader throws an exception if it cannot load the file
135
        new JsonLoader($jsonFile);
136
    }
137
138
    /**
139
     * @param InputInterface $input
140
     * @return LocateASTFromFiles
141
     */
142
    private function getASTFromFilesLocator(InputInterface $input): LocateASTFromFiles
143
    {
144
        $errorHandler = $input->getOption('ignore-parse-errors') ? new CollectingErrorHandler() : null;
145
        $sourcesASTs = new LocateASTFromFiles((new ParserFactory())->create(ParserFactory::PREFER_PHP7), $errorHandler);
146
        return $sourcesASTs;
147
    }
148
149
}
150