RunCommand   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 117
Duplicated Lines 2.56 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 11
c 4
b 1
f 0
lcom 1
cbo 3
dl 3
loc 117
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
B execute() 0 58 7
A askJobCode() 3 22 3
A configure() 0 12 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace N98\Magento\Command\System\Cron;
4
5
use Symfony\Component\Console\Helper\DialogHelper;
6
use Symfony\Component\Console\Input\InputArgument;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Output\OutputInterface;
9
use Magento\Cron\Model\Schedule;
10
11
class RunCommand extends AbstractCronCommand
12
{
13
    const REGEX_RUN_MODEL = '#^([a-z0-9_]+/[a-z0-9_]+)::([a-z0-9_]+)$#i';
14
    /**
15
     * @var array
16
     */
17
    protected $infos;
18
19
    protected function configure()
20
    {
21
        $this
22
            ->setName('sys:cron:run')
23
            ->addArgument('job', InputArgument::OPTIONAL, 'Job code')
24
            ->setDescription('Runs a cronjob by job code');
25
        $help = <<<HELP
26
If no `job` argument is passed you can select a job from a list.
27
See it in action: http://www.youtube.com/watch?v=QkzkLgrfNaM
28
HELP;
29
        $this->setHelp($help);
30
    }
31
32
    /**
33
     * @param InputInterface $input
34
     * @param OutputInterface $output
35
     * @throws \Exception
36
     * @return int|void
37
     */
38
    protected function execute(InputInterface $input, OutputInterface $output)
39
    {
40
        $jobCode = $input->getArgument('job');
41
        $jobs = $this->getJobs();
42
43
        if (!$jobCode) {
44
            $this->writeSection($output, 'Cronjob');
45
            $jobCode = $this->askJobCode($input, $output, $jobs);
46
        }
47
48
        $jobConfig = $this->getJobConfig($jobCode);
49
50
        if (empty($jobCode) || !isset($jobConfig['instance'])) {
51
            throw new \InvalidArgumentException('No job config found!');
52
        }
53
54
        $model = $this->getObjectManager()->get($jobConfig['instance']);
55
56
        if (!$model || !is_callable(array($model, $jobConfig['method']))) {
57
            throw new \RuntimeException(
58
                sprintf(
59
                    'Invalid callback: %s::%s does not exist',
60
                    $jobConfig['instance'],
61
                    $jobConfig['method']
62
                )
63
            );
64
        }
65
66
        $callback = array($model, $jobConfig['method']);
67
68
        $output->write(
69
            '<info>Run </info><comment>' . $jobConfig['instance'] . '::' . $jobConfig['method'] . '</comment> '
70
        );
71
72
        try {
73
            $schedule = $this->_cronScheduleCollection->getNewEmptyItem();
74
            $schedule
75
                ->setJobCode($jobCode)
76
                ->setStatus(Schedule::STATUS_RUNNING)
77
                ->setExecutedAt(strftime('%Y-%m-%d %H:%M:%S', time()))
78
                ->save();
79
80
            $this->_state->emulateAreaCode('crontab', $callback, array($schedule));
81
82
            $schedule
83
                ->setStatus(Schedule::STATUS_SUCCESS)
84
                ->setFinishedAt(strftime('%Y-%m-%d %H:%M:%S', time()))
85
                ->save();
86
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class N98\Magento\Command\System\Cron\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
87
            $schedule
88
                ->setStatus(Schedule::STATUS_ERROR)
89
                ->setMessages($e->getMessage())
90
                ->setFinishedAt(strftime('%Y-%m-%d %H:%M:%S', time()))
91
                ->save();
92
        }
93
94
        $output->writeln('<info>done</info>');
95
    }
96
97
    /**
98
     * @param InputInterface $input
99
     * @param OutputInterface $output
100
     * @param array $jobs
101
     * @return string
102
     * @throws \InvalidArgumentException
103
     * @throws \Exception
104
     */
105
    protected function askJobCode(InputInterface $input, OutputInterface $output, $jobs)
0 ignored issues
show
Unused Code introduced by
The parameter $input 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...
106
    {
107 View Code Duplication
        foreach ($jobs as $key => $job) {
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...
108
            $question[] = '<comment>[' . ($key + 1) . ']</comment> ' . $job['Job'] . 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...
109
        }
110
        $question[] = '<question>Please select job: </question>' . PHP_EOL;
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...
111
112
        /** @var $dialog DialogHelper */
113
        $dialog = $this->getHelper('dialog');
114
        $jobCode = $dialog->askAndValidate(
115
            $output,
116
            $question,
117
            function ($typeInput) use ($jobs) {
118
                if (!isset($jobs[$typeInput - 1])) {
119
                    throw new \InvalidArgumentException('Invalid job');
120
                }
121
                return $jobs[$typeInput - 1]['Job'];
122
            }
123
        );
124
125
        return $jobCode;
126
    }
127
}
128