Completed
Pull Request — 3.x (#276)
by Maksim
01:50
created

AMQPBackendDispatcher::getContext()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
rs 8.439
c 0
b 0
f 0
cc 6
eloc 23
nc 5
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\NotificationBundle\Backend;
13
14
use Enqueue\AmqpTools\DelayStrategyAware;
15
use Enqueue\AmqpTools\RabbitMqDlxDelayStrategy;
16
use Guzzle\Http\Client as GuzzleClient;
17
use Interop\Amqp\AmqpConnectionFactory;
18
use Interop\Amqp\AmqpContext;
19
use PhpAmqpLib\Channel\AMQPChannel;
20
use PhpAmqpLib\Connection\AMQPConnection;
21
use Sonata\NotificationBundle\Exception\BackendNotFoundException;
22
use Sonata\NotificationBundle\Model\MessageInterface;
23
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
24
use ZendDiagnostics\Result\Failure;
25
use ZendDiagnostics\Result\Success;
26
27
/**
28
 * Producer side of the rabbitmq backend.
29
 */
30
class AMQPBackendDispatcher extends QueueBackendDispatcher
31
{
32
    /**
33
     * @var array
34
     */
35
    protected $settings;
36
37
    /**
38
     * @var AmqpConnectionFactory
39
     */
40
    protected $connectionFactory;
41
42
    /**
43
     * @var AmqpContext
44
     */
45
    protected $context;
46
47
    /**
48
     * @deprecated since 3.2, will be removed in 4.x
49
     *
50
     * @var AMQPChannel
51
     */
52
    protected $channel;
53
54
    /**
55
     * @deprecated since 3.2, will be removed in 4.x
56
     *
57
     * @var AMQPConnection
58
     */
59
    protected $connection;
60
61
    protected $backendsInitialized = false;
62
63
    /**
64
     * @param array  $settings
65
     * @param array  $queues
66
     * @param string $defaultQueue
67
     * @param array  $backends
68
     */
69
    public function __construct(array $settings, array $queues, $defaultQueue, array $backends)
70
    {
71
        parent::__construct($queues, $defaultQueue, $backends);
72
73
        $this->settings = $settings;
74
    }
75
76
    /**
77
     * @deprecated since 3.2, will be removed in 4.x
78
     *
79
     * @return AMQPChannel
80
     */
81
    public function getChannel()
82
    {
83
        @trigger_error(sprintf('The method %s is deprecated since version 3.3 and will be removed in 4.0. Use %s::getContext() instead.', __METHOD__, __CLASS__), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
84
85
        if (!$this->channel) {
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\NotificationBundl...endDispatcher::$channel has been deprecated with message: since 3.2, will be removed in 4.x

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
86
            if (!$this->context instanceof \Enqueue\AmqpLib\AmqpContext) {
87
                throw new \LogicException('The BC layer works only if enqueue/amqp-lib lib is being used.');
88
            }
89
90
            // load context
91
            $this->getContext();
92
93
            /** @var \Enqueue\AmqpLib\AmqpContext $context */
94
            $context = $this->getContext();
95
96
            $this->channel = $context->getLibChannel();
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\NotificationBundl...endDispatcher::$channel has been deprecated with message: since 3.2, will be removed in 4.x

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
97
            $this->connection = $this->channel->getConnection();
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\NotificationBundl...Dispatcher::$connection has been deprecated with message: since 3.2, will be removed in 4.x

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
Deprecated Code introduced by
The property Sonata\NotificationBundl...endDispatcher::$channel has been deprecated with message: since 3.2, will be removed in 4.x

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
98
        }
99
100
        return $this->channel;
0 ignored issues
show
Deprecated Code introduced by
The property Sonata\NotificationBundl...endDispatcher::$channel has been deprecated with message: since 3.2, will be removed in 4.x

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
101
    }
102
103
    /**
104
     * @return AmqpContext
105
     */
106
    public function getContext()
107
    {
108
        if (!$this->context) {
109
            if (!array_key_exists('factory_class', $this->settings)) {
110
                throw new \LogicException('The factory_class option is missing though it is required.');
111
            }
112
113
            $factoryClass = $this->settings['factory_class'];
114
            if (
115
                !class_exists($factoryClass) ||
116
                !(new \ReflectionClass($factoryClass))->implementsInterface(AmqpConnectionFactory::class)
117
            ) {
118
                throw new \LogicException(sprintf(
119
                    'The factory_class option "%s" has to be valid class that implements "%s"',
120
                    $factoryClass,
121
                    AmqpConnectionFactory::class
122
                ));
123
            }
124
125
            /** @var AmqpConnectionFactory $factory */
126
            $factory = new $factoryClass([
127
                'host' => $this->settings['host'],
128
                'port' => $this->settings['port'],
129
                'user' => $this->settings['user'],
130
                'pass' => $this->settings['pass'],
131
                'vhost' => $this->settings['vhost'],
132
            ]);
133
134
            if ($factory instanceof DelayStrategyAware) {
135
                $factory->setDelayStrategy(new RabbitMqDlxDelayStrategy());
136
            }
137
138
            $this->context = $this->connectionFactory->createContext();
139
140
            register_shutdown_function([$this, 'shutdown']);
141
        }
142
143
        return $this->context;
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149
    public function getBackend($type)
150
    {
151
        if (!$this->backendsInitialized) {
152
            foreach ($this->backends as $backend) {
153
                $backend['backend']->initialize();
154
            }
155
            $this->backendsInitialized = true;
156
        }
157
158
        $default = null;
159
160
        if (0 === count($this->queues)) {
161
            foreach ($this->backends as $backend) {
162
                if ('default' === $backend['type']) {
163
                    return $backend['backend'];
164
                }
165
            }
166
        }
167
168
        foreach ($this->backends as $backend) {
169
            if ('all' === $type && '' === $backend['type']) {
170
                return $backend['backend'];
171
            }
172
173
            if ($backend['type'] === $type) {
174
                return $backend['backend'];
175
            }
176
177
            if ($backend['type'] === $this->defaultQueue) {
178
                $default = $backend['backend'];
179
            }
180
        }
181
182
        if (null === $default) {
183
            throw new BackendNotFoundException('Could not find a message backend for the type '.$type);
184
        }
185
186
        return $default;
187
    }
188
189
    /**
190
     * {@inheritdoc}
191
     */
192
    public function getIterator()
193
    {
194
        throw new \RuntimeException(
195
            'You need to use a specific rabbitmq backend supporting the selected queue to run a consumer.'
196
        );
197
    }
198
199
    /**
200
     * {@inheritdoc}
201
     */
202
    public function handle(MessageInterface $message, EventDispatcherInterface $dispatcher)
203
    {
204
        throw new \RuntimeException(
205
            'You need to use a specific rabbitmq backend supporting the selected queue to run a consumer.'
206
        );
207
    }
208
209
    /**
210
     * {@inheritdoc}
211
     */
212
    public function getStatus()
213
    {
214
        try {
215
            $this->getContext();
216
            $output = $this->getApiQueueStatus();
217
            $checked = 0;
218
            $missingConsumers = [];
219
220
            foreach ($this->queues as $queue) {
221
                foreach ($output as $q) {
222
                    if ($q['name'] === $queue['queue']) {
223
                        ++$checked;
224
                        if (0 === $q['consumers']) {
225
                            $missingConsumers[] = $queue['queue'];
226
                        }
227
                    }
228
                }
229
            }
230
231
            if ($checked !== count($this->queues)) {
232
                return new Failure(
233
                    'Not all queues for the available notification types registered in the rabbitmq broker. '
234
                    .'Are the consumer commands running?'
235
                );
236
            }
237
238
            if (count($missingConsumers) > 0) {
239
                return new Failure(
240
                    'There are no rabbitmq consumers running for the queues: '.implode(', ', $missingConsumers)
241
                );
242
            }
243
        } catch (\Exception $e) {
244
            return new Failure($e->getMessage());
245
        }
246
247
        return new Success('Channel is running (RabbitMQ) and consumers for all queues available.');
248
    }
249
250
    /**
251
     * {@inheritdoc}
252
     */
253
    public function cleanup()
254
    {
255
        throw new \RuntimeException(
256
            'You need to use a specific rabbitmq backend supporting the selected queue to run a consumer.'
257
        );
258
    }
259
260
    public function shutdown()
261
    {
262
        if ($this->context) {
263
            $this->context->close();
264
        }
265
    }
266
267
    /**
268
     * {@inheritdoc}
269
     */
270
    public function initialize()
271
    {
272
    }
273
274
    /**
275
     * Calls the rabbitmq management api /api/<vhost>/queues endpoint to list the available queues.
276
     *
277
     * @see http://hg.rabbitmq.com/rabbitmq-management/raw-file/3646dee55e02/priv/www-api/help.html
278
     *
279
     * @return array
280
     */
281
    protected function getApiQueueStatus()
282
    {
283
        if (!class_exists(GuzzleClient::class)) {
284
            throw new \RuntimeException(
285
                'The guzzle http client library is required to run rabbitmq health checks. '
286
                .'Make sure to add guzzlehttp/guzzle to your composer.json.'
287
            );
288
        }
289
290
        $client = new GuzzleClient();
291
        $client->setConfig(['curl.options' => [CURLOPT_CONNECTTIMEOUT_MS => 3000]]);
292
        $request = $client->get(sprintf('%s/queues', $this->settings['console_url']));
293
        $request->setAuth($this->settings['user'], $this->settings['pass']);
294
295
        return json_decode($request->send()->getBody(true), true);
296
    }
297
}
298