|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* @author Marwan Al-Soltany <[email protected]> |
|
5
|
|
|
* @copyright Marwan Al-Soltany 2020 |
|
6
|
|
|
* For the full copyright and license information, please view |
|
7
|
|
|
* the LICENSE file that was distributed with this source code. |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
declare(strict_types=1); |
|
11
|
|
|
|
|
12
|
|
|
namespace MAKS\AmqpAgent\Helper; |
|
13
|
|
|
|
|
14
|
|
|
use Exception; |
|
15
|
|
|
use PhpAmqpLib\Message\AMQPMessage; |
|
16
|
|
|
use MAKS\AmqpAgent\Helper\Logger; |
|
17
|
|
|
use MAKS\AmqpAgent\Helper\Serializer; |
|
18
|
|
|
use MAKS\AmqpAgent\Worker\Consumer; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* An abstract class used as a default callback for the consumer. |
|
22
|
|
|
* @since 1.0.0 |
|
23
|
|
|
*/ |
|
24
|
|
|
abstract class Example |
|
25
|
|
|
{ |
|
26
|
|
|
/** |
|
27
|
|
|
* @var Serializer |
|
28
|
|
|
*/ |
|
29
|
|
|
private static $serializer; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Whether to log messages to a file or not. |
|
33
|
|
|
* @var bool |
|
34
|
|
|
*/ |
|
35
|
|
|
public static $logToFile = true; |
|
36
|
|
|
|
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* Default AMQP Agent callback. |
|
40
|
|
|
* @param AMQPMessage $message |
|
41
|
|
|
* @return bool |
|
42
|
|
|
*/ |
|
43
|
1 |
|
public static function callback(AMQPMessage $message): bool |
|
44
|
|
|
{ |
|
45
|
1 |
|
if (!isset(self::$serializer)) { |
|
46
|
1 |
|
self::$serializer = new Serializer(); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
try { |
|
50
|
1 |
|
$data = self::$serializer->unserialize($message->body, 'PHP', true); |
|
51
|
1 |
|
} catch (Exception $e) { |
|
52
|
|
|
// the strict value of the serializer is false here |
|
53
|
|
|
// because the data can also be plain-text |
|
54
|
1 |
|
$data = self::$serializer->unserialize($message->body, 'JSON', false); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
1 |
|
Consumer::ack($message); |
|
58
|
|
|
|
|
59
|
1 |
|
if ($data && Consumer::isCommand($data)) { |
|
60
|
1 |
|
usleep(25000); // For acknowledgment to take effect. |
|
61
|
1 |
|
if (Consumer::hasCommand($data, 'close')) { |
|
62
|
1 |
|
Consumer::shutdown($message); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
1 |
|
if (static::$logToFile) { |
|
67
|
|
|
Logger::log($message->body, 'maks-amqp-agent-example-callback'); // @codeCoverageIgnore |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
1 |
|
return true; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|