Completed
Pull Request — master (#28)
by
unknown
11:17 queued 09:41
created

CheckCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 19
ccs 14
cts 14
cp 1
rs 9.4285
cc 1
eloc 14
nc 1
nop 0
crap 1
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\Exception\InvalidInputFileException;
11
use ComposerRequireChecker\FileLocator\LocateComposerPackageDirectDependenciesSourceFiles;
12
use ComposerRequireChecker\FileLocator\LocateComposerPackageSourceFiles;
13
use ComposerRequireChecker\GeneratorUtil\ComposeGenerators;
14
use ComposerRequireChecker\UsedSymbolsLocator\LocateUsedSymbolsFromASTRoots;
15
use PhpParser\ParserFactory;
16
use Symfony\Component\Console\Command\Command;
17
use Symfony\Component\Console\Helper\Table;
18
use Symfony\Component\Console\Input\InputArgument;
19
use Symfony\Component\Console\Input\InputInterface;
20
use Symfony\Component\Console\Input\InputOption;
21
use Symfony\Component\Console\Output\OutputInterface;
22
23
class CheckCommand extends Command
24
{
25 1
    protected function configure()
26
    {
27
        $this
28 1
            ->setName('check')
29 1
            ->setDescription('check the defined dependencies against your code')
30 1
            ->addOption(
31 1
                'config-file',
32 1
                null,
33 1
                InputOption::VALUE_REQUIRED,
34 1
                'the config.json file to configure the checking options'
35
            )
36 1
            ->addArgument(
37 1
                'composer-json',
38 1
                InputArgument::OPTIONAL,
39 1
                'the composer.json of your package, that should be checked',
40 1
                './composer.json'
41
            )
42
        ;
43 1
    }
44
45
    protected function execute(InputInterface $input, OutputInterface $output) : int
46
    {
47
48
        if(!$output->isQuiet()) {
49
            $output->writeln($this->getApplication()->getLongVersion());
50
        }
51
52
        $composerJson = realpath($input->getArgument('composer-json'));
53
        if(false === $composerJson) {
54
            throw new \InvalidArgumentException('file not found: [' . $input->getArgument('composer-json') . ']');
55
        }
56
        $this->checkJsonFile($composerJson);
57
58
        $options = $this->getCheckOptions($input);
59
60
        $getPackageSourceFiles = new LocateComposerPackageSourceFiles();
61
62
        $sourcesASTs = new LocateASTFromFiles((new ParserFactory())->create(ParserFactory::PREFER_PHP7));
63
64
        $definedVendorSymbols = (new LocateDefinedSymbolsFromASTRoots())->__invoke($sourcesASTs(
65
            (new ComposeGenerators())->__invoke(
66
                $getPackageSourceFiles($composerJson),
67
                (new LocateComposerPackageDirectDependenciesSourceFiles())->__invoke($composerJson)
68
            )
69
        ));
70
71
        $definedExtensionSymbols = (new LocateDefinedSymbolsFromExtensions())->__invoke(
72
            (new DefinedExtensionsResolver())->__invoke($composerJson, $options->getPhpCoreExtensions())
73
        );
74
75
        $usedSymbols = (new LocateUsedSymbolsFromASTRoots())->__invoke($sourcesASTs($getPackageSourceFiles($composerJson)));
76
77
        if (!count($usedSymbols)) {
78
            throw new \LogicException('There were no symbols found, please check your configuration.');
79
        }
80
81
        $unknownSymbols = array_diff(
82
            $usedSymbols,
83
            $definedVendorSymbols,
84
            $definedExtensionSymbols,
85
            $options->getSymbolWhitelist()
86
        );
87
88
        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...
89
            $output->writeln("There were no unknown symbols found.");
90
            return 0;
91
        }
92
93
        $output->writeln("The following unknown symbols were found:");
94
        $table = new Table($output);
95
        $table->setHeaders(['unknown symbol', 'guessed dependency']);
96
        $guesser = new DependencyGuesser();
97
        foreach ($unknownSymbols as $unknownSymbol) {
98
            $guessedDependencies = [];
99
            foreach($guesser($unknownSymbol) as $guessedDependency) {
100
                $guessedDependencies[] = $guessedDependency;
101
            }
102
            $table->addRow([$unknownSymbol, implode("\n", $guessedDependencies)]);
103
        }
104
        $table->render();
105
106
        return ((int) (bool) $unknownSymbols);
107
    }
108
109
    private function getCheckOptions(InputInterface $input) : Options
110
    {
111
        $fileName = $input->getOption('config-file');
112
        if(!$fileName) {
113
            return new Options();
114
        }
115
116
        if(!is_readable($fileName)) {
117
            throw new \InvalidArgumentException('unable to read ' . $fileName);
118
        }
119
120
        $jsonData = json_decode(file_get_contents($fileName), true);
121
        if(false === $jsonData) {
122
            throw new \Exception('error parsing the config file: ' . json_last_error_msg());
123
        }
124
125
        return new Options($jsonData);
126
127
    }
128
129
    /**
130
     * @param string $jsonFile
131
     * @throws InvalidInputFileException
132
     * @internal param string $composerJson the path to composer.json
133
     */
134
    private function checkJsonFile(string $jsonFile)
135
    {
136
        if(!is_readable($jsonFile)) {
137
            throw new InvalidInputFileException('cannot read ' . $jsonFile);
138
        }
139
140
        if(false == json_decode(file_get_contents($jsonFile))) {
141
            throw new InvalidInputFileException('error parsing ' . $jsonFile . ': ' . json_last_error_msg());
142
        }
143
144
    }
145
146
}
147