Test Failed
Push — master ( 2775f1...e031e9 )
by Vladimir
02:56
created

QueueWorker   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 67
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
wmc 9
lcom 2
cbo 4

4 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 8 1
B handle() 0 29 5
A isTimeout() 0 6 1
A handledJobsInLimit() 0 7 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace FondBot\Toolbelt\Commands;
6
7
use FondBot\Contracts\Queue;
8
use FondBot\Toolbelt\Command;
9
use Symfony\Component\Console\Input\InputOption;
10
11
class QueueWorker extends Command
12 1
{
13
    /** @var float */
14
    private $startTime;
15 1
    /** @var int */
16 1
    private $jobsHandled;
17 1
18
    protected function configure(): void
19
    {
20
        $this
21
            ->setName('queue:worker')
22
            ->setDescription('Run queue worker')
23
            ->addOption('timeout', 't', InputOption::VALUE_OPTIONAL, 'The number of seconds worker will run.')
24
            ->addOption('jobs', 'j', InputOption::VALUE_OPTIONAL, 'The number of jobs worker will process.');
25
    }
26
27
    /**
28
     * Handle command.
29
     *
30
     * @throws \Psr\Container\ContainerExceptionInterface
31
     * @throws \Symfony\Component\Console\Exception\InvalidArgumentException
32
     */
33
    public function handle(): void
34
    {
35
        $this->startTime = microtime(true);
36
        $this->jobsHandled = 0;
37
38
        /** @var Queue $queue */
39
        $queue = resolve(Queue::class);
40
41
        $this->info('Worker started...');
42
43
        while (true) {
44
            $job = $queue->next();
45
46
            if ($job === null) {
47
                continue;
48
            }
49
50
            $this->line('Job: '.get_class($job));
51
52
            $driver = $job->driver;
53
            $command = $job->command;
54
55
            $driver->handle($command);
56
57
            if ($this->isTimeout() || $this->handledJobsInLimit()) {
58
                break;
59
            }
60
        }
61
    }
62
63
    private function isTimeout(): bool
64
    {
65
        $timeout = $this->getOption('timeout') ?? 60;
66
67
        return microtime(true) - $this->startTime > $timeout;
68
    }
69
70
    private function handledJobsInLimit(): bool
71
    {
72
        $this->jobsHandled++;
73
        $limit = (int) $this->getOption('jobs');
74
75
        return $limit <= 0 || $this->jobsHandled >= $limit;
76
    }
77
}
78