Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Publisher.php
Go to the documentation of this file.
1 <?php
7 
8 use Magento\Framework\Amqp\Config as AmqpConfig;
9 use Magento\Framework\MessageQueue\ConfigInterface as MessageQueueConfig;
11 
15 class Publisher implements PublisherInterface
16 {
20  private $exchangeRepository;
21 
25  private $envelopeFactory;
26 
30  private $messageEncoder;
31 
35  private $messageValidator;
36 
40  private $publisherConfig;
41 
47  private $amqpConfig;
48 
61  public function __construct(
62  ExchangeRepository $exchangeRepository,
63  EnvelopeFactory $envelopeFactory,
64  MessageQueueConfig $messageQueueConfig,
65  MessageEncoder $messageEncoder,
66  MessageValidator $messageValidator
67  ) {
68  $this->exchangeRepository = $exchangeRepository;
69  $this->envelopeFactory = $envelopeFactory;
70  $this->messageEncoder = $messageEncoder;
71  $this->messageValidator = $messageValidator;
72  }
73 
77  public function publish($topicName, $data)
78  {
79  $this->messageValidator->validate($topicName, $data);
80  $data = $this->messageEncoder->encode($topicName, $data);
81  $envelope = $this->envelopeFactory->create(
82  [
83  'body' => $data,
84  'properties' => [
85  'delivery_mode' => 2,
86  'message_id' => md5(uniqid($topicName))
87  ]
88  ]
89  );
90  $connectionName = $this->getPublisherConfig()->getPublisher($topicName)->getConnection()->getName();
91  $connectionName = ($connectionName === 'amqp' && !$this->isAmqpConfigured()) ? 'db' : $connectionName;
92  $exchange = $this->exchangeRepository->getByConnectionName($connectionName);
93  $exchange->enqueue($topicName, $envelope);
94  return null;
95  }
96 
102  private function isAmqpConfigured()
103  {
104  return $this->getAmqpConfig()->getValue(AmqpConfig::HOST) ? true : false;
105  }
106 
114  private function getPublisherConfig()
115  {
116  if ($this->publisherConfig === null) {
117  $this->publisherConfig = \Magento\Framework\App\ObjectManager::getInstance()->get(PublisherConfig::class);
118  }
119  return $this->publisherConfig;
120  }
121 
129  private function getAmqpConfig()
130  {
131  if ($this->amqpConfig === null) {
132  $this->amqpConfig = \Magento\Framework\App\ObjectManager::getInstance()->get(AmqpConfig::class);
133  }
134 
135  return $this->amqpConfig;
136  }
137 }
__construct(ExchangeRepository $exchangeRepository, EnvelopeFactory $envelopeFactory, MessageQueueConfig $messageQueueConfig, MessageEncoder $messageEncoder, MessageValidator $messageValidator)
Definition: Publisher.php:61