Passed
Push — master ( 323c76...ddad29 )
by Kevin
01:54
created

ScheduleListCommand   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 237
Duplicated Lines 0 %

Test Coverage

Coverage 94.92%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 42
eloc 115
c 2
b 0
f 1
dl 0
loc 237
rs 9.0399
ccs 112
cts 118
cp 0.9492

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A extensionHighlightMap() 0 7 1
A renderFrequency() 0 7 2
A getScheduleIssues() 0 7 3
A renderExtenstions() 0 15 3
B renderDetail() 0 42 8
A execute() 0 27 6
A configure() 0 6 1
A renderIssues() 0 14 4
B getTaskIssues() 0 25 7
A renderTable() 0 32 6

How to fix   Complexity   

Complex Class

Complex classes like ScheduleListCommand often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ScheduleListCommand, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Zenstruck\ScheduleBundle\Command;
4
5
use Lorisleiva\CronTranslator\CronTranslator;
6
use Symfony\Component\Console\Command\Command;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Input\StringInput;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\Console\Style\SymfonyStyle;
11
use Zenstruck\ScheduleBundle\Schedule;
12
use Zenstruck\ScheduleBundle\Schedule\Extension;
13
use Zenstruck\ScheduleBundle\Schedule\Extension\ExtensionHandlerRegistry;
14
use Zenstruck\ScheduleBundle\Schedule\ScheduleRunner;
15
use Zenstruck\ScheduleBundle\Schedule\Task;
16
use Zenstruck\ScheduleBundle\Schedule\Task\CommandTask;
17
18
/**
19
 * @author Kevin Bond <[email protected]>
20
 */
21
final class ScheduleListCommand extends Command
22
{
23
    protected static $defaultName = 'schedule:list';
24
25
    private $scheduleRunner;
26
    private $handlerRegistry;
27
28 5
    public function __construct(ScheduleRunner $scheduleRunner, ExtensionHandlerRegistry $handlerRegistry)
29
    {
30 5
        $this->scheduleRunner = $scheduleRunner;
31 5
        $this->handlerRegistry = $handlerRegistry;
32
33 5
        parent::__construct();
34 5
    }
35
36 5
    protected function configure(): void
37
    {
38
        $this
39 5
            ->setDescription('List configured scheduled tasks')
40 5
            ->addOption('detail', null, null, 'Show detailed task list')
41 5
            ->setHelp(<<<EOF
42 5
Exit code 0: no issues.
43
Exit code 1: some issues.
44
EOF
45
            )
46
        ;
47 5
    }
48
49 5
    protected function execute(InputInterface $input, OutputInterface $output): int
50
    {
51 5
        $schedule = $this->scheduleRunner->buildSchedule();
52
53 5
        if (0 === \count($schedule->all())) {
54 1
            throw new \RuntimeException('No scheduled tasks configured.');
55
        }
56
57 4
        $io = new SymfonyStyle($input, $output);
58
59 4
        $io->title(\sprintf('<info>%d</info> Scheduled Task%s Configured', \count($schedule->all()), \count($schedule->all()) > 1 ? 's' : ''));
60
61 4
        $exit = $input->getOption('detail') ? $this->renderDetail($schedule, $io) : $this->renderTable($schedule, $io);
62
63 4
        $this->renderExtenstions($io, 'Schedule', $schedule->getExtensions());
64
65 4
        $scheduleIssues = \iterator_to_array($this->getScheduleIssues($schedule));
66
67 4
        if ($issueCount = \count($scheduleIssues)) {
68 2
            $io->warning(\sprintf('%d issue%s with schedule:', $issueCount, $issueCount > 1 ? 's' : ''));
69
70 2
            $exit = 1;
71
        }
72
73 4
        $this->renderIssues($io, ...$scheduleIssues);
74
75 4
        return $exit;
76
    }
77
78 1
    private function renderDetail(Schedule $schedule, SymfonyStyle $io): int
79
    {
80 1
        $exit = 0;
81
82 1
        foreach ($schedule->all() as $i => $task) {
83 1
            $io->section(\sprintf('(%d/%d) %s: %s', $i + 1, \count($schedule->all()), $task->getType(), $task));
84
85 1
            if ($task instanceof CommandTask && $arguments = $task->getArguments()) {
0 ignored issues
show
Unused Code introduced by
The assignment to $arguments is dead and can be removed.
Loading history...
86 1
                $io->comment("Arguments: <comment>{$task->getArguments()}</comment>");
87
            }
88
89
            // BC - Symfony 4.4 added SymfonyStyle::definitionList()
90 1
            if (\method_exists($io, 'definitionList')) {
91 1
                $io->definitionList(
92 1
                    ['Class' => \get_class($task)],
93 1
                    ['Frequency' => $this->renderFrequency($task)],
94 1
                    ['Next Run' => $task->getNextRun()->format('D, M d, Y @ g:i (e O)')]
95
                );
96
            } else {
97
                $io->listing([
98
                    'Class: '.\get_class($task),
99
                    'Frequency: '.$this->renderFrequency($task),
100
                    'Next Run: '.$task->getNextRun()->format('D, M d, Y @ g:i (e O)'),
101
                ]);
102
            }
103
104 1
            $this->renderExtenstions($io, 'Task', $task->getExtensions());
105
106 1
            $issues = \iterator_to_array($this->getTaskIssues($task));
107
108 1
            if ($issueCount = \count($issues)) {
109 1
                $io->warning(\sprintf('%d issue%s with this task:', $issueCount, $issueCount > 1 ? 's' : ''));
110
            }
111
112 1
            $this->renderIssues($io, ...$issues);
113
114 1
            if ($issueCount > 0) {
115 1
                $exit = 1;
116
            }
117
        }
118
119 1
        return $exit;
120
    }
121
122 3
    private function renderTable(Schedule $schedule, SymfonyStyle $io): int
123
    {
124
        /** @var \Throwable[] $taskIssues */
125 3
        $taskIssues = [];
126 3
        $rows = [];
127
128 3
        foreach ($schedule->all() as $task) {
129 3
            $issues = \iterator_to_array($this->getTaskIssues($task));
130 3
            $taskIssues[] = $issues;
131
132 3
            $rows[] = [
133 3
                \count($issues) ? "<error>[!] {$task->getType()}</error>" : $task->getType(),
134 3
                $this->getHelper('formatter')->truncate($task, 50),
135 3
                \count($task->getExtensions()),
136 3
                $this->renderFrequency($task),
137 3
                $task->getNextRun()->format(DATE_ATOM),
138
            ];
139
        }
140
141 3
        $taskIssues = \array_merge([], ...$taskIssues);
142
143 3
        $io->table(['Type', 'Task', 'Extensions', 'Frequency', 'Next Run'], $rows);
144
145 3
        if ($issueCount = \count($taskIssues)) {
146 3
            $io->warning(\sprintf('%d task issue%s:', $issueCount, $issueCount > 1 ? 's' : ''));
147
        }
148
149 3
        $this->renderIssues($io, ...$taskIssues);
150
151 3
        $io->note('For more details, run php bin/console schedule:list --detail');
152
153 3
        return \count($taskIssues) ? 1 : 0;
154
    }
155
156
    /**
157
     * @param Extension[] $extensions
158
     */
159 4
    private function renderExtenstions(SymfonyStyle $io, string $type, array $extensions): void
160
    {
161 4
        if (0 === $count = \count($extensions)) {
162 2
            return;
163
        }
164
165 2
        $io->comment(\sprintf('<info>%d</info> %s Extension%s:', $count, $type, $count > 1 ? 's' : ''));
166 2
        $io->listing(\array_map(
167
            function (Extension $extension) {
168 2
                return \sprintf('%s <comment>(%s)</comment>',
169 2
                    \strtr($extension, self::extensionHighlightMap()),
170 2
                    \get_class($extension)
171
                );
172 2
            },
173 2
            $extensions
174
        ));
175 2
    }
176
177
    /**
178
     * @return \Throwable[]
179
     */
180 4
    private function getScheduleIssues(Schedule $schedule): \Generator
181
    {
182 4
        foreach ($schedule->getExtensions() as $extension) {
183
            try {
184 2
                $this->handlerRegistry->handlerFor($extension);
185 2
            } catch (\Throwable $e) {
186 2
                yield $e;
0 ignored issues
show
Bug Best Practice introduced by
The expression yield $e returns the type Generator which is incompatible with the documented return type Throwable[].
Loading history...
187
            }
188
        }
189 4
    }
190
191 2
    private static function extensionHighlightMap(): array
192
    {
193
        return [
194 2
            Extension::TASK_SUCCESS => \sprintf('<info>%s</info>', Extension::TASK_SUCCESS),
195 2
            Extension::SCHEDULE_SUCCESS => \sprintf('<info>%s</info>', Extension::SCHEDULE_SUCCESS),
196 2
            Extension::TASK_FAILURE => \sprintf('<error>%s</error>', Extension::TASK_FAILURE),
197 2
            Extension::SCHEDULE_FAILURE => \sprintf('<error>%s</error>', Extension::SCHEDULE_FAILURE),
198
        ];
199
    }
200
201
    /**
202
     * @return \Throwable[]
203
     */
204 4
    private function getTaskIssues(Task $task): \Generator
205
    {
206
        try {
207 4
            $this->scheduleRunner->runnerFor($task);
208 4
        } catch (\Throwable $e) {
209 4
            yield $e;
0 ignored issues
show
Bug Best Practice introduced by
The expression yield $e returns the type Generator which is incompatible with the documented return type Throwable[].
Loading history...
210
        }
211
212 4
        if ($task instanceof CommandTask && $application = $this->getApplication()) {
213
            try {
214 4
                $definition = $task->createCommand($application)->getDefinition();
215 1
                $definition->addOptions($application->getDefinition()->getOptions());
216 1
                $input = new StringInput($task->getArguments());
217
218 1
                $input->bind($definition);
219 4
            } catch (\Throwable $e) {
220 4
                yield $e;
221
            }
222
        }
223
224 4
        foreach ($task->getExtensions() as $extension) {
225
            try {
226 2
                $this->handlerRegistry->handlerFor($extension);
227 2
            } catch (\Throwable $e) {
228 2
                yield $e;
229
            }
230
        }
231 4
    }
232
233 4
    private function renderIssues(SymfonyStyle $io, \Throwable ...$issues): void
234
    {
235 4
        foreach ($issues as $issue) {
236 4
            if (OutputInterface::VERBOSITY_NORMAL === $io->getVerbosity()) {
237 3
                $io->error($issue->getMessage());
238
239 3
                continue;
240
            }
241
242
            // BC - Symfony 4.4 deprecated Application::renderException()
243 1
            if (\method_exists($this->getApplication(), 'renderThrowable')) {
244 1
                $this->getApplication()->renderThrowable($issue, $io);
245
            } else {
246
                $this->getApplication()->renderException($issue, $io);
0 ignored issues
show
Bug introduced by
The method renderException() does not exist on Symfony\Component\Console\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

246
                $this->getApplication()->/** @scrutinizer ignore-call */ renderException($issue, $io);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
247
            }
248
        }
249 4
    }
250
251 4
    private function renderFrequency(Task $task): string
252
    {
253 4
        if (!\class_exists(CronTranslator::class)) {
254
            return $task->getExpression();
255
        }
256
257 4
        return CronTranslator::translate($task->getExpression())." ({$task->getExpression()})";
258
    }
259
}
260