Completed
Push — master ( 013881...fadbba )
by Keith
06:26
created

UecodeQPushExtension::getAlias()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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