1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cmp\Queues\Infrastructure\AWS\v20121105\Queue; |
4
|
|
|
|
5
|
|
|
use Cmp\Queues\Domain\Event\Exception\InvalidJSONDomainEventException; |
6
|
|
|
use Cmp\Queues\Domain\Queue\Exception\InvalidJSONMessageException; |
7
|
|
|
use Cmp\Queues\Domain\Queue\Exception\ReaderException; |
8
|
|
|
use Cmp\Queues\Domain\Queue\JSONMessageFactory; |
9
|
|
|
use Cmp\Queues\Domain\Task\Exception\ParseMessageException; |
10
|
|
|
use Exception; |
11
|
|
|
|
12
|
|
|
class MessageHandler |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var JSONMessageFactory |
16
|
|
|
*/ |
17
|
|
|
private $jsonMessageFactory; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var callable |
21
|
|
|
*/ |
22
|
|
|
private $callback; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param JSONMessageFactory $jsonMessageFactory |
26
|
|
|
*/ |
27
|
|
|
public function __construct(JSONMessageFactory $jsonMessageFactory) |
28
|
|
|
{ |
29
|
|
|
$this->jsonMessageFactory = $jsonMessageFactory; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param array $message |
34
|
|
|
* |
35
|
|
|
* @return mixed |
36
|
|
|
* @throws ParseMessageException |
37
|
|
|
* @throws ReaderException |
38
|
|
|
*/ |
39
|
|
|
public function handleMessage(array $message) |
40
|
|
|
{ |
41
|
|
|
if (!isset($this->callback)) { |
42
|
|
|
throw new ReaderException("Handling a message with no callback set"); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
try{ |
46
|
|
|
|
47
|
|
View Code Duplication |
if (!isset($message['Body'])) { |
|
|
|
|
48
|
|
|
throw new InvalidJSONMessageException('Undefined index key Body: ' . print_r($message, true)); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
$body = json_decode($message['Body'], true); |
52
|
|
|
|
53
|
|
View Code Duplication |
if (!isset($body['Message'])) { |
|
|
|
|
54
|
|
|
throw new InvalidJSONMessageException('Undefined index key Message: ' . print_r($body, true)); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return call_user_func($this->callback, $this->jsonMessageFactory->create($body['Message'])); |
58
|
|
|
|
59
|
|
|
} catch(InvalidJSONMessageException $e) { |
60
|
|
|
throw new ParseMessageException(json_encode($message),0, $e); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @param callable $callback |
66
|
|
|
*/ |
67
|
|
|
public function setCallback(callable $callback) |
68
|
|
|
{ |
69
|
|
|
$this->callback = $callback; |
70
|
|
|
} |
71
|
|
|
} |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.