1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This class is used by the CPE Core InputPoller |
5
|
|
|
* We use it to listen to SQS input messages from clients |
6
|
|
|
**/ |
7
|
|
|
|
8
|
|
|
namespace SA\CpeSdk\Sqs; |
9
|
|
|
|
10
|
|
|
// Amazon libraries |
11
|
|
|
use Aws\Common\Aws; |
12
|
|
|
use Aws\Sqs; |
13
|
|
|
|
14
|
|
|
// SA Cpe SDK |
15
|
|
|
use SA\CpeSdk; |
16
|
|
|
|
17
|
|
|
class CpeSqsListener |
18
|
|
|
{ |
19
|
|
|
private $debug; |
20
|
|
|
private $sqs; |
21
|
|
|
private $cpeLogger; |
22
|
|
|
|
23
|
|
|
public function __construct($debug, $cpeLogger = null) |
24
|
|
|
{ |
25
|
|
|
$this->debug = $debug; |
26
|
|
|
|
27
|
|
|
// Create AWS SDK instance |
28
|
|
|
$aws = Aws::factory(array( |
29
|
|
|
'region' => getenv("AWS_DEFAULT_REGION") |
30
|
|
|
)); |
31
|
|
|
$this->sqs = $aws->get('Sqs'); |
32
|
|
|
|
33
|
|
|
// Logger |
34
|
|
|
if (!$cpeLogger) |
35
|
|
|
$this->cpeLogger = new CpeSdk\CpeLogger(); |
36
|
|
|
else |
37
|
|
|
$this->cpeLogger = $cpeLogger; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* LISTEN to OUTPUT SQS queue |
42
|
|
|
* Listen to the CPE stack for output messages |
43
|
|
|
*/ |
44
|
|
|
|
45
|
|
|
// Poll one message at a time from the provided SQS queue |
46
|
|
|
public function receive_message($queue, $timeout) |
47
|
|
|
{ |
48
|
|
|
if ($this->debug) |
49
|
|
|
$this->cpeLogger->log_out( |
50
|
|
|
"DEBUG", |
51
|
|
|
"[CPE SDK] ".basename(__FILE__), |
52
|
|
|
"Polling from '$queue' ..." |
53
|
|
|
); |
54
|
|
|
|
55
|
|
|
// Poll from SQS to check for new message |
56
|
|
|
$result = $this->sqs->receiveMessage(array( |
57
|
|
|
'QueueUrl' => $queue, |
58
|
|
|
'WaitTimeSeconds' => $timeout, |
59
|
|
|
)); |
60
|
|
|
|
61
|
|
|
// Get the message if any and return it to the caller |
62
|
|
|
if (($messages = $result->get('Messages')) && |
63
|
|
|
count($messages)) |
64
|
|
|
{ |
65
|
|
|
if ($this->debug) |
66
|
|
|
$this->cpeLogger->log_out( |
67
|
|
|
"DEBUG", |
68
|
|
|
"[CPE SDK] ".basename(__FILE__), |
69
|
|
|
"New messages recieved in queue: '$queue'" |
70
|
|
|
); |
71
|
|
|
|
72
|
|
|
return $messages[0]; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return false; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
// Delete a message from SQS queue |
79
|
|
|
// Call it after reading a message |
80
|
|
|
public function delete_message($queue, $msg) |
81
|
|
|
{ |
82
|
|
|
$this->sqs->deleteMessage(array( |
83
|
|
|
'QueueUrl' => $queue, |
84
|
|
|
'ReceiptHandle' => $msg['ReceiptHandle'])); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|