Completed
Pull Request — v2 (#16)
by Faouzi
02:28
created

RabbitServiceProvider::loadRpcServers()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 20
rs 9.4285
cc 3
eloc 13
nc 1
nop 1
1
<?php
2
3
namespace ETNA\Silex\Provider\RabbitMQ;
4
5
use OldSound\RabbitMqBundle\RabbitMq\AnonConsumer;
6
use OldSound\RabbitMqBundle\RabbitMq\BaseConsumer;
7
use OldSound\RabbitMqBundle\RabbitMq\Consumer;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, ETNA\Silex\Provider\RabbitMQ\Consumer.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
use OldSound\RabbitMqBundle\RabbitMq\MultipleConsumer;
9
use OldSound\RabbitMqBundle\RabbitMq\Producer;
10
use OldSound\RabbitMqBundle\RabbitMq\RpcClient;
11
use OldSound\RabbitMqBundle\RabbitMq\RpcServer;
12
use PhpAmqpLib\Connection\AMQPConnection;
13
use PhpAmqpLib\Connection\AMQPLazyConnection;
14
use PhpAmqpLib\Connection\AMQPSSLConnection;
15
use Pimple\Container;
16
use Pimple\ServiceProviderInterface;
17
18
/**
19
 * Code repris de fiunchinho/rabbitmq-service-provider en attendant la compatibilité
20
 * avec silex 2
21
 */
22
class RabbitServiceProvider implements ServiceProviderInterface
23
{
24
    const DEFAULT_CONNECTION = 'default';
25
26
    public function register(Container $app)
27
    {
28
        $this->loadConnections($app);
0 ignored issues
show
Unused Code introduced by
The call to the method ETNA\Silex\Provider\Rabb...ider::loadConnections() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
29
        $this->loadProducers($app);
0 ignored issues
show
Unused Code introduced by
The call to the method ETNA\Silex\Provider\Rabb...ovider::loadProducers() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
30
        $this->loadConsumers($app);
0 ignored issues
show
Unused Code introduced by
The call to the method ETNA\Silex\Provider\Rabb...ovider::loadConsumers() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
31
        $this->loadAnonymousConsumers($app);
0 ignored issues
show
Unused Code introduced by
The call to the method ETNA\Silex\Provider\Rabb...oadAnonymousConsumers() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
32
        $this->loadMultipleConsumers($app);
0 ignored issues
show
Unused Code introduced by
The call to the method ETNA\Silex\Provider\Rabb...loadMultipleConsumers() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
33
        $this->loadRpcClients($app);
0 ignored issues
show
Unused Code introduced by
The call to the method ETNA\Silex\Provider\Rabb...vider::loadRpcClients() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
34
        $this->loadRpcServers($app);
0 ignored issues
show
Unused Code introduced by
The call to the method ETNA\Silex\Provider\Rabb...vider::loadRpcServers() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
35
    }
36
37
    /**
38
     * Return the name of the connection to use.
39
     *
40
     * @param  array     $options     Options for the Producer or Consumer.
41
     * @param  array     $connections Connections defined in the config file.
42
     * @return string                 The connection name that will be used
43
     */
44
    private function getConnection($app, $options, $connections)
45
    {
46
        $connection_name = @$options['connection']?: self::DEFAULT_CONNECTION;
47
48
        if (!isset($connections[$connection_name])) {
49
            throw new \InvalidArgumentException('Configuration for connection [' . $connection_name . '] not found');
50
        }
51
52
        return $app['rabbit.connection'][$connection_name];
53
    }
54
55
    /**
56
     * @param Container $app
57
     */
58
    private function loadConnections($app)
59
    {
60
        $app['rabbit.connection'] = function ($app) {
61
            if (!isset($app['rabbit.connections'])) {
62
                throw new \InvalidArgumentException('You need to specify at least a connection in your configuration.');
63
            }
64
65
            $connections = [];
66
            foreach ($app["rabbit.connections"] as $name => $options) {
67
                $amqp_class = "PhpAmqpLib\Connection\AMQPConnection";
68
                $amqp_args  = [
69
                    $options["host"],
70
                    $options["port"],
71
                    $options["user"],
72
                    $options["password"],
73
                    $options["vhost"]
74
                ];
75
76
                if (isset($options["ssl"]) && true === $options["ssl"]) {
77
                    $amqp_class = "PhpAmqpLib\Connection\AMQPSSLConnection";
78
                    $amqp_args  = array_merge(
79
                        $amqp_args,
80
                        [
81
                            isset($options["ssl_options"]) ? $options["ssl_options"] : ['verify_peer' => false],
82
                            isset($options["options"]) ?
83
                                $options["options"] :
84
                                ['read_write_timeout' => 60,'heartbeat' => 30]
85
                        ]
86
                    );
87
                }
88
89
                $reflection = new \ReflectionClass($amqp_class);
90
                $connection = $reflection->newInstanceArgs($amqp_args);
91
92
                register_shutdown_function(
93
                    function ($connection) {
94
                        $connection->close();
95
                    },
96
                    $connection
97
                );
98
99
                $connections[$name] = $connection;
100
            }
101
102
            return $connections;
103
        };
104
    }
105
106
    /**
107
     * @param Container $app
108
     */
109
    private function loadProducers($app)
110
    {
111
        $app['rabbit.producer'] = function ($app) {
112
            if (!isset($app['rabbit.producers'])) {
113
                return;
114
            }
115
            $producers = [];
116
            foreach ($app['rabbit.producers'] as $name => $options) {
117
                $connection = $this->getConnection($app, $options, $app['rabbit.connections']);
118
119
                $producer = new Producer($connection);
0 ignored issues
show
Documentation introduced by
$connection is of type string, but the function expects a object<PhpAmqpLib\Connection\AbstractConnection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
120
                $producer->setExchangeOptions($options['exchange_options']);
121
122
                //this producer doesn't define a queue
123
                if (!isset($options['queue_options'])) {
124
                    $options['queue_options']['name'] = null;
125
                }
126
                $producer->setQueueOptions($options['queue_options']);
127
128
                if ((array_key_exists('auto_setup_fabric', $options)) && (!$options['auto_setup_fabric'])) {
129
                    $producer->disableAutoSetupFabric();
130
                }
131
132
                $producers[$name] = $producer;
133
            }
134
135
            return $producers;
136
        };
137
    }
138
139
    /**
140
     * @param Container $app
141
     */
142
    private function loadConsumers($app)
143
    {
144
        $app['rabbit.consumer'] = function ($app) {
145
            if (!isset($app['rabbit.consumers'])) {
146
                return;
147
            }
148
149
            $consumers = [];
150
            foreach ($app['rabbit.consumers'] as $name => $options) {
151
                $connection = $this->getConnection($app, $options, $app['rabbit.connections']);
152
                $consumer = new Consumer($connection);
0 ignored issues
show
Documentation introduced by
$connection is of type string, but the function expects a object<PhpAmqpLib\Connection\AbstractConnection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
153
                $consumer->setExchangeOptions($options['exchange_options']);
154
                $consumer->setQueueOptions($options['queue_options']);
155
                $consumer->setCallback(array($app[$options['callback']], 'execute'));
156
                $consumer = $this->setQosOptions($consumer, $options);
157
158
                if (array_key_exists('idle_timeout', $options)) {
159
                    $consumer->setIdleTimeout($options['idle_timeout']);
160
                }
161
162
                if ((array_key_exists('auto_setup_fabric', $options)) && (!$options['auto_setup_fabric'])) {
163
                    $consumer->disableAutoSetupFabric();
164
                }
165
166
                $consumers[$name] = $consumer;
167
            }
168
169
            return $consumers;
170
        };
171
    }
172
173
    /**
174
     * @param Container $app
175
     */
176
    private function loadAnonymousConsumers($app)
177
    {
178
        $app['rabbit.anonymous_consumer'] = function ($app) {
179
            if (!isset($app['rabbit.anon_consumers'])) {
180
                return;
181
            }
182
183
            $consumers = [];
184
            foreach ($app['rabbit.anon_consumers'] as $name => $options) {
185
                $connection = $this->getConnection($app, $options, $app['rabbit.connections']);
186
                $consumer = new AnonConsumer($connection);
0 ignored issues
show
Documentation introduced by
$connection is of type string, but the function expects a object<PhpAmqpLib\Connection\AMQPConnection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
187
                $consumer->setExchangeOptions($options['exchange_options']);
188
                $consumer->setCallback(array($options['callback'], 'execute'));
189
190
                $consumers[$name] = $consumer;
191
            }
192
193
            return $consumers;
194
        };
195
    }
196
197
    /**
198
     * @param Container $app
199
     */
200
    private function loadMultipleConsumers($app)
201
    {
202
        $app['rabbit.multiple_consumer'] = function ($app) {
203
            if (!isset($app['rabbit.multiple_consumers'])) {
204
                return;
205
            }
206
207
            $consumers = [];
208
            foreach ($app['rabbit.multiple_consumers'] as $name => $options) {
209
                $connection = $this->getConnection($app, $options, $app['rabbit.connections']);
210
                $consumer = new MultipleConsumer($connection);
0 ignored issues
show
Documentation introduced by
$connection is of type string, but the function expects a object<PhpAmqpLib\Connection\AbstractConnection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
211
                $consumer->setExchangeOptions($options['exchange_options']);
212
                $consumer->setQueues($options['queues']);
213
                $consumer = $this->setQosOptions($consumer, $options);
214
215
                if (array_key_exists('idle_timeout', $options)) {
216
                    $consumer->setIdleTimeout($options['idle_timeout']);
217
                }
218
219
                if ((array_key_exists('auto_setup_fabric', $options)) && (!$options['auto_setup_fabric'])) {
220
                    $consumer->disableAutoSetupFabric();
221
                }
222
223
                $consumers[$name] = $consumer;
224
            }
225
226
            return $consumers;
227
        };
228
229
    }
230
231
    /**
232
     * @param Container $app
233
     */
234
    private function loadRpcClients($app)
235
    {
236
        $app['rabbit.rpc_client'] = function ($app) {
237
            if (!isset($app['rabbit.rpc_clients'])) {
238
                return;
239
            }
240
241
            $clients = [];
242
            foreach ($app['rabbit.rpc_clients'] as $name => $options) {
243
                $connection = $this->getConnection($app, $options, $app['rabbit.connections']);
244
                $client = new RpcClient($connection);
0 ignored issues
show
Documentation introduced by
$connection is of type string, but the function expects a object<PhpAmqpLib\Connection\AbstractConnection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
245
246
                if (array_key_exists('expect_serialized_response', $options)) {
247
                    $client->initClient($options['expect_serialized_response']);
248
                }
249
250
                $clients[$name] = $client;
251
            }
252
253
            return $clients;
254
        };
255
    }
256
257
    /**
258
     * @param Container $app
259
     */
260
    private function loadRpcServers($app)
261
    {
262
        $app['rabbit.rpc_server'] = function ($app) {
263
            if (!isset($app['rabbit.rpc_servers'])) {
264
                return;
265
            }
266
267
            $servers = [];
268
            foreach ($app['rabbit.rpc_servers'] as $name => $options) {
269
                $connection = $this->getConnection($app, $options, $app['rabbit.connections']);
270
                $server = new RpcServer($connection);
0 ignored issues
show
Documentation introduced by
$connection is of type string, but the function expects a object<PhpAmqpLib\Connection\AbstractConnection>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
271
                $server->initServer($name);
272
                $server->setCallback(array($options['callback'], 'execute'));
273
                $server         = $this->setQosOptions($server, $options);
274
                $servers[$name] = $server;
275
            }
276
277
            return $servers;
278
        };
279
    }
280
281
    private function setQosOptions(BaseConsumer $consumer, $options)
282
    {
283
        if (array_key_exists('qos_options', $options)) {
284
            $consumer->setQosOptions(
285
                $options['qos_options']['prefetch_size'],
286
                $options['qos_options']['prefetch_count'],
287
                $options['qos_options']['global']
288
            );
289
        }
290
291
        return $consumer;
292
    }
293
}
294