Completed
Pull Request — master (#110)
by
unknown
10:09
created

UecodeQPushExtension::createDoctrineClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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