Completed
Push — master ( 29ee36...92bd35 )
by Tom
03:51
created

AbstractCronCommand::askJobCode()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 22
Code Lines 13

Duplication

Lines 3
Ratio 13.64 %

Importance

Changes 0
Metric Value
dl 3
loc 22
rs 9.2
c 0
b 0
f 0
cc 3
eloc 13
nc 2
nop 3
1
<?php
2
3
namespace N98\Magento\Command\System\Cron;
4
5
use N98\Magento\Command\AbstractMagentoCommand;
6
use Symfony\Component\Console\Helper\DialogHelper;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Output\OutputInterface;
9
10
abstract class AbstractCronCommand extends AbstractMagentoCommand
11
{
12
    /**
13
     * @var \Magento\Framework\App\State
14
     */
15
    protected $state;
16
17
    /**
18
     * @var \Magento\Cron\Model\ConfigInterface
19
     */
20
    protected $cronConfig;
21
22
    /**
23
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
24
     */
25
    protected $scopeConfig;
26
27
    /**
28
     * @var \Magento\Cron\Model\ResourceModel\Schedule\Collection
29
     */
30
    protected $cronScheduleCollection;
31
32
    /**
33
     * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
34
     */
35
    protected $timezone;
36
37
    /**
38
     * @param \Magento\Framework\App\State $state
39
     * @param \Magento\Framework\Event\ManagerInterface $eventManager
40
     * @param \Magento\Cron\Model\ConfigInterface $cronConfig
41
     * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
42
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
43
     * @param \Magento\Cron\Model\ResourceModel\Schedule\Collection $cronScheduleCollection
44
     */
45
    public function inject(
46
        \Magento\Framework\App\State $state,
47
        \Magento\Framework\Event\ManagerInterface $eventManager,
0 ignored issues
show
Unused Code introduced by
The parameter $eventManager 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...
48
        \Magento\Cron\Model\ConfigInterface $cronConfig,
49
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone,
50
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
51
        \Magento\Cron\Model\ResourceModel\Schedule\Collection $cronScheduleCollection
52
    ) {
53
        $this->state = $state;
54
        $this->cronConfig = $cronConfig;
55
        $this->scopeConfig = $scopeConfig;
56
        $this->cronScheduleCollection = $cronScheduleCollection;
57
        $this->timezone = $timezone;
58
    }
59
60
    /**
61
     * @return array
62
     */
63
    protected function getJobs()
64
    {
65
        $table = array();
66
67
        $jobs = $this->cronConfig->getJobs();
68
69
        foreach ($jobs as $jobGroupCode => $jobGroup) {
70
            foreach ($jobGroup as $job) {
71
                $row = [
72
                    'Job'   => isset($job['name']) ? $job['name'] : null,
73
                    'Group' => $jobGroupCode,
74
                ];
75
76
                $row = $row + $this->getSchedule($job);
77
78
                $table[] = $row;
79
            }
80
        }
81
82
        usort($table, function ($a, $b) {
83
            return strcmp($a['Job'], $b['Job']);
84
        });
85
86
        return $table;
87
    }
88
89
    /**
90
     * @param string $jobCode
91
     * @return array
92
     */
93
    protected function getJobConfig($jobCode)
94
    {
95
        foreach ($this->cronConfig->getJobs() as $jobGroup) {
96
            foreach ($jobGroup as $job) {
97
                if ($job['name'] == $jobCode) {
98
                    return $job;
99
                }
100
            }
101
        }
102
103
        return [];
104
    }
105
106
    /**
107
     * @param array $job
108
     * @return array
109
     */
110
    protected function getSchedule(array $job)
111
    {
112
        if (isset($job['schedule'])) {
113
            $expr = $job['schedule'];
114
            if ($expr == 'always') {
115
                return ['m' => '*', 'h' => '*', 'D' => '*', 'M' => '*', 'WD' => '*'];
116
            }
117
118
            $schedule = $this->getObjectManager()->create('Magento\Cron\Model\Schedule');
119
            $schedule->setCronExpr($expr);
120
            $array = $schedule->getCronExprArr();
121
122
            return [
123
                'm'  => $array[0],
124
                'h'  => $array[1],
125
                'D'  => $array[2],
126
                'M'  => $array[3],
127
                'WD' => $array[4],
128
            ];
129
        }
130
131
        return ['m' => '-', 'h' => '-', 'D' => '-', 'M' => '-', 'WD' => '-'];
132
    }
133
134
    /**
135
     * @param InputInterface $input
136
     * @param OutputInterface $output
137
     * @param array $jobs
138
     * @return string
139
     * @throws \InvalidArgumentException
140
     * @throws \Exception
141
     */
142
    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...
143
    {
144 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...
145
            $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...
146
        }
147
        $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...
148
149
        /** @var $dialog DialogHelper */
150
        $dialog = $this->getHelper('dialog');
151
        $jobCode = $dialog->askAndValidate(
152
            $output,
153
            $question,
154
            function ($typeInput) use ($jobs) {
155
                if (!isset($jobs[$typeInput - 1])) {
156
                    throw new \InvalidArgumentException('Invalid job');
157
                }
158
                return $jobs[$typeInput - 1]['Job'];
159
            }
160
        );
161
162
        return $jobCode;
163
    }
164
165
    /**
166
     * @param InputInterface $input
167
     * @param OutputInterface $output
168
     * @return array
169
     */
170
    protected function getJobForExecuteMethod(InputInterface $input, OutputInterface $output)
171
    {
172
        $jobCode = $input->getArgument('job');
173
        $jobs = $this->getJobs();
174
175
        if (!$jobCode) {
176
            $this->writeSection($output, 'Cronjob');
177
            $jobCode = $this->askJobCode($input, $output, $jobs);
178
        }
179
180
        $jobConfig = $this->getJobConfig($jobCode);
181
182
        if (empty($jobCode) || !isset($jobConfig['instance'])) {
183
            throw new \InvalidArgumentException('No job config found!');
184
        }
185
186
        $model = $this->getObjectManager()->get($jobConfig['instance']);
187
188
        if (!$model || !is_callable(array($model, $jobConfig['method']))) {
189
            throw new \RuntimeException(
190
                sprintf(
191
                    'Invalid callback: %s::%s does not exist',
192
                    $jobConfig['instance'],
193
                    $jobConfig['method']
194
                )
195
            );
196
        }
197
198
        return array($jobCode, $jobConfig, $model);
199
    }
200
}
201