1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ozean12\GooglePubSubBundle\Service\Publisher; |
4
|
|
|
|
5
|
|
|
use Google\Cloud\Exception\ConflictException; |
6
|
|
|
use Google\Cloud\PubSub\PubSubClient; |
7
|
|
|
use Google\Cloud\PubSub\Topic; |
8
|
|
|
use JMS\Serializer\Serializer; |
9
|
|
|
use Ozean12\GooglePubSubBundle\DTO\MessageDataDTOInterface; |
10
|
|
|
use Ozean12\GooglePubSubBundle\DTO\PublishMessageResultDTO; |
11
|
|
|
use Ozean12\GooglePubSubBundle\Service\AbstractClient; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Class Publisher |
15
|
|
|
*/ |
16
|
|
|
class Publisher extends AbstractClient |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var Topic |
20
|
|
|
*/ |
21
|
|
|
private $topic; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var string |
25
|
|
|
*/ |
26
|
|
|
private $topicName; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Publisher constructor. |
30
|
|
|
* |
31
|
|
|
* @param string $topic |
32
|
|
|
* @param PubSubClient $client |
33
|
|
|
* @param Serializer $serializer |
34
|
|
|
*/ |
35
|
|
|
public function __construct($topic, PubSubClient $client, Serializer $serializer) |
36
|
|
|
{ |
37
|
|
|
parent::__construct($client, $serializer); |
38
|
|
|
|
39
|
|
|
$this->topicName = $topic; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param MessageDataDTOInterface $data |
44
|
|
|
* @param array $attributes |
45
|
|
|
* @param array $options |
46
|
|
|
* @return PublishMessageResultDTO |
47
|
|
|
*/ |
48
|
|
|
public function publish(MessageDataDTOInterface $data, array $attributes = [], $options = []) |
49
|
|
|
{ |
50
|
|
|
$this->setupTopic(); |
51
|
|
|
|
52
|
|
|
$message = [ |
53
|
|
|
'data' => $this->serializer->serialize($data, 'json'), |
54
|
|
|
]; |
55
|
|
|
|
56
|
|
|
if (!empty($attributes)) { |
57
|
|
|
$message['attributes'] = $attributes; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$result = $this->topic->publish($message, $options); |
61
|
|
|
/** @var PublishMessageResultDTO $resultDTO */ |
62
|
|
|
$resultDTO = $this->serializer->fromArray($result, PublishMessageResultDTO::class); |
63
|
|
|
|
64
|
|
|
$this->logInfo('Message(s) {messages} submitted to topic {topic}', [ |
65
|
|
|
'messages' => join(', ', $resultDTO->getMessageIds()), |
66
|
|
|
'topic' => $this->topicName, |
67
|
|
|
]); |
68
|
|
|
|
69
|
|
|
return $resultDTO; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Create or fetch topic |
74
|
|
|
*/ |
75
|
|
|
private function setupTopic() |
76
|
|
|
{ |
77
|
|
|
if ($this->topic instanceof Topic) { |
78
|
|
|
return; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
try { |
82
|
|
|
$this->topic = $this->client->createTopic($this->topicName); |
83
|
|
|
$this->logInfo('New topic {topic} created', ['topic' => $this->topicName]); |
84
|
|
|
} catch (ConflictException $exception) { // topic already exists |
85
|
|
|
$this->topic = $this->client->topic($this->topicName); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|