Completed
Push — master ( ad0611...abd676 )
by Tom
09:08 queued 04:30
created

CompareVersionsCommand::execute()   F

Complexity

Conditions 16
Paths 529

Size

Total Lines 92
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 2 Features 1
Metric Value
c 3
b 2
f 1
dl 0
loc 92
rs 2.8386
cc 16
eloc 60
nc 529
nop 2

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 N98\Magento\Command\System\Setup;
4
5
use N98\JUnitXml\Document as JUnitXmlDocument;
6
use Symfony\Component\Console\Input\InputInterface;
7
use Symfony\Component\Console\Input\InputOption;
8
use Symfony\Component\Console\Output\OutputInterface;
9
use N98\Util\Console\Helper\Table\Renderer\RendererFactory;
10
11
class CompareVersionsCommand extends AbstractSetupCommand
12
{
13
    /**
14
     * Setup
15
     */
16
    protected function configure()
17
    {
18
        $this
19
            ->setName('sys:setup:compare-versions')
20
            ->addOption('ignore-data', null, InputOption::VALUE_NONE, 'Ignore data updates')
21
            ->addOption('log-junit', null, InputOption::VALUE_REQUIRED, 'Log output to a JUnit xml file.')
22
            ->addOption(
23
                'format',
24
                null,
25
                InputOption::VALUE_OPTIONAL,
26
                'Output Format. One of [' . implode(',', RendererFactory::getFormats()) . ']'
27
            )
28
            ->setDescription('Compare module version with core_resource table.');
29
        $help = <<<HELP
30
Compares module version with saved setup version in `core_resource` table and displays version mismatch.
31
HELP;
32
        $this->setHelp($help);
33
    }
34
35
    /**
36
     * @param InputInterface $input
37
     * @param OutputInterface $output
38
     * @return int|null
39
     */
40
    protected function execute(InputInterface $input, OutputInterface $output)
41
    {
42
        $this->detectMagento($output, true);
43
44
        if (!$this->initMagento()) {
45
            return;
46
        }
47
48
        $time = microtime(true);
49
        $ignoreDataUpdate = $input->getOption('ignore-data');
50
51
        $headers = array('Setup', 'Module', 'DB', 'Data', 'Status');
52
        if ($ignoreDataUpdate) {
53
            unset($headers[array_search('Data', $headers)]);
54
        }
55
56
        $errorCounter = 0;
57
        $table = array();
58
        foreach ($this->getMagentoModuleList() as $moduleName => $moduleInfo) {
59
            $moduleVersion = $moduleInfo['setup_version'];
60
            $resource      = $this->getMagentoModuleResource();
61
            $dbVersion     = $resource->getDbVersion($moduleName);
62
            if (!$ignoreDataUpdate) {
63
                $dataVersion = $resource->getDataVersion($moduleName);
64
            }
65
66
            $ok = $dbVersion == $moduleVersion;
67
            if ($ok && !$ignoreDataUpdate) {
68
                $ok = $dataVersion == $moduleVersion;
0 ignored issues
show
Bug introduced by
The variable $dataVersion does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
69
            }
70
            if (!$ok) {
71
                $errorCounter++;
72
            }
73
74
            $row = array(
75
                'Module' => $moduleName,
76
                'DB'     => $dbVersion,
77
                'Data'   => $dataVersion,
78
            );
79
80
            if (!$ignoreDataUpdate) {
81
                $row['Data-Version'] = $dataVersion;
82
            }
83
            $row['Status'] = $ok ? 'OK' : 'Error';
84
            $table[] = $row;
85
        }
86
87
        // If there is no output format highlight the status and show error'd rows at bottom
88
        if (!$input->getOption('format')) {
89
            usort($table, function ($a, $b) {
0 ignored issues
show
Unused Code introduced by
The parameter $b is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
90
                return $a['Status'] !== 'OK';
91
            });
92
93
            array_walk($table, function (&$row) {
94
                $status             = $row['Status'];
95
                $availableStatus    = array('OK' => 'info', 'Error' => 'error');
96
                $statusString       = sprintf(
97
                    '<%s>%s</%s>',
98
                    $availableStatus[$status],
99
                    $status,
100
                    $availableStatus[$status]
101
                );
102
                $row['Status'] = $statusString;
103
            });
104
        }
105
106
        if ($input->getOption('log-junit')) {
107
            $this->logJUnit($table, $input->getOption('log-junit'), microtime($time) - $time);
108
        } else {
109
            $this->getHelper('table')
110
                ->setHeaders($headers)
111
                ->renderByFormat($output, $table, $input->getOption('format'));
112
113
            //if no output format specified - output summary line
114
            if (!$input->getOption('format')) {
115
                if ($errorCounter > 0) {
116
                    $this->writeSection(
117
                        $output,
118
                        sprintf(
119
                            '%s error%s %s found!',
120
                            $errorCounter,
121
                            $errorCounter === 1 ? '' : 's',
122
                            $errorCounter === 1 ? 'was' : 'were'
123
                        ),
124
                        'error'
125
                    );
126
                } else {
127
                    $this->writeSection($output, 'No setup problems were found.', 'info');
128
                }
129
            }
130
        }
131
    }
132
133
    /**
134
     * @param array $data
135
     * @param string $filename
136
     * @param float $duration
137
     */
138
    protected function logJUnit(array $data, $filename, $duration)
139
    {
140
        $document = new JUnitXmlDocument();
141
        $suite = $document->addTestSuite();
142
        $suite->setName('n98-magerun2: ' . $this->getName());
143
        $suite->setTimestamp(new \DateTime());
144
        $suite->setTime($duration);
145
146
        $testCase = $suite->addTestCase();
147
        $testCase->setName('Magento Setup Version Test');
148
        $testCase->setClassname('CompareVersionsCommand');
149
        if (count($data) > 0) {
150
            foreach ($data as $moduleSetup) {
151
                if (stristr($moduleSetup['Status'], 'error')) {
152
                    $testCase->addFailure(
153
                        'Setup Script Error',
154
                        'MagentoSetupScriptVersionException'
155
                    );
156
                }
157
            }
158
        }
159
160
        $document->save($filename);
161
    }
162
}
163