Passed
Push — master ( 76636e...a7cce5 )
by Kevin
03:12
created

ScheduleListCommand::renderIssues()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.0312

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 14
ccs 7
cts 8
cp 0.875
rs 10
cc 4
nc 4
nop 2
crap 4.0312
1
<?php
2
3
namespace Zenstruck\ScheduleBundle\Command;
4
5
use Lorisleiva\CronTranslator\CronParsingException;
6
use Lorisleiva\CronTranslator\CronTranslator;
7
use Symfony\Component\Console\Command\Command;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Input\StringInput;
10
use Symfony\Component\Console\Output\OutputInterface;
11
use Symfony\Component\Console\Style\SymfonyStyle;
12
use Zenstruck\ScheduleBundle\Schedule;
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 10
    public function __construct(ScheduleRunner $scheduleRunner, ExtensionHandlerRegistry $handlerRegistry)
29
    {
30 10
        $this->scheduleRunner = $scheduleRunner;
31 10
        $this->handlerRegistry = $handlerRegistry;
32
33 10
        parent::__construct();
34 10
    }
35
36 10
    protected function configure(): void
37
    {
38
        $this
39 10
            ->setDescription('List configured scheduled tasks')
40 10
            ->addOption('detail', null, null, 'Show detailed task list')
41 10
            ->setHelp(<<<EOF
42 10
Exit code 0: no issues.
43
Exit code 1: some issues.
44
EOF
45
            )
46
        ;
47 10
    }
48
49 10
    protected function execute(InputInterface $input, OutputInterface $output): int
50
    {
51 10
        $schedule = $this->scheduleRunner->buildSchedule();
52
53 10
        if (0 === \count($schedule->all())) {
54 1
            throw new \RuntimeException('No scheduled tasks configured.');
55
        }
56
57 9
        $io = new SymfonyStyle($input, $output);
58
59 9
        $io->title(\sprintf('<info>%d</info> Scheduled Task%s Configured', \count($schedule->all()), \count($schedule->all()) > 1 ? 's' : ''));
60
61 9
        $exit = $input->getOption('detail') ? $this->renderDetail($schedule, $io) : $this->renderTable($schedule, $io);
62
63 9
        $this->renderExtenstions($io, 'Schedule', $schedule->getExtensions());
64
65 9
        $scheduleIssues = \iterator_to_array($this->getScheduleIssues($schedule), false);
66
67 9
        if ($issueCount = \count($scheduleIssues)) {
68 3
            $io->warning(\sprintf('%d issue%s with schedule:', $issueCount, $issueCount > 1 ? 's' : ''));
69
70 3
            $exit = 1;
71
        }
72
73 9
        $this->renderIssues($io, ...$scheduleIssues);
74
75 9
        if (0 === $exit) {
76 4
            $io->success('No schedule or task issues.');
77
        }
78
79 9
        return $exit;
80
    }
81
82 3
    private function renderDetail(Schedule $schedule, SymfonyStyle $io): int
83
    {
84 3
        $exit = 0;
85
86 3
        foreach ($schedule->all() as $i => $task) {
87 3
            $io->section(\sprintf('(%d/%d) %s', $i + 1, \count($schedule->all()), $task));
88
89 3
            $details = [];
90
91 3
            foreach ($task->getContext() as $key => $value) {
92 1
                $details[] = [$key => $value];
93
            }
94
95 3
            $details[] = ['Task ID' => $task->getId()];
96 3
            $details[] = ['Task Class' => \get_class($task)];
97
98 3
            $details[] = [$task->getExpression()->isHashed() ? 'Calculated Frequency' : 'Frequency' => $this->renderFrequency($task)];
99
100 3
            if ($task->getExpression()->isHashed()) {
101 1
                $details[] = ['Raw Frequency' => $task->getExpression()->getRawValue()];
102
            }
103
104 3
            $details[] = ['Next Run' => $task->getNextRun()->format('D, M d, Y @ g:i (e O)')];
105
106 3
            $this->renderDefinitionList($io, $details);
107 3
            $this->renderExtenstions($io, 'Task', $task->getExtensions());
108
109 3
            $issues = \iterator_to_array($this->getTaskIssues($task), false);
110
111 3
            if ($issueCount = \count($issues)) {
112 1
                $io->warning(\sprintf('%d issue%s with this task:', $issueCount, $issueCount > 1 ? 's' : ''));
113
            }
114
115 3
            $this->renderIssues($io, ...$issues);
116
117 3
            if ($issueCount > 0) {
118 1
                $exit = 1;
119
            }
120
        }
121
122 3
        return $exit;
123
    }
124
125
    /**
126
     * BC - Symfony 4.4 added SymfonyStyle::definitionList().
127
     */
128 3
    private function renderDefinitionList(SymfonyStyle $io, array $list): void
129
    {
130 3
        if (\method_exists($io, 'definitionList')) {
131 3
            $io->definitionList(...$list);
132
133 3
            return;
134
        }
135
136
        $io->listing(\array_map(
137
            function(array $line) {
138
                return \sprintf('<info>%s:</info> %s', \array_keys($line)[0], \array_values($line)[0]);
139
            },
140
            $list
141
        ));
142
    }
143
144 7
    private function renderTable(Schedule $schedule, SymfonyStyle $io): int
145
    {
146
        /** @var \Throwable[] $taskIssues */
147 7
        $taskIssues = [];
148 7
        $rows = [];
149
150 7
        foreach ($schedule->all() as $task) {
151 7
            $issues = \iterator_to_array($this->getTaskIssues($task), false);
152 7
            $taskIssues[] = $issues;
153
154 7
            $rows[] = [
155 7
                \count($issues) ? "<error>[!] {$task->getType()}</error>" : $task->getType(),
156 7
                $this->getHelper('formatter')->truncate($task->getDescription(), 50),
157 7
                \count($task->getExtensions()),
158 7
                $this->renderFrequency($task),
159 7
                $task->getNextRun()->format(DATE_ATOM),
160
            ];
161
        }
162
163 7
        $taskIssues = \array_merge([], ...$taskIssues);
164
165 7
        $io->table(['Type', 'Description', 'Extensions', 'Frequency', 'Next Run'], $rows);
166
167 7
        if ($issueCount = \count($taskIssues)) {
168 3
            $io->warning(\sprintf('%d task issue%s:', $issueCount, $issueCount > 1 ? 's' : ''));
169
        }
170
171 7
        $this->renderIssues($io, ...$taskIssues);
172
173 7
        $io->note('For more details, run php bin/console schedule:list --detail');
174
175 7
        return \count($taskIssues) ? 1 : 0;
176
    }
177
178
    /**
179
     * @param object[] $extensions
180
     */
181 9
    private function renderExtenstions(SymfonyStyle $io, string $type, array $extensions): void
182
    {
183 9
        if (0 === $count = \count($extensions)) {
184 7
            return;
185
        }
186
187 2
        $io->comment(\sprintf('<info>%d</info> %s Extension%s:', $count, $type, $count > 1 ? 's' : ''));
188 2
        $io->listing(\array_map(
189
            function(object $extension) {
190 2
                if (\method_exists($extension, '__toString')) {
191 2
                    return \sprintf('%s <comment>(%s)</comment>',
192 2
                        \strtr($extension, self::extensionHighlightMap()),
0 ignored issues
show
Bug introduced by
$extension of type object is incompatible with the type string expected by parameter $str of strtr(). ( Ignorable by Annotation )

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

192
                        \strtr(/** @scrutinizer ignore-type */ $extension, self::extensionHighlightMap()),
Loading history...
193 2
                        \get_class($extension)
194
                    );
195
                }
196
197
                return \get_class($extension);
198 2
            },
199 2
            $extensions
200
        ));
201 2
    }
202
203
    /**
204
     * @return \Throwable[]
205
     */
206 9
    private function getScheduleIssues(Schedule $schedule): iterable
207
    {
208 9
        foreach ($schedule->getExtensions() as $extension) {
209
            try {
210 2
                $this->handlerRegistry->handlerFor($extension);
211 2
            } catch (\Throwable $e) {
212 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...
213
            }
214
        }
215
216
        // check for duplicated task ids
217 9
        $tasks = [];
218
219 9
        foreach ($schedule->all() as $task) {
220 9
            $tasks[$task->getId()][] = $task;
221
        }
222
223 9
        foreach ($tasks as $taskGroup) {
224 9
            $count = \count($taskGroup);
225
226 9
            if (1 === $count) {
227 9
                continue;
228
            }
229
230 1
            $task = $taskGroup[0];
231
232 1
            yield new \LogicException(\sprintf('Task "%s" (%s) is duplicated %d times. Make their descriptions unique to fix.', $task, $task->getExpression(), $count));
233
        }
234 9
    }
235
236 2
    private static function extensionHighlightMap(): array
237
    {
238
        return [
239 2
            Task::SUCCESS => \sprintf('<info>%s</info>', Task::SUCCESS),
240 2
            Schedule::SUCCESS => \sprintf('<info>%s</info>', Schedule::SUCCESS),
241 2
            Task::FAILURE => \sprintf('<error>%s</error>', Task::FAILURE),
242 2
            Schedule::FAILURE => \sprintf('<error>%s</error>', Schedule::FAILURE),
243
        ];
244
    }
245
246
    /**
247
     * @return \Throwable[]
248
     */
249 9
    private function getTaskIssues(Task $task): iterable
250
    {
251
        try {
252 9
            $this->scheduleRunner->runnerFor($task);
253 4
        } catch (\Throwable $e) {
254 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...
255
        }
256
257 9
        if ($task instanceof CommandTask && $application = $this->getApplication()) {
258
            try {
259 4
                $definition = $task->createCommand($application)->getDefinition();
260 1
                $definition->addOptions($application->getDefinition()->getOptions());
261 1
                $input = new StringInput($task->getArguments());
262
263 1
                $input->bind($definition);
264 4
            } catch (\Throwable $e) {
265 4
                yield $e;
266
            }
267
        }
268
269 9
        foreach ($task->getExtensions() as $extension) {
270
            try {
271 2
                $this->handlerRegistry->handlerFor($extension);
272 2
            } catch (\Throwable $e) {
273 2
                yield $e;
274
            }
275
        }
276 9
    }
277
278 9
    private function renderIssues(SymfonyStyle $io, \Throwable ...$issues): void
279
    {
280 9
        foreach ($issues as $issue) {
281 5
            if (OutputInterface::VERBOSITY_NORMAL === $io->getVerbosity()) {
282 4
                $io->error($issue->getMessage());
283
284 4
                continue;
285
            }
286
287
            // BC - Symfony 4.4 deprecated Application::renderException()
288 1
            if (\method_exists($this->getApplication(), 'renderThrowable')) {
289 1
                $this->getApplication()->renderThrowable($issue, $io);
290
            } else {
291
                $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

291
                $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...
292
            }
293
        }
294 9
    }
295
296 9
    private function renderFrequency(Task $task): string
297
    {
298 9
        $expression = (string) $task->getExpression();
299
300 9
        if (!\class_exists(CronTranslator::class)) {
301
            return $expression;
302
        }
303
304
        try {
305 9
            return \sprintf('%s (%s)', $expression, CronTranslator::translate($expression));
306
        } catch (CronParsingException $e) {
307
            return $expression;
308
        }
309
    }
310
}
311