Repository navigation
Expand file tree
/
Copy pathProcessHelpCommand.php
More file actions
569 lines (483 loc) · 19.7 KB
/
Copy pathProcessHelpCommand.php
File metadata and controls
569 lines (483 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
<?php
declare(strict_types=1);
/*
* This file is part of the CleverAge/ProcessBundle package.
*
* Copyright (c) Clever-Age
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CleverAge\ProcessBundle\Command;
use CleverAge\ProcessBundle\Configuration\ProcessConfiguration;
use CleverAge\ProcessBundle\Configuration\TaskConfiguration;
use CleverAge\ProcessBundle\Exception\InvalidArgumentException;
use CleverAge\ProcessBundle\Exception\UnexpectedValueException;
use CleverAge\ProcessBundle\Model\BlockingTaskInterface;
use CleverAge\ProcessBundle\Model\FlushableTaskInterface;
use CleverAge\ProcessBundle\Model\IterableTaskInterface;
use CleverAge\ProcessBundle\Model\TaskInterface;
use CleverAge\ProcessBundle\Registry\ProcessConfigurationRegistry;
use CleverAge\ProcessBundle\Registry\TaskRegistry;
use CleverAge\ProcessBundle\Registry\TaskRegistryInterface;
use CleverAge\ProcessBundle\Task\Process\ProcessExecutorTask;
use CleverAge\ProcessBundle\Task\Process\ProcessLauncherTask;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Describe a process configuration
* This is a POC, waiting to evolve properly.
*
* @internal
*/
#[AsCommand(name: 'cleverage:process:help', description: 'Describe a process', )]
class ProcessHelpCommand extends Command
{
protected const CHAR_DOWN = '│';
protected const CHAR_MERGE = '┘';
protected const CHAR_MULTIMERGE = '┴─';
protected const CHAR_JUMP = '┿─';
protected const CHAR_HORIZ = '──';
protected const CHAR_MULTIEXPAND = '┬─';
protected const CHAR_EXPAND = '┐';
protected const CHAR_RECEIVE = '├─';
protected const CHAR_NODE = '■';
protected const BRANCH_SIZE = 2;
protected const INDENT_SIZE = 4;
protected TaskRegistryInterface $taskRegistry;
/**
* @deprecated since 5.4, only set when a container is passed to the constructor, will be removed in v6.0
*/
protected ?ContainerInterface $container = null;
public function __construct(
protected ProcessConfigurationRegistry $processConfigRegistry,
TaskRegistryInterface|ContainerInterface $taskRegistry,
) {
parent::__construct();
if ($taskRegistry instanceof ContainerInterface) {
trigger_deprecation(
'cleverage/process-bundle',
'5.4',
'Passing a service container to "%s::__construct()" is deprecated, pass a "%s" instead: the tasks are fetched from the service container. Only a "%s" will be accepted in v6.0.',
self::class,
TaskRegistry::class,
TaskRegistry::class,
);
// @phpstan-ignore property.deprecated (kept for BC until v6.0)
$this->container = $taskRegistry;
// Same behaviour as before the task registry: any service of the container
$taskRegistry = new TaskRegistry($taskRegistry, $taskRegistry);
}
$this->taskRegistry = $taskRegistry;
}
protected function configure(): void
{
// Shell completion: the codes of the processes, without resolving their configuration (getProcessConfigurations()
// logs the invalid ones, the log would be completed)
$this->addArgument('process_code', InputArgument::REQUIRED, 'The code of the process', null, fn (): array => $this->processConfigRegistry->getProcessCodes());
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->getFormatter()
->setStyle('fire', new OutputFormatterStyle('red'));
$processCode = $input->getArgument('process_code');
$process = $this->processConfigRegistry->getProcessConfiguration($processCode);
$output->writeln('<comment>Process: </comment>');
$output->writeln(str_repeat(' ', self::INDENT_SIZE).$processCode);
$output->writeln('');
if ('' !== $process->getDescription() && '0' !== $process->getDescription()) {
$output->writeln('<comment>Description:</comment>');
$output->writeln(str_repeat(' ', self::INDENT_SIZE).$process->getDescription());
$output->writeln('');
}
if ('' !== $process->getHelp() && '0' !== $process->getHelp()) {
$output->writeln('<comment>Help:</comment>');
$helpLines = array_filter(explode("\n", $process->getHelp()));
foreach ($helpLines as $helpLine) {
$output->writeln(str_repeat(' ', self::INDENT_SIZE).$helpLine);
}
$output->writeln('');
}
$output->writeln('<comment>Tasks tree:</comment>');
$branches = [];
$taskList = $process->getMainTaskGroup();
$remainingTasks = $taskList;
$totalBranches = \count($taskList);
for ($i = 0; $i < $totalBranches; ++$i) {
// Find the best task to display
// A numeric task code may be returned as an integer array key
$nextTaskCode = (string) $this->findBestNextTask($branches, $remainingTasks, $process);
$this->resolveBranchOutput($branches, $nextTaskCode, $process, $output);
// Remove the task from the remaining list
$remainingTasks = array_values(array_filter($remainingTasks, static fn ($task): bool => $task !== $nextTaskCode));
}
$branches = array_filter($branches);
if ([] !== $branches) {
$branchStr = '['.implode(', ', $branches).']';
$output->writeln("<error>All branches are not resolved : {$branchStr}</error>");
}
return Command::SUCCESS;
}
/**
* Try to find a best candidate for next display.
*
* @param array<int, string|null> $branches
* @param list<string> $taskList
*/
protected function findBestNextTask(
array $branches,
array $taskList,
ProcessConfiguration $process,
): int|string|null {
// Get resolvable tasks
$taskCandidates = [];
foreach ($taskList as $taskCode) {
$task = $process->getTaskConfiguration($taskCode);
if ([] === $task->getPreviousTasksConfigurations()) {
return $taskCode;
}
// Check if task has all necessary ancestors in branches
$hasAllAncestors = array_reduce(
$task->getPreviousTasksConfigurations(),
static fn ($result, TaskConfiguration $prevTask): bool => $result && \in_array(
$prevTask->getCode(),
$branches,
true
),
true
);
if ($hasAllAncestors) {
$taskCandidates[] = $taskCode;
}
}
if ([] === $taskCandidates) {
throw new UnexpectedValueException('Cannot find a task to output');
}
// Try to find the task the most on the right
$taskWeights = [];
foreach ($taskCandidates as $taskCandidate) {
$weight = 0;
$task = $process->getTaskConfiguration($taskCandidate);
foreach ($task->getPreviousTasksConfigurations() as $prevTask) {
$key = array_search($prevTask->getCode(), $branches, true);
// Should never be non-numeric...
if (!is_numeric($key)) {
throw new UnexpectedValueException('Invalid key type');
}
$weight += $key;
}
if ([] !== $task->getPreviousTasksConfigurations()) {
$weight /= \count($task->getPreviousTasksConfigurations());
}
$taskWeights[$taskCandidate] = $weight;
}
arsort($taskWeights);
$bestCandidate = key($taskWeights);
$bestWeight = $taskWeights[$bestCandidate];
$equalWeights = array_filter($taskWeights, static fn ($item): bool => $item === $bestWeight);
if (1 === \count($equalWeights)) {
return $bestCandidate;
}
// If a few tasks have the same weight, return the tasks with the lowest number of children
$childCounts = [];
foreach (array_keys($equalWeights) as $taskCode) {
$task = $process->getTaskConfiguration($taskCode);
$childCounts[$taskCode] = $this->getTaskChildrenCount($task);
}
asort($childCounts);
return key($childCounts);
}
/**
* Get the number of children (error or not) of a task.
*/
protected function getTaskChildrenCount(TaskConfiguration $task): int
{
$count = 0;
foreach ($task->getNextTasksConfigurations() as $nextTasksConfiguration) {
$count += 1 + $this->getTaskChildrenCount($nextTasksConfiguration);
}
foreach ($task->getErrorTasksConfigurations() as $errorTasksConfiguration) {
$count += 1 + $this->getTaskChildrenCount($errorTasksConfiguration);
}
return $count;
}
/**
* Merge needed branches, display a task node, split following needed branches.
*
* @param array<int, string|null> $branches
*/
protected function resolveBranchOutput(
array &$branches,
string $taskCode,
ProcessConfiguration $process,
OutputInterface $output,
): void {
$task = $process->getTaskConfiguration($taskCode);
$branchesToMerge = [];
$gapBranches = [];
$origin = null;
$final = null;
// Get unique previous branches
$previousTasks = [];
foreach ($task->getPreviousTasksConfigurations() as $previousTasksConfiguration) {
$previousTasks[$previousTasksConfiguration->getCode()] = $previousTasksConfiguration;
}
// Check previous branches
if ([] === $previousTasks) {
$branches[] = $task->getCode();
} elseif (1 === \count($previousTasks)) {
$prevTask = array_first($previousTasks)
->getCode();
foreach (array_reverse($branches, true) as $i => $branchTask) {
if ($branchTask === $prevTask) {
$branches[$i] = $taskCode;
break;
}
}
} else {
foreach ($previousTasks as $prevTask) {
$foundBranch = false;
foreach (array_reverse($branches, true) as $i => $branchTask) {
if ($branchTask === $prevTask->getCode()) {
$branchesToMerge[] = $i;
$foundBranch = true;
break;
}
}
if (!$foundBranch) {
$output->writeln(
"<error>Could not find previous branch : {$taskCode} depends on {$prevTask->getCode()}</error>"
);
}
}
// Don't touch the 1st branch to merge
sort($branchesToMerge);
$gapFrom = null;
foreach ($branchesToMerge as $i) {
$gapTo = $i;
if (null !== $gapFrom) {
for ($j = $gapFrom + 1; $j < $gapTo; ++$j) {
$gapBranches[] = $j;
}
}
$gapFrom = $i;
}
$origin = array_shift($branchesToMerge);
$final = $gapFrom;
if (null === $origin) {
// No previous branch found (an error has been displayed): open a new branch
$branches[] = $taskCode;
} else {
$branches[$origin] = $taskCode;
}
}
// Merge branches
if ([] !== $branchesToMerge) {
$this->writeBranches($output, $branches);
$this->writeBranches(
$output,
$branches,
'',
static fn ($taskCode, $i): bool => \in_array($i, $branchesToMerge, true)
|| \in_array($i, $gapBranches, true)
|| $i === $origin,
static function ($taskCode, $i) use ($gapBranches, $origin, $final, $branches): string {
if ($i === $origin) {
return self::CHAR_RECEIVE;
}
if (\in_array($i, $gapBranches, true)) {
if (null !== $branches[$i]) {
return self::CHAR_JUMP;
}
return self::CHAR_HORIZ;
}
if ($i === $final) {
return self::CHAR_MERGE;
}
return self::CHAR_MULTIMERGE;
}
);
foreach (array_keys($branches) as $i) {
if (\in_array($i, $branchesToMerge, true)) {
$branches[$i] = null;
}
}
$this->writeBranches($output, $branches);
}
// Cleanup empty trailing branches
foreach (array_reverse($branches, true) as $i => $branchTask) {
if (null !== $branchTask) {
$branches = \array_slice($branches, 0, $i + 1);
break;
}
}
// Write main line
$nodeStr = self::CHAR_NODE;
if ($task->isInErrorBranch()) {
$nodeStr = "<fire>{$nodeStr}</fire>";
}
$this->writeBranches(
$output,
$branches,
$this->getTaskDescription($task),
static fn ($branchTask, $i): bool => $branchTask === $taskCode,
$nodeStr
);
// Write task help message
if ($output->isVerbose() && $task->getHelp()) {
$helpLines = array_filter(explode("\n", $task->getHelp()));
foreach ($helpLines as $helpLine) {
$helpMessage = str_repeat(' ', self::INDENT_SIZE)."<info>{$helpLine}</info>";
$this->writeBranches($output, $branches, $helpMessage);
}
}
// Check next tasks
$nextTasks = array_unique(
array_map(
static fn (TaskConfiguration $task): string => $task->getCode(),
array_merge($task->getNextTasksConfigurations(), $task->getErrorTasksConfigurations())
)
);
if (\count($nextTasks) > 1) {
$this->writeBranches($output, $branches);
array_shift($nextTasks);
$origin = array_search($taskCode, $branches, true);
if (false === $origin) {
throw new UnexpectedValueException("Task '{$taskCode}' is not in any branch");
}
$expandBranches = [];
foreach ($nextTasks as $nextTask) {
$index = array_search(null, $branches, true);
if (false !== $index && $index >= $origin) {
/* @var int $index */
$branches[$index] = $taskCode;
$expandBranches[] = $index;
} else {
$expandBranches[] = \count($branches);
$branches[] = $taskCode;
}
}
$gapBranches = [];
sort($expandBranches);
$gapFrom = $origin;
$gapTo = null;
foreach ($expandBranches as $i) {
$gapTo = $i;
for ($j = $gapFrom + 1; $j < $gapTo; ++$j) {
$gapBranches[] = $j;
}
$gapFrom = $i;
}
$final = $gapFrom;
$this->writeBranches(
$output,
$branches,
'',
static fn ($branchTask, $i): bool => $i >= $origin && $i <= $final,
static function ($branchTask, $i) use ($origin, $branches, $gapBranches, $final): string {
if ($i === $origin) {
return self::CHAR_RECEIVE;
}
if (\in_array($i, $gapBranches, true)) {
if (null !== $branches[$i]) {
return self::CHAR_JUMP;
}
return self::CHAR_HORIZ;
}
if ($final === $i) {
return self::CHAR_EXPAND;
}
return self::CHAR_MULTIEXPAND;
}
);
}
if ([] === $nextTasks) {
foreach ($branches as $i => $branchTask) {
if ($branchTask === $taskCode) {
$branches[$i] = null;
}
}
}
// Cleanup empty trailing branches
foreach (array_reverse($branches, true) as $i => $branchTask) {
if (null !== $branchTask) {
$branches = \array_slice($branches, 0, $i + 1);
break;
}
}
$this->writeBranches($output, $branches);
}
/**
* @param array<int, string|null> $branches
* @param string|iterable<string> $comment
*/
protected function writeBranches(
OutputInterface $output,
array $branches,
string|iterable $comment = '',
?callable $match = null,
string|callable|null $char = null,
): void {
$output->write(str_repeat(' ', self::INDENT_SIZE));
// Merge lines
foreach ($branches as $i => $branchTask) {
$str = '';
if (null !== $match && $match($branchTask, $i)) {
if (\is_string($char)) {
$str = $char;
} elseif (\is_callable($char)) {
$str = $char($branchTask, $i);
} else {
throw new InvalidArgumentException('Char must be string|callable');
}
} elseif (null !== $branchTask) {
$str = self::CHAR_DOWN;
}
// Str_pad does not work with unicode ?
$noFormatStrLen = mb_strlen((string) preg_replace('/<[^>]*>/', '', (string) $str));
for ($j = $noFormatStrLen; $j < self::BRANCH_SIZE; ++$j) {
$str .= ' ';
}
$output->write($str);
}
$output->writeln($comment);
}
protected function getTaskDescription(TaskConfiguration $task): string
{
$description = $task->getCode();
$interfaces = [];
$subprocess = [];
$taskService = $this->getTaskService($task);
if ($taskService instanceof IterableTaskInterface) {
$interfaces[] = 'Iterable';
}
if ($taskService instanceof BlockingTaskInterface) {
$interfaces[] = 'Blocking';
}
if ($taskService instanceof FlushableTaskInterface) {
$interfaces[] = 'Flushable';
}
if ($taskService instanceof ProcessExecutorTask || $taskService instanceof ProcessLauncherTask) {
$subprocess[] = $task->getOption('process');
}
if ([] !== $interfaces) {
$description .= ' <info>('.implode(', ', $interfaces).')</info>';
}
if ([] !== $subprocess) {
$description .= ' <fire>{'.implode(', ', $subprocess).'}</fire>';
}
if ('' !== $task->getDescription() && '0' !== $task->getDescription()) {
$description .= " <comment>{$task->getDescription()}</comment>";
}
return $description;
}
protected function getTaskService(TaskConfiguration $taskConfiguration): TaskInterface
{
return $this->taskRegistry->getTask($taskConfiguration);
}
}