Completed
Pull Request — master (#15)
by Alex
01:44
created

QueueWriter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 4
dl 0
loc 77
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A write() 0 6 2
A send() 0 12 2
A initialize() 0 10 2
1
<?php
2
3
namespace Cmp\Queues\Infrastructure\AWS\v20121105\Queue;
4
5
use Aws\Sns\SnsClient;
6
use Cmp\Queues\Domain\Queue\Exception\WriterException;
7
use Cmp\Queues\Domain\Queue\Message;
8
use Cmp\Queues\Domain\Queue\QueueWriter as DomainQueueWriter;
9
use Psr\Log\LoggerInterface;
10
11
class QueueWriter implements DomainQueueWriter
12
{
13
    /**
14
     * @var SnsClient
15
     */
16
    protected $client;
17
18
    /**
19
     * @var string
20
     */
21
    private $topicArn;
22
23
    /**
24
     * @var LoggerInterface
25
     */
26
    protected $logger;
27
28
    /**
29
     * @param SnsClient       $client
30
     * @param string          $topicName
31
     * @param LoggerInterface $logger
32
     */
33
    public function __construct(SnsClient $client, $topicName, LoggerInterface $logger)
34
    {
35
        $this->client = $client;
36
        $this->logger = $logger;
37
38
        $this->initialize($topicName);
39
    }
40
41
    /**
42
     * @param Message[] $messages
43
     *
44
     * @throws WriterException
45
     * @return null
46
     */
47
    public function write(array $messages)
48
    {
49
        foreach ($messages as $message) {
50
            $this->send($message);
51
        }
52
    }
53
54
    /**
55
     * @param Message $message
56
     *
57
     * @throws WriterException
58
     */
59
    protected function send(Message $message)
60
    {
61
        try {
62
            $this->client->publish([
63
                'TopicArn' => $this->topicArn,
64
                'Message' => json_encode($message),
65
            ]);
66
        } catch(\Exception $e) {
67
            $this->logger->error('Error writing messages', ['exception' => $e]);
68
            throw new WriterException($e->getMessage(), $e->getCode());
69
        }
70
    }
71
72
    /**
73
     * @param string $name
74
     *
75
     * @throws WriterException
76
     */
77
    protected function initialize($name)
78
    {
79
        try {
80
            $result = $this->client->createTopic(['Name' => $name]);
81
            $this->topicArn = $result->get('TopicArn');
82
        } catch (\Exception $e) {
83
            $this->logger->error('Error trying to create an SNS topic', ['exception' => $e]);
84
            throw new WriterException($e->getMessage(), $e->getCode());
85
        }
86
    }
87
}