PrintCFGCommand::execute()   F
last analyzed

Complexity

Conditions 16
Paths 288

Size

Total Lines 117

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 272

Importance

Changes 0
Metric Value
cc 16
nc 288
nop 2
dl 0
loc 117
ccs 0
cts 63
cp 0
crap 272
rs 2.9066
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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 PHPSA\Command;
4
5
use FilesystemIterator;
6
use PhpParser\ParserFactory;
7
use PHPSA\Application;
8
use PHPSA\Compiler;
9
use PHPSA\Context;
10
use PHPSA\ControlFlow\BlockTraverser;
11
use PHPSA\ControlFlow\Visitor;
12
use PHPSA\Definition\FileParser;
13
use RecursiveDirectoryIterator;
14
use RecursiveIteratorIterator;
15
use SplFileInfo;
16
use Symfony\Component\Console\Input\InputArgument;
17
use Symfony\Component\Console\Input\InputInterface;
18
use Symfony\Component\Console\Input\InputOption;
19
use Symfony\Component\Console\Output\OutputInterface;
20
use Webiny\Component\EventManager\EventManager;
21
22
/**
23
 * Command to dump the analyzer documentation as markdown
24
 */
25
class PrintCFGCommand extends AbstractCommand
26
{
27
    /**
28
     * {@inheritdoc}
29
     */
30 1
    protected function configure()
31
    {
32
        $this
33 1
            ->setName('print-cfg')
34 1
            ->setDescription('Dumps Control Flow Graph')
35 1
            ->addOption('config-file', null, InputOption::VALUE_REQUIRED, 'Path to the configuration file.')
36 1
            ->addArgument('path', InputArgument::OPTIONAL, 'Path to check file or directory', '.');
37
        ;
38 1
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    protected function execute(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Complexity introduced by
This operation has 3600 execution paths which exceeds the configured maximum of 200.

A high number of execution paths generally suggests many nested conditional statements and make the code less readible. This can usually be fixed by splitting the method into several smaller methods.

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

Loading history...
44
    {
45
        $output->writeln('');
46
47
        if (extension_loaded('xdebug')) {
48
            /**
49
             * This will disable only showing stack traces on error conditions.
50
             */
51
            if (function_exists('xdebug_disable')) {
52
                xdebug_disable();
53
            }
54
55
            $output->writeln('<error>It is highly recommended to disable the XDebug extension before invoking this command.</error>');
56
        }
57
58
        /** @var Application $application */
59
        $application = $this->getApplication();
60
        $application->compiler = new Compiler();
61
62
        $configFile = $input->getOption('config-file') ?: '.phpsa.yml';
63
        $configDir = realpath($input->getArgument('path'));
64
        $application->configuration = $this->loadConfiguration($configFile, $configDir);
65
66
        $parser = $this->createParser($application);
0 ignored issues
show
Documentation introduced by
$application is of type object<PHPSA\Application>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
67
68
        $output->writeln('Used config file: ' . $application->configuration->getPath());
69
70
        $em = EventManager::getInstance();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $em. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
71
        $context = new Context($output, $application, $em);
72
73
        $fileParser = new FileParser(
74
            $parser,
75
            $application->compiler
76
        );
77
78
        $path = $input->getArgument('path');
79
        if (is_dir($path)) {
80
            $directoryIterator = new RecursiveIteratorIterator(
81
                new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)
82
            );
83
            $output->writeln('Scanning directory <info>' . $path . '</info>');
84
85
            $count = 0;
86
87
            /** @var SplFileInfo $file */
88
            foreach ($directoryIterator as $file) {
89
                if ($file->getExtension() !== 'php') {
90
                    continue;
91
                }
92
93
                $context->debug($file->getPathname());
94
                $count++;
95
            }
96
97
            $output->writeln("Found <info>{$count} files</info>");
98
99
            if ($count > 100) {
100
                $output->writeln('<comment>Caution: You are trying to scan a lot of files; this might be slow. For bigger libraries, consider setting up a dedicated platform or using ci.lowl.io.</comment>');
101
            }
102
103
            $output->writeln('');
104
105
            /** @var SplFileInfo $file */
106
            foreach ($directoryIterator as $file) {
107
                if ($file->getExtension() !== 'php') {
108
                    continue;
109
                }
110
111
                $fileParser->parserFile($file->getPathname(), $context);
112
            }
113
        } elseif (is_file($path)) {
114
            $fileParser->parserFile($path, $context);
0 ignored issues
show
Bug introduced by
It seems like $path defined by $input->getArgument('path') on line 78 can also be of type array<integer,string> or null; however, PHPSA\Definition\FileParser::parserFile() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
115
        }
116
117
118
        /**
119
         * Step 2 Recursive check ...
120
         */
121
        $application->compiler->compile($context);
122
123
        $traverser = new BlockTraverser();
124
        //$traverser->addVisitor(new Visitor\DebugTextVisitor());
125
        $traverser->addVisitor(new Visitor\UnreachableVisitor());
126
127
        $printer = new \PHPSA\ControlFlow\Printer\DebugText();
128
129
        $functions = $application->compiler->getFunctions();
130
        foreach ($functions as $function) {
131
            $output->writeln('Function: ' . $function->getName());
132
133
            $cfg = $function->getCFG();
134
            if ($cfg) {
135
                $traverser->traverse($cfg);
136
                $printer->printGraph($cfg->getRoot());
137
            }
138
        }
139
140
        $classess = $application->compiler->getClasses();
141
        foreach ($classess as $class) {
142
            $output->writeln('Class: ' . $class->getName());
143
144
            $methods = $class->getMethods();
145
146
            foreach ($methods as $method) {
147
                $output->writeln('Method: ' . $method->getName());
148
149
                $cfg = $method->getCFG();
150
                if ($cfg) {
151
                    $traverser->traverse($cfg);
152
                    $printer->printGraph($cfg->getRoot());
153
                }
154
            }
155
        }
156
157
        $output->writeln('');
158
        $output->writeln('Memory usage: ' . $this->getMemoryUsage(false) . ' (peak: ' . $this->getMemoryUsage(true) . ') MB');
159
    }
160
}
161