|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace OldSound\RabbitMqBundle\ExecuteReceiverStrategy; |
|
4
|
|
|
|
|
5
|
|
|
use OldSound\RabbitMqBundle\Declarations\ConsumeOptions; |
|
6
|
|
|
use OldSound\RabbitMqBundle\ExecuteCallbackStrategy\ExecuteReceiverStrategyInterface; |
|
|
|
|
|
|
7
|
|
|
use PhpAmqpLib\Exception\AMQPTimeoutException; |
|
8
|
|
|
use PhpAmqpLib\Message\AMQPMessage; |
|
9
|
|
|
|
|
10
|
|
|
class BatchExecuteReceiverStrategy extends AbstractExecuteReceiverStrategy |
|
11
|
|
|
{ |
|
12
|
|
|
/** @var int */ |
|
13
|
|
|
private $batchCount; |
|
14
|
|
|
/** @var AMQPMessage[] */ |
|
15
|
|
|
protected $messagesBatch = []; |
|
16
|
|
|
|
|
17
|
|
|
public function __construct(int $batchCount) |
|
18
|
|
|
{ |
|
19
|
|
|
$this->batchCount = $batchCount; |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
public function canPrecessMultiMessages(): bool |
|
23
|
|
|
{ |
|
24
|
|
|
return true; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public function onConsumeCallback(AMQPMessage $message): ?array |
|
28
|
|
|
{ |
|
29
|
|
|
$this->messagesBatch[$message->getDeliveryTag()] = $message; |
|
30
|
|
|
|
|
31
|
|
|
if ($this->isBatchCompleted()) { |
|
32
|
|
|
return $this->execute($this->messagesBatch); |
|
33
|
|
|
} |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public function onMessageProcessed(AMQPMessage $message) |
|
37
|
|
|
{ |
|
38
|
|
|
unset($this->messagesBatch[array_search($message, $this->messagesBatch, true)]); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
public function onCatchTimeout(AMQPTimeoutException $e) |
|
42
|
|
|
{ |
|
43
|
|
|
if (!$this->isBatchEmpty()) { |
|
44
|
|
|
$this->processMessages($this->messagesBatch); |
|
|
|
|
|
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
public function onStopConsuming() |
|
49
|
|
|
{ |
|
50
|
|
|
if (!$this->isBatchEmpty()) { |
|
51
|
|
|
$this->processMessages($this->messagesBatch); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
protected function isBatchCompleted(): bool |
|
56
|
|
|
{ |
|
57
|
|
|
return count($this->messagesBatch) === $this->batchCount; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* @return bool |
|
62
|
|
|
*/ |
|
63
|
|
|
protected function isBatchEmpty() |
|
64
|
|
|
{ |
|
65
|
|
|
return count($this->messagesBatch) === 0; |
|
66
|
|
|
} |
|
67
|
|
|
} |
Let?s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let?s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.phpHowever, as
OtherDir/Foo.phpdoes not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: