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
|
|
|
|