-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Example.php
72 lines (59 loc) · 1.79 KB
/
Example.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
<?php
/**
* @author Marwan Al-Soltany <[email protected]>
* @copyright Marwan Al-Soltany 2020
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace MAKS\AmqpAgent\Helper;
use Exception;
use PhpAmqpLib\Message\AMQPMessage;
use MAKS\AmqpAgent\Helper\Logger;
use MAKS\AmqpAgent\Helper\Serializer;
use MAKS\AmqpAgent\Worker\Consumer;
/**
* An abstract class used as a default callback for the consumer.
* @since 1.0.0
*/
abstract class Example
{
/**
* @var Serializer
*/
private static $serializer;
/**
* Whether to log messages to a file or not.
* @var bool
*/
public static $logToFile = true;
/**
* Default AMQP Agent callback.
* @param AMQPMessage $message
* @return bool
*/
public static function callback(AMQPMessage $message): bool
{
if (!isset(self::$serializer)) {
self::$serializer = new Serializer();
}
try {
$data = self::$serializer->unserialize($message->body, 'PHP', true);
} catch (Exception $e) {
// the strict value of the serializer is false here
// because the data can also be plain-text
$data = self::$serializer->unserialize($message->body, 'JSON', false);
}
Consumer::ack($message);
if ($data && Consumer::isCommand($data)) {
usleep(25000); // For acknowledgment to take effect.
if (Consumer::hasCommand($data, 'close')) {
Consumer::shutdown($message);
}
}
if (static::$logToFile) {
Logger::log($message->body, 'maks-amqp-agent-example-callback'); // @codeCoverageIgnore
}
return true;
}
}