Completed
Pull Request — master (#163)
by Guillaume
04:49
created

CheckCommand::verbose()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 3
c 1
b 0
f 1
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 3
crap 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\FileLocator\LocateFilesByGlobPattern;
13
use ComposerRequireChecker\GeneratorUtil\ComposeGenerators;
14
use ComposerRequireChecker\JsonLoader;
15
use ComposerRequireChecker\UsedSymbolsLocator\LocateUsedSymbolsFromASTRoots;
16
use PhpParser\ErrorHandler\Collecting as CollectingErrorHandler;
17
use PhpParser\ParserFactory;
18
use Symfony\Component\Console\Command\Command;
19
use Symfony\Component\Console\Helper\Table;
20
use Symfony\Component\Console\Input\InputArgument;
21
use Symfony\Component\Console\Input\InputInterface;
22
use Symfony\Component\Console\Input\InputOption;
23
use Symfony\Component\Console\Output\OutputInterface;
24
use function dirname;
25
26
class CheckCommand extends Command
27
{
28 6
    protected function configure()
29
    {
30
        $this
31 6
            ->setName('check')
32 6
            ->setDescription('check the defined dependencies against your code')
33 6
            ->addOption(
34 6
                'config-file',
35 6
                null,
36 6
                InputOption::VALUE_REQUIRED,
37 6
                'the config.json file to configure the checking options'
38
            )
39 6
            ->addArgument(
40 6
                'composer-json',
41 6
                InputArgument::OPTIONAL,
42 6
                'the composer.json of your package, that should be checked',
43 6
                './composer.json'
44
            )
45 6
            ->addOption(
46 6
                'ignore-parse-errors',
47 6
                null,
48 6
                InputOption::VALUE_NONE,
49
                'this will cause ComposerRequireChecker to ignore errors when files cannot be parsed, otherwise'
50 6
                . ' errors will be thrown'
51
            )
52 6
            ->addOption(
53 6
                'include-dev',
54 6
                null,
55 6
                InputOption::VALUE_NONE,
56 6
                'also check the development sources and the development dependencies'
57
            );
58 6
    }
59
60 5
    protected function execute(InputInterface $input, OutputInterface $output): int
61
    {
62 5
        if (!$output->isQuiet()) {
63 5
            $output->writeln($this->getApplication()->getLongVersion());
64
        }
65
66 5
        $composerJson = realpath($input->getArgument('composer-json'));
0 ignored issues
show
Bug introduced by
It seems like $input->getArgument('composer-json') can also be of type string[]; however, parameter $path of realpath() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

66
        $composerJson = realpath(/** @scrutinizer ignore-type */ $input->getArgument('composer-json'));
Loading history...
67 5
        if (false === $composerJson) {
68 1
            throw new \InvalidArgumentException('file not found: [' . $input->getArgument('composer-json') . ']');
0 ignored issues
show
Bug introduced by
Are you sure $input->getArgument('composer-json') of type null|string|string[] can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

68
            throw new \InvalidArgumentException('file not found: [' . /** @scrutinizer ignore-type */ $input->getArgument('composer-json') . ']');
Loading history...
69
        }
70 4
        $composerData = $this->getComposerData($composerJson);
71
72 4
        $includeDev = (bool)$input->getOption('include-dev');
73
74 4
        $options = $this->getCheckOptions($input);
75
76 4
        $getPackageSourceFiles = new LocateComposerPackageSourceFiles($includeDev);
77 4
        $getAdditionalSourceFiles = new LocateFilesByGlobPattern();
78
79 4
        $sourcesASTs = $this->getASTFromFilesLocator($input);
80
81 4
        $this->verbose("Collecting defined vendor symbols... ", $output);
82 4
        $definedVendorSymbols = (new LocateDefinedSymbolsFromASTRoots())->__invoke($sourcesASTs(
83 4
            (new ComposeGenerators())->__invoke(
84 4
                $getAdditionalSourceFiles($options->getScanFiles(), dirname($composerJson)),
85 4
                $getPackageSourceFiles($composerData, dirname($composerJson)),
86 4
                (new LocateComposerPackageDirectDependenciesSourceFiles($includeDev))->__invoke($composerJson)
87
            )
88
        ));
89 4
        $this->verbose("found " . count($definedVendorSymbols) . " symbols.", $output, true);
90
91 4
        $this->verbose("Collecting defined extension symbols... ", $output);
92 4
        $definedExtensionSymbols = (new LocateDefinedSymbolsFromExtensions())->__invoke(
93 4
            (new DefinedExtensionsResolver())->__invoke($composerJson, $options->getPhpCoreExtensions())
94
        );
95 4
        $this->verbose("found " . count($definedExtensionSymbols) . " symbols.", $output, true);
96
97 4
        $this->verbose("Collecting used symbols... ", $output);
98 4
        $usedSymbols = (new LocateUsedSymbolsFromASTRoots())->__invoke($sourcesASTs(
99 4
            (new ComposeGenerators())->__invoke(
100 4
                $getPackageSourceFiles($composerData, dirname($composerJson)),
101 4
                $getAdditionalSourceFiles($options->getScanFiles(), dirname($composerJson))
102
            )
103
        ));
104 4
        $this->verbose("found " . count($usedSymbols) . " symbols.", $output, true);
105
106 4
        if (!count($usedSymbols)) {
107
            throw new \LogicException('There were no symbols found, please check your configuration.');
108
        }
109
110 4
        $this->verbose("Checking for unknown symbols... ", $output, true);
111 4
        $unknownSymbols = array_diff(
112 4
            $usedSymbols,
113 4
            $definedVendorSymbols,
114 4
            $definedExtensionSymbols,
115 4
            $options->getSymbolWhitelist()
116
        );
117
118 4
        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...
119 4
            $output->writeln("There were no unknown symbols found.");
120 4
            return 0;
121
        }
122
123
        $output->writeln("The following unknown symbols were found:");
124
        $table = new Table($output);
125
        $table->setHeaders(['unknown symbol', 'guessed dependency']);
126
        $guesser = new DependencyGuesser($options);
127
        foreach ($unknownSymbols as $unknownSymbol) {
128
            $guessedDependencies = [];
129
            foreach ($guesser($unknownSymbol) as $guessedDependency) {
130
                $guessedDependencies[] = $guessedDependency;
131
            }
132
            $table->addRow([$unknownSymbol, implode("\n", $guessedDependencies)]);
133
        }
134
        $table->render();
135
136
        return ((int)(bool)$unknownSymbols);
137
    }
138
139 4
    private function getCheckOptions(InputInterface $input): Options
140
    {
141 4
        $fileName = $input->getOption('config-file');
142 4
        if (!$fileName) {
143 3
            return new Options();
144
        }
145 1
        return new Options((new JsonLoader($fileName))->getData());
146
    }
147
148
    /**
149
     * @param string $jsonFile
150
     * @throws \ComposerRequireChecker\Exception\InvalidJsonException
151
     * @throws \ComposerRequireChecker\Exception\NotReadableException
152
     */
153 4
    private function getComposerData(string $jsonFile): array
154
    {
155
        // JsonLoader throws an exception if it cannot load the file
156 4
        return (new JsonLoader($jsonFile))->getData();
157
    }
158
159
    /**
160
     * @param InputInterface $input
161
     * @return LocateASTFromFiles
162
     */
163 4
    private function getASTFromFilesLocator(InputInterface $input): LocateASTFromFiles
164
    {
165 4
        $errorHandler = $input->getOption('ignore-parse-errors') ? new CollectingErrorHandler() : null;
166 4
        $sourcesASTs = new LocateASTFromFiles((new ParserFactory())->create(ParserFactory::PREFER_PHP7), $errorHandler);
167 4
        return $sourcesASTs;
168
    }
169
170
171
    /**
172
     * @param string $string the message that should be printed
173
     * @param OutputInterface $output the output to log to
174
     * @param bool $newLine if a new line will be started afterwards
175
     */
176 4
    private function verbose(string $string, OutputInterface $output, bool $newLine = false): void
177
    {
178 4
        if (!$output->isVerbose()) {
179 3
            return;
180
        }
181
182 1
        $output->write($string, $newLine);
183 1
    }
184
}
185