Passed
Branch main (b0ee7b)
by Gaetano
09:00
created

CleanupCommand::execute()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 46
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 29
c 1
b 0
f 0
nc 8
nop 2
dl 0
loc 46
rs 8.2114
1
<?php
2
3
namespace Kaliop\eZWorkflowEngineBundle\Command;
4
5
use Symfony\Component\Console\Input\InputInterface;
6
use Symfony\Component\Console\Output\OutputInterface;
7
use Symfony\Component\Console\Input\InputOption;
8
use Kaliop\eZMigrationBundle\API\Value\Migration;
9
use Kaliop\eZMigrationBundle\API\Value\MigrationDefinition;
10
11
/**
12
 * Command to clean up workflows.
13
 */
14
class CleanupCommand extends AbstractCommand
15
{
16
    protected function configure()
17
    {
18
        $this->setName('kaliop:workflows:cleanup')
19
            ->addOption('older-than', 'o', InputOption::VALUE_REQUIRED, "Only remove workflows which have finished since N minutes", 86400)
20
            ->addOption('failed', 'f',  InputOption::VALUE_NONE, "Remove failed instead of finished workflows")
21
            ->addOption('dry-run', 'd', InputOption::VALUE_NONE, "Only list workflows to remove, without actually doing it")
22
            ->setDescription('Removes old workflows from the list of executed ones')
23
        ;
24
    }
25
26
    public function execute(InputInterface $input, OutputInterface $output)
27
    {
28
        $minAge = $input->getOption('older-than');
29
30
        $maxAge = time() - ($minAge * 60);
31
        $offset = 0;
32
        $limit = 1000;
33
34
        $workflowService = $this->getWorkflowService();
35
        $toRemove = array();
36
        $total = 0;
37
        do {
38
            $status = Migration::STATUS_DONE;
39
            $label = 'executed';
40
            if ($input->getOption('failed')) {
41
                $status = $status = Migration::STATUS_FAILED;
0 ignored issues
show
Unused Code introduced by
The assignment to $status is dead and can be removed.
Loading history...
42
                $label = 'failed';
43
            }
44
45
            $workflows = $workflowService->getWorkflowsByStatus($status, $limit, $offset);
46
47
            if (!count($workflows)) {
48
                break;
49
            }
50
51
            foreach($workflows as $workflow) {
52
                if ($workflow->executionDate < $maxAge) {
53
                    $toRemove[] = $workflow;
54
                }
55
            }
56
57
            $total += count($workflows);
58
            $offset += $limit;
59
        } while(true);
60
61
        if ($input->getOption('dry-run')) {
62
            $action = "To remove: ";
63
64
        } else {
65
            $action = "Removed ";
66
            foreach ($toRemove as $workflow) {
67
                $workflowService->deleteMigration($workflow);
68
            }
69
        }
70
71
        $output->writeln($action . count($toRemove) . " workflows out of $total $label");
72
    }
73
}
74