Completed
Push — master ( 9b6362...d575cd )
by Keith
03:01
created

UecodeQPushExtension::createAwsClient()   C

Complexity

Conditions 9
Paths 6

Size

Total Lines 51
Code Lines 30

Duplication

Lines 10
Ratio 19.61 %

Code Coverage

Tests 20
CRAP Score 10.8889

Importance

Changes 6
Bugs 0 Features 3
Metric Value
c 6
b 0
f 3
dl 10
loc 51
ccs 20
cts 28
cp 0.7143
rs 6.2727
cc 9
eloc 30
nc 6
nop 3
crap 10.8889

How to fix   Long Method   

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
32
/**
33
 * @author Keith Kirk <[email protected]>
34
 */
35
class UecodeQPushExtension extends Extension
36
{
37 1
    public function load(array $configs, ContainerBuilder $container)
38
    {
39 1
        $configuration = new Configuration();
40 1
        $config = $this->processConfiguration($configuration, $configs);
41
42 1
        $loader = new YamlFileLoader(
43
            $container,
44 1
            new FileLocator(__DIR__.'/../Resources/config')
45
        );
46
47 1
        $loader->load('parameters.yml');
48 1
        $loader->load('services.yml');
49
50 1
        $registry = $container->getDefinition('uecode_qpush.registry');
51 1
        $cache    = $config['cache_service'] ?: 'uecode_qpush.file_cache';
52
53 1
        foreach ($config['queues'] as $queue => $values) {
54
55
            // Adds logging property to queue options
56 1
            $values['options']['logging_enabled'] = $config['logging_enabled'];
57
58 1
            $provider   = $values['provider'];
59 1
            $class      = null;
60 1
            $client     = null;
61
62 1
            switch ($config['providers'][$provider]['driver']) {
63
                case 'aws':
64 1
                    $class  = $container->getParameter('uecode_qpush.provider.aws');
65 1
                    $client = $this->createAwsClient(
66 1
                        $config['providers'][$provider],
67
                        $container,
68
                        $provider
69
                    );
70 1
                    break;
71
                case 'ironmq':
72 1
                    $class  = $container->getParameter('uecode_qpush.provider.ironmq');
73 1
                    $client = $this->createIronMQClient(
74 1
                        $config['providers'][$provider],
75
                        $container,
76
                        $provider
77
                    );
78 1
                    break;
79
                case 'sync':
80
                    $class  = $container->getParameter('uecode_qpush.provider.sync');
81
                    $client = $this->createSyncClient();
82
                    break;
83
                case 'custom':
84
                    $class  = $container->getParameter('uecode_qpush.provider.custom');
85
                    $client = $this->createCustomClient($config['providers'][$provider]['service']);
86
                    break;
87
                case 'file':
88 1
                    $class = $container->getParameter('uecode_qpush.provider.file');
89 1
                    $values['options']['path'] = $config['providers'][$provider]['path'];
90 1
                    break;
91
            }
92
93 1
            $definition = new Definition(
94 1
                $class, [$queue, $values['options'], $client, new Reference($cache), new Reference('logger')]
95
            );
96
97 1
            $name = sprintf('uecode_qpush.%s', $queue);
98
99 1
            $container->setDefinition($name, $definition)
100 1
                ->addTag('monolog.logger', ['channel' => 'qpush'])
101 1
                ->addTag(
102 1
                    'uecode_qpush.event_listener',
103
                    [
104 1
                        'event' => "{$queue}.on_notification",
105 1
                        'method' => "onNotification",
106 1
                        'priority' => 255
107
                    ]
108
                )
109 1
                ->addTag(
110 1
                    'uecode_qpush.event_listener',
111
                    [
112 1
                        'event' => "{$queue}.message_received",
113 1
                        'method' => "onMessageReceived",
114
                        'priority' => -255
115
                    ]
116
                )
117
            ;
118
119 1
            $registry->addMethodCall('addProvider', [$queue, new Reference($name)]);
120
        }
121 1
    }
122
123
    /**
124
     * Creates a definition for the AWS provider
125
     *
126
     * @param array            $config    A Configuration array for the client
127
     * @param ContainerBuilder $container The container
128
     * @param string           $name      The provider key
129
     *
130
     * @return Reference
131
     */
132 1
    private function createAwsClient($config, ContainerBuilder $container, $name)
133
    {
134 1
        $service = sprintf('uecode_qpush.provider.%s', $name);
135
136 1
        if (!$container->hasDefinition($service)) {
137
138 1
            $aws2 = class_exists('Aws\Common\Aws');
139 1
            $aws3 = class_exists('Aws\Sdk');
140 1
            if (!$aws2 && !$aws3) {
141
                throw new \RuntimeException(
142
                    'You must require "aws/aws-sdk-php" to use the AWS provider.'
143
                );
144
            }
145
146
            $awsConfig = [
147 1
                'region' => $config['region']
148
            ];
149
150 1
            $aws = new Definition('Aws\Common\Aws');
151 1
            $aws->setFactory(['Aws\Common\Aws', 'factory']);
152 1
            $aws->setArguments([$awsConfig]);
153
154 1
            if ($aws2) {
155 1
                $aws = new Definition('Aws\Common\Aws');
156 1
                $aws->setFactory(['Aws\Common\Aws', 'factory']);
157
158 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...
159 1
                    $awsConfig['key']    = $config['key'];
160 1
                    $awsConfig['secret'] = $config['secret'];
161
                }
162
163
            } else {
164
                $aws = new Definition('Aws\Sdk');
165
166 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...
167
                    $awsConfig['credentials'] = [
168
                        'key'    => $config['key'],
169
                        'secret' => $config['secret']
170
                    ];
171
                }
172
                $awsConfig['version']  = 'latest';
173
            }
174
175 1
            $aws->setArguments([$awsConfig]);
176
177 1
            $container->setDefinition($service, $aws)
178 1
                ->setPublic(false);
179
        }
180
181 1
        return new Reference($service);
182
    }
183
184
    /**
185
     * Creates a definition for the IronMQ provider
186
     *
187
     * @param array            $config    A Configuration array for the provider
188
     * @param ContainerBuilder $container The container
189
     * @param string           $name      The provider key
190
     *
191
     * @return Reference
192
     */
193 1
    private function createIronMQClient($config, ContainerBuilder $container, $name)
194
    {
195 1
        $service = sprintf('uecode_qpush.provider.%s', $name);
196
197 1
        if (!$container->hasDefinition($service)) {
198
199 1
            if (!class_exists('IronMQ\IronMQ')) {
200
                throw new \RuntimeException(
201
                    'You must require "iron-io/iron_mq" to use the Iron MQ provider.'
202
                );
203
            }
204
205 1
            $ironmq = new Definition('IronMQ\IronMQ');
206 1
            $ironmq->setArguments([
207
                [
208 1
                    'token'         => $config['token'],
209 1
                    'project_id'    => $config['project_id'],
210 1
                    'host'          => sprintf('%s.iron.io', $config['host']),
211 1
                    'port'          => $config['port'],
212 1
                    'api_version'   => $config['api_version']
213
                ]
214
            ]);
215
216 1
            $container->setDefinition($service, $ironmq)
217 1
                ->setPublic(false);
218
        }
219
220 1
        return new Reference($service);
221
    }
222
223
    private function createSyncClient()
224
    {
225
        return new Reference('event_dispatcher');
226
    }
227
228
    /**
229
     * @param string $serviceId
230
     *
231
     * @return Reference
232
     */
233
    private function createCustomClient($serviceId)
234
    {
235
        return new Reference($serviceId);
236
    }
237
238
    /**
239
     * Returns the Extension Alias
240
     *
241
     * @return string
242
     */
243 1
    public function getAlias()
244
    {
245 1
        return 'uecode_qpush';
246
    }
247
}
248