ListCommand::execute()   C
last analyzed

Complexity

Conditions 14
Paths 54

Size

Total Lines 75
Code Lines 40

Duplication

Lines 10
Ratio 13.33 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 10
loc 75
rs 5.3217
cc 14
eloc 40
nc 54
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\Developer\Module\Observer;
4
5
use N98\Magento\Command\AbstractMagentoCommand;
6
use Symfony\Component\Console\Input\InputOption;
7
use Symfony\Component\Console\Input\InputArgument;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use N98\Util\Console\Helper\Table\Renderer\RendererFactory;
11
12
class ListCommand extends AbstractMagentoCommand
13
{
14
    const SORT_WARNING_MESSAGE = '<warning>Sorting observers is a bad idea, call-order is important.</warning>';
15
16
    protected $areas = [
17
        'global',
18
        'adminhtml',
19
        'frontend',
20
        'crontab'
21
    ];
22
23
    protected function configure()
24
    {
25
        $this
26
            ->setName('dev:module:observer:list')
27
            ->setDescription('Lists all registered observers')
28
            ->addArgument(
29
                'event',
30
                InputArgument::OPTIONAL,
31
                'Filter observers for specific event.'
32
            )
33
            ->addArgument(
34
                'area',
35
                InputArgument::OPTIONAL,
36
                'Filter observers in specific area. One of [' . implode(',', $this->areas) . ']'
37
            )
38
            ->addOption(
39
                'format',
40
                null,
41
                InputOption::VALUE_OPTIONAL,
42
                'Output Format. One of [' . implode(',', RendererFactory::getFormats()) . ']'
43
            )
44
            ->addOption(
45
                'sort',
46
                null,
47
                InputOption::VALUE_NONE,
48
                'Sort output ascending by event name'
49
            );
50
    }
51
52
    /**
53
     * @param \Symfony\Component\Console\Input\InputInterface $input
54
     * @param \Symfony\Component\Console\Output\OutputInterface $output
55
     * @return int|void
56
     */
57
    protected function execute(InputInterface $input, OutputInterface $output)
58
    {
59
        $this->detectMagento($output);
60
        $this->initMagento();
61
62
        $area = $input->getArgument('area');
63
        $eventFilter = $input->getArgument('event');
64
65
        if (is_null($area) || !in_array($area, $this->areas)) {
66 View Code Duplication
            foreach ($this->areas as $key => $area) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
67
                $question[] = '<comment>[' . ($key + 1) . ']</comment> ' . $area . PHP_EOL;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$question was never initialized. Although not strictly required by PHP, it is generally a good practice to add $question = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
68
            }
69
70
            $question[] = '<question>Please select an area:</question>';
0 ignored issues
show
Bug introduced by
The variable $question 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...
71
72 View Code Duplication
            $area = $this->getHelper('dialog')->askAndValidate($output, $question, function ($areaIndex) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
73
                if (!in_array($areaIndex, range(1, count($this->areas)))) {
74
                    throw new \InvalidArgumentException('Invalid selection.');
75
                }
76
77
                return $this->areas[$areaIndex - 1];
78
            });
79
        }
80
81
        if ($input->getOption('format') === null) {
82
            $sectionHeader = 'Observers in [' . $area . '] area';
83
84
            if (!is_null($eventFilter)) {
85
                $sectionHeader .= ' registered for [' . $eventFilter . '] event';
86
            }
87
88
            $this->writeSection($output, $sectionHeader);
89
        }
90
91
        $observerConfig = $this->getObjectManager()
92
                            ->get('\Magento\Framework\Event\Config\Reader')
93
                            ->read($area);
94
95
        if (true === $input->getOption('sort')) {
96
            /**
97
             * n98-magerun comment:
98
             *  sorting for Observers is a bad idea because the order in which observers will be called is important.
99
             */
100
            if ($input->getOption('format') === null) {
101
                $output->writeln(self::SORT_WARNING_MESSAGE);
102
            }
103
104
            ksort($observerConfig);
105
        }
106
107
        $table = [];
108
109
        foreach ($observerConfig as $eventName => $observers) {
110
            $firstObserver = true;
111
112
            if (!is_null($eventFilter) && $eventName != $eventFilter) {
113
                continue;
114
            }
115
116
            foreach ($observers as $observerName => $observerData) {
117
                if ($firstObserver) {
118
                    $firstObserver = !$firstObserver;
119
                    $table[] = [$eventName, $observerName, $observerData['instance'] . '::' . $observerData['name']];
120
                } else {
121
                    $table[] = ['', $observerName, $observerData['instance'] . '::' . $observerData['name']];
122
                }
123
            }
124
        }
125
126
        // @todo Output is a bit ugly!?
127
        $this->getHelper('table')
128
                ->setHeaders(['Event', 'Observer name', 'Fires'])
129
                ->setRows($table)
130
                ->renderByFormat($output, $table, $input->getOption('format'));
131
    }
132
}
133