Completed
Push — master ( ac8b27...2b7ee8 )
by Keith
06:55 queued 04:40
created

UecodeQPushExtension   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 225
Duplicated Lines 4.44 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 77.27%

Importance

Changes 22
Bugs 1 Features 6
Metric Value
wmc 25
c 22
b 1
f 6
lcom 1
cbo 7
dl 10
loc 225
ccs 85
cts 110
cp 0.7727
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
D load() 0 97 10
C createAwsClient() 10 51 9
B createIronMQClient() 0 29 3
A createSyncClient() 0 4 1
A createCustomClient() 0 4 1
A getAlias() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 1
                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 1
                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 1
                case 'sync':
80
                    $class  = $container->getParameter('uecode_qpush.provider.sync');
81
                    $client = $this->createSyncClient();
82
                    break;
83 1
                case 'custom':
84
                    $class  = $container->getParameter('uecode_qpush.provider.custom');
85
                    $client = $this->createCustomClient($config['providers'][$provider]['service']);
86
                    break;
87 1
                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
            $definition->addTag('monolog.logger', ['channel' => 'qpush'])
98 1
                ->addTag(
99 1
                    'uecode_qpush.event_listener',
100
                    [
101 1
                        'event' => "{$queue}.on_notification",
102 1
                        'method' => "onNotification",
103 1
                        'priority' => 255
104
                    ]
105
                )
106 1
                ->addTag(
107 1
                    'uecode_qpush.event_listener',
108
                    [
109 1
                        'event' => "{$queue}.message_received",
110 1
                        'method' => "onMessageReceived",
111
                        'priority' => -255
112
                    ]
113
                );
114
115 1
            if (!empty($values['options']['queue_name'])
116 1
                && $config['providers'][$provider]['driver'] == 'aws'
117
            ) {
118
                $definition->addTag(
119
                    'uecode_qpush.event_listener',
120
                    [
121
                        'event' => "{$values['options']['queue_name']}.on_notification",
122
                        'method' => "onNotification",
123
                        'priority' => 255
124
                    ]
125
                );
126
            }
127
128 1
            $name = sprintf('uecode_qpush.%s', $queue);
129 1
            $container->setDefinition($name, $definition);
130
131 1
            $registry->addMethodCall('addProvider', [$queue, new Reference($name)]);
132
        }
133 1
    }
134
135
    /**
136
     * Creates a definition for the AWS provider
137
     *
138
     * @param array            $config    A Configuration array for the client
139
     * @param ContainerBuilder $container The container
140
     * @param string           $name      The provider key
141
     *
142
     * @return Reference
143
     */
144 1
    private function createAwsClient($config, ContainerBuilder $container, $name)
145
    {
146 1
        $service = sprintf('uecode_qpush.provider.%s', $name);
147
148 1
        if (!$container->hasDefinition($service)) {
149
150 1
            $aws2 = class_exists('Aws\Common\Aws');
151 1
            $aws3 = class_exists('Aws\Sdk');
152 1
            if (!$aws2 && !$aws3) {
153
                throw new \RuntimeException(
154
                    'You must require "aws/aws-sdk-php" to use the AWS provider.'
155
                );
156
            }
157
158
            $awsConfig = [
159 1
                'region' => $config['region']
160
            ];
161
162 1
            $aws = new Definition('Aws\Common\Aws');
163 1
            $aws->setFactory(['Aws\Common\Aws', 'factory']);
164 1
            $aws->setArguments([$awsConfig]);
165
166 1
            if ($aws2) {
167 1
                $aws = new Definition('Aws\Common\Aws');
168 1
                $aws->setFactory(['Aws\Common\Aws', 'factory']);
169
170 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...
171 1
                    $awsConfig['key']    = $config['key'];
172 1
                    $awsConfig['secret'] = $config['secret'];
173
                }
174
175
            } else {
176
                $aws = new Definition('Aws\Sdk');
177
178 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...
179
                    $awsConfig['credentials'] = [
180
                        'key'    => $config['key'],
181
                        'secret' => $config['secret']
182
                    ];
183
                }
184
                $awsConfig['version']  = 'latest';
185
            }
186
187 1
            $aws->setArguments([$awsConfig]);
188
189 1
            $container->setDefinition($service, $aws)
190 1
                ->setPublic(false);
191
        }
192
193 1
        return new Reference($service);
194
    }
195
196
    /**
197
     * Creates a definition for the IronMQ provider
198
     *
199
     * @param array            $config    A Configuration array for the provider
200
     * @param ContainerBuilder $container The container
201
     * @param string           $name      The provider key
202
     *
203
     * @return Reference
204
     */
205 1
    private function createIronMQClient($config, ContainerBuilder $container, $name)
206
    {
207 1
        $service = sprintf('uecode_qpush.provider.%s', $name);
208
209 1
        if (!$container->hasDefinition($service)) {
210
211 1
            if (!class_exists('IronMQ\IronMQ')) {
212
                throw new \RuntimeException(
213
                    'You must require "iron-io/iron_mq" to use the Iron MQ provider.'
214
                );
215
            }
216
217 1
            $ironmq = new Definition('IronMQ\IronMQ');
218 1
            $ironmq->setArguments([
219
                [
220 1
                    'token'         => $config['token'],
221 1
                    'project_id'    => $config['project_id'],
222 1
                    'host'          => sprintf('%s.iron.io', $config['host']),
223 1
                    'port'          => $config['port'],
224 1
                    'api_version'   => $config['api_version']
225
                ]
226
            ]);
227
228 1
            $container->setDefinition($service, $ironmq)
229 1
                ->setPublic(false);
230
        }
231
232 1
        return new Reference($service);
233
    }
234
235
    private function createSyncClient()
236
    {
237
        return new Reference('event_dispatcher');
238
    }
239
240
    /**
241
     * @param string $serviceId
242
     *
243
     * @return Reference
244
     */
245
    private function createCustomClient($serviceId)
246
    {
247
        return new Reference($serviceId);
248
    }
249
250
    /**
251
     * Returns the Extension Alias
252
     *
253
     * @return string
254
     */
255 1
    public function getAlias()
256
    {
257 1
        return 'uecode_qpush';
258
    }
259
}
260