forked from swarrot/swarrot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaxExecutionTimeProcessor.php
80 lines (68 loc) · 1.99 KB
/
MaxExecutionTimeProcessor.php
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
<?php
namespace Swarrot\Processor\MaxExecutionTime;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Swarrot\Broker\Message;
use Swarrot\Processor\ConfigurableInterface;
use Swarrot\Processor\InitializableInterface;
use Swarrot\Processor\ProcessorInterface;
use Swarrot\Processor\SleepyInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class MaxExecutionTimeProcessor implements ConfigurableInterface, InitializableInterface, SleepyInterface
{
private $processor;
private $logger;
/**
* @var float
*/
private $startTime;
public function __construct(ProcessorInterface $processor, LoggerInterface $logger = null)
{
$this->processor = $processor;
$this->logger = $logger ?: new NullLogger();
}
/**
* {@inheritdoc}
*/
public function setDefaultOptions(OptionsResolver $resolver): void
{
$resolver
->setDefaults([
'max_execution_time' => 300,
])
->setAllowedTypes('max_execution_time', 'int')
;
}
/**
* {@inheritdoc}
*/
public function initialize(array $options): void
{
$this->startTime = microtime(true);
}
/**
* {@inheritdoc}
*/
public function sleep(array $options): bool
{
return !$this->isTimeExceeded($options);
}
/**
* {@inheritdoc}
*/
public function process(Message $message, array $options): bool
{
return $this->processor->process($message, $options) && !$this->isTimeExceeded($options);
}
protected function isTimeExceeded(array $options): bool
{
if (microtime(true) - $this->startTime > $options['max_execution_time']) {
$this->logger->info('[MaxExecutionTime] Max execution time has been reached', [
'max_execution_time' => $options['max_execution_time'],
'swarrot_processor' => 'max_execution_time',
]);
return true;
}
return false;
}
}