Completed
Push — master ( fc1bf9...6b91a0 )
by Keith
06:58
created

UecodeQPushExtension::load()   D

Complexity

Conditions 14
Paths 86

Size

Total Lines 110
Code Lines 74

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 56
CRAP Score 16.8192

Importance

Changes 0
Metric Value
dl 0
loc 110
ccs 56
cts 74
cp 0.7568
rs 4.9516
c 0
b 0
f 0
cc 14
eloc 74
nc 86
nop 2
crap 16.8192

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Copyright 2014 Underground Elephant
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 *
18
 * @package     qpush-bundle
19
 * @copyright   Underground Elephant 2014
20
 * @license     Apache License, Version 2.0
21
 */
22
23
namespace Uecode\Bundle\QPushBundle\DependencyInjection;
24
25
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
26
use Symfony\Component\DependencyInjection\Definition;
27
use Symfony\Component\DependencyInjection\Reference;
28
use Symfony\Component\DependencyInjection\ContainerBuilder;
29
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
30
use Symfony\Component\Config\FileLocator;
31
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
32
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
33
use RuntimeException;
34
use Exception;
35
36
/**
37
 * @author Keith Kirk <[email protected]>
38
 */
39
class UecodeQPushExtension extends Extension
40
{
41
    /**
42
     * @param array            $configs
43
     * @param ContainerBuilder $container
44
     *
45
     * @throws RuntimeException|InvalidArgumentException|ServiceNotFoundException
46
     */
47 1
    public function load(array $configs, ContainerBuilder $container)
48
    {
49 1
        $configuration = new Configuration();
50 1
        $config = $this->processConfiguration($configuration, $configs);
51
52 1
        $loader = new YamlFileLoader(
53 1
            $container,
54 1
            new FileLocator(__DIR__.'/../Resources/config')
55
        );
56
57 1
        $loader->load('parameters.yml');
58 1
        $loader->load('services.yml');
59
60 1
        $registry = $container->getDefinition('uecode_qpush.registry');
61 1
        $cache    = $config['cache_service'] ?: 'uecode_qpush.file_cache';
62
63 1
        foreach ($config['queues'] as $queue => $values) {
64
65
            // Adds logging property to queue options
66 1
            $values['options']['logging_enabled'] = $config['logging_enabled'];
67
68 1
            $provider   = $values['provider'];
69 1
            $class      = null;
70 1
            $client     = null;
71
72 1
            switch ($config['providers'][$provider]['driver']) {
73 1
                case 'aws':
74 1
                    $class  = $container->getParameter('uecode_qpush.provider.aws');
75 1
                    $client = $this->createAwsClient(
76 1
                        $config['providers'][$provider],
77 1
                        $container,
78 1
                        $provider
79
                    );
80 1
                    break;
81 1
                case 'ironmq':
82 1
                    $class  = $container->getParameter('uecode_qpush.provider.ironmq');
83 1
                    $client = $this->createIronMQClient(
84 1
                        $config['providers'][$provider],
85 1
                        $container,
86 1
                        $provider
87
                    );
88 1
                    break;
89 1
                case 'sync':
90
                    $class  = $container->getParameter('uecode_qpush.provider.sync');
91
                    $client = $this->createSyncClient();
92
                    break;
93 1
                case 'custom':
94
                    $class  = $container->getParameter('uecode_qpush.provider.custom');
95
                    $client = $this->createCustomClient($config['providers'][$provider]['service']);
96
                    break;
97 1
                case 'file':
98 1
                    $class = $container->getParameter('uecode_qpush.provider.file');
99 1
                    $values['options']['path'] = $config['providers'][$provider]['path'];
100 1
                    break;
101
                case 'doctrine':
102
                    $class = $container->getParameter('uecode_qpush.provider.doctrine');
103
                    $client = $this->createDoctrineClient($config['providers'][$provider]);
104
                    break;
105
            }
106
107 1
            $definition = new Definition(
108 1
                $class, [$queue, $values['options'], $client, new Reference($cache), new Reference('logger')]
109
            );
110
111 1
            $definition->setPublic(true);
112
113 1
            $definition->addTag('monolog.logger', ['channel' => 'qpush'])
114 1
                ->addTag(
115 1
                    'uecode_qpush.event_listener',
116
                    [
117 1
                        'event' => "{$queue}.on_notification",
118 1
                        'method' => "onNotification",
119 1
                        'priority' => 255
120
                    ]
121
                )
122 1
                ->addTag(
123 1
                    'uecode_qpush.event_listener',
124
                    [
125 1
                        'event' => "{$queue}.message_received",
126 1
                        'method' => "onMessageReceived",
127
                        'priority' => -255
128
                    ]
129
                );
130
131 1
            $isProviderAWS = $config['providers'][$provider]['driver'] === 'aws';
132 1
            $isQueueNameSet = isset($values['options']['queue_name']) && !empty($values['options']['queue_name']);
133
134 1
            if ($isQueueNameSet && $isProviderAWS) {
135
                $definition->addTag(
136
                    'uecode_qpush.event_listener',
137
                    [
138
                        'event' => "{$values['options']['queue_name']}.on_notification",
139
                        'method' => "onNotification",
140
                        'priority' => 255
141
                    ]
142
                );
143
144
                // Check queue name ends with ".fifo"
145
                $isQueueNameFIFOReady = preg_match("/$(?<=(\.fifo))/", $values['options']['queue_name']) === 1;
146
                if ($values['options']['fifo'] === true && !$isQueueNameFIFOReady) {
147
                    throw new InvalidArgumentException('Queue name must end with ".fifo" on AWS FIFO queues');
148
                }
149
            }
150
151 1
            $name = sprintf('uecode_qpush.%s', $queue);
152 1
            $container->setDefinition($name, $definition);
153
154 1
            $registry->addMethodCall('addProvider', [$queue, new Reference($name)]);
155
        }
156 1
    }
157
158
    /**
159
     * Creates a definition for the AWS provider
160
     *
161
     * @param array            $config    A Configuration array for the client
162
     * @param ContainerBuilder $container The container
163
     * @param string           $name      The provider key
164
     *
165
     * @throws RuntimeException
166
     *
167
     * @return Reference
168
     */
169 1
    private function createAwsClient($config, ContainerBuilder $container, $name)
170
    {
171 1
        $service = sprintf('uecode_qpush.provider.%s', $name);
172
173 1
        if (!$container->hasDefinition($service)) {
174
175 1
            $aws2 = class_exists('Aws\Common\Aws');
176 1
            $aws3 = class_exists('Aws\Sdk');
177 1
            if (!$aws2 && !$aws3) {
178
                throw new RuntimeException('You must require "aws/aws-sdk-php" to use the AWS provider.');
179
            }
180
181
            $awsConfig = [
182 1
                'region' => $config['region']
183
            ];
184
185 1
            $aws = new Definition('Aws\Common\Aws');
186 1
            $aws->setFactory(['Aws\Common\Aws', 'factory']);
187 1
            $aws->setArguments([$awsConfig]);
188
189 1
            if ($aws2) {
190 1
                $aws = new Definition('Aws\Common\Aws');
191 1
                $aws->setFactory(['Aws\Common\Aws', 'factory']);
192
193 1 View Code Duplication
                if (!empty($config['key']) && !empty($config['secret'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
194 1
                    $awsConfig['key']    = $config['key'];
195 1
                    $awsConfig['secret'] = $config['secret'];
196
                }
197
198
            } else {
199
                $aws = new Definition('Aws\Sdk');
200
201 View Code Duplication
                if (!empty($config['key']) && !empty($config['secret'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
202
                    $awsConfig['credentials'] = [
203
                        'key'    => $config['key'],
204
                        'secret' => $config['secret']
205
                    ];
206
                }
207
                $awsConfig['version']  = 'latest';
208
            }
209
210 1
            $aws->setArguments([$awsConfig]);
211
212 1
            $container->setDefinition($service, $aws)->setPublic(false);
213
        }
214
215 1
        return new Reference($service);
216
    }
217
218
    /**
219
     * Creates a definition for the IronMQ provider
220
     *
221
     * @param array            $config    A Configuration array for the provider
222
     * @param ContainerBuilder $container The container
223
     * @param string           $name      The provider key
224
     *
225
     * @throws RuntimeException
226
     *
227
     * @return Reference
228
     */
229 1
    private function createIronMQClient($config, ContainerBuilder $container, $name)
230
    {
231 1
        $service = sprintf('uecode_qpush.provider.%s', $name);
232
233 1
        if (!$container->hasDefinition($service)) {
234
235 1
            if (!class_exists('IronMQ\IronMQ')) {
236
                throw new RuntimeException('You must require "iron-io/iron_mq" to use the Iron MQ provider.');
237
            }
238
239 1
            $ironmq = new Definition('IronMQ\IronMQ');
240 1
            $ironmq->setArguments([
241
                [
242 1
                    'token'         => $config['token'],
243 1
                    'project_id'    => $config['project_id'],
244 1
                    'host'          => sprintf('%s.iron.io', $config['host']),
245 1
                    'port'          => $config['port'],
246 1
                    'api_version'   => $config['api_version']
247
                ]
248
            ]);
249
250 1
            $container->setDefinition($service, $ironmq)->setPublic(false);
251
        }
252
253 1
        return new Reference($service);
254
    }
255
256
    /**
257
     * @return Reference
258
     */
259
    private function createSyncClient()
260
    {
261
        return new Reference('event_dispatcher');
262
    }
263
    
264
    private function createDoctrineClient($config)
265
    {
266
        return new Reference($config['entity_manager']);
267
    }
268
269
    /**
270
     * @param string $serviceId
271
     *
272
     * @return Reference
273
     */
274
    private function createCustomClient($serviceId)
275
    {
276
        return new Reference($serviceId);
277
    }
278
279
    /**
280
     * Returns the Extension Alias
281
     *
282
     * @return string
283
     */
284 1
    public function getAlias()
285
    {
286 1
        return 'uecode_qpush';
287
    }
288
}
289