Passed
Push — v2 ( 1cd5a7...0b44bc )
by Brice
02:47
created

Consume::execute()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5.0729

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
ccs 12
cts 14
cp 0.8571
cc 5
eloc 14
nc 4
nop 2
crap 5.0729
1
<?php
2
3
namespace JobQueue\Application\Worker;
4
5
use JobQueue\Application\Utils\CommandTrait;
6
use JobQueue\Domain\Task\Profile;
7
use JobQueue\Domain\Worker;
8
use JobQueue\Infrastructure\ServiceContainer;
9
use Ramsey\Uuid\Uuid;
10
use Symfony\Component\Console\Command\Command;
11
use Symfony\Component\Console\Input\InputArgument;
12
use Symfony\Component\Console\Input\InputInterface;
13
use Symfony\Component\Console\Input\InputOption;
14
use Symfony\Component\Console\Output\OutputInterface;
15
16
final class Consume extends Command
17
{
18
    use CommandTrait;
19
20
    public function configure()
21
    {
22
        $this
23
            ->setName('consume')
24
            ->setDescription('Consumes tasks from the queue')
25
            ->setHelp("Consumes tasks from a queue depending on one or multiple profiles.  \nEach task is consumed by executing the corresponding job.\n ")
26
            ->addArgument('profile', InputArgument::REQUIRED, 'Name of the profile to consume')
27
            ->addOption('name', 'w', InputOption::VALUE_OPTIONAL, 'Name of the worker')
28
            ->addOption('quantity', 'x', InputOption::VALUE_OPTIONAL, 'Quantity of tasks to consume')
29
        ;
30
    }
31
32
    /**
33
     *
34
     * @param InputInterface $input
35
     * @param OutputInterface $output
36
     * @return int
37
     */
38 2
    protected function execute(InputInterface $input, OutputInterface $output): int
39
    {
40 2
        $services = ServiceContainer::getInstance();
41
42 2
        $worker = new Worker(
43 2
            $name = $input->getOption('name') ?: (string) Uuid::uuid4(),
44 2
            $services->queue,
45 2
            $profile = new Profile($input->getArgument('profile'))
46
        );
47
48 2
        if (isset($services->logger)) {
49
            $worker->setLogger($services->logger);
50
        }
51
52 2
        $this->formatInfoSection(sprintf('Worker %s handles "%s" tasks...', $name, $profile), $output);
53
54 2
        $worker->consume($quantity = (int) $input->getOption('quantity') ?: null);
55
56 2
        if ($quantity > 0) {
57 2
            $this->formatInfoSection(sprintf('Worker %s is done.', $name), $output);
58
        } else {
59
            $this->formatErrorSection(sprintf('Worker %s has hanged out!', $name), $output);
60
        }
61
62 2
        return 0;
63
    }
64
}
65