GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — master (#289)
by Asmir
02:30
created

EightPointsGuzzleExtension::load()   C

Complexity

Conditions 12
Paths 20

Size

Total Lines 56
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 34
c 1
b 0
f 0
nc 20
nop 2
dl 0
loc 56
rs 6.9666

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
namespace EightPoints\Bundle\GuzzleBundle\DependencyInjection;
4
5
use EightPoints\Bundle\GuzzleBundle\Log\Logger;
6
use EightPoints\Bundle\GuzzleBundle\Twig\Extension\DebugExtension;
7
use Symfony\Component\DependencyInjection\ContainerBuilder;
8
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
9
use Symfony\Component\DependencyInjection\Reference;
10
use Symfony\Component\DependencyInjection\Definition;
11
use Symfony\Component\Config\FileLocator;
12
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
13
use Symfony\Component\ExpressionLanguage\Expression;
14
use GuzzleHttp\HandlerStack;
15
16
class EightPointsGuzzleExtension extends Extension
17
{
18
    /** @var \EightPoints\Bundle\GuzzleBundle\PluginInterface[] */
19
    protected $plugins;
20
21
    /**
22
     * @param \EightPoints\Bundle\GuzzleBundle\PluginInterface[] $plugins
23
     */
24
    public function __construct(array $plugins = [])
25
    {
26
        $this->plugins = $plugins;
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function getConfiguration(array $config, ContainerBuilder $container) : Configuration
33
    {
34
        return new Configuration($this->getAlias(), $container->getParameter('kernel.debug'), $this->plugins);
35
    }
36
37
    /**
38
     * Loads the Guzzle configuration.
39
     *
40
     * @param array $configs an array of configuration settings
41
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container a ContainerBuilder instance
42
     *
43
     * @throws \InvalidArgumentException
44
     * @throws \Symfony\Component\DependencyInjection\Exception\BadMethodCallException
45
     * @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
46
     * @throws \Exception
47
     *
48
     * @return void
49
     */
50
    public function load(array $configs, ContainerBuilder $container)
51
    {
52
        $configPath = implode(DIRECTORY_SEPARATOR, [__DIR__, '..', 'Resources', 'config']);
53
        $loader     = new XmlFileLoader($container, new FileLocator($configPath));
54
55
        $loader->load('services.xml');
56
57
        $configuration = new Configuration($this->getAlias(), $container->getParameter('kernel.debug'), $this->plugins);
58
        $config        = $this->processConfiguration($configuration, $configs);
59
        $logging       = $config['logging'] === true;
60
        $profiling     = $config['profiling'] === true;
61
62
        foreach ($this->plugins as $plugin) {
63
            $container->addObjectResource(new \ReflectionClass(get_class($plugin)));
64
            $plugin->load($config, $container);
65
        }
66
67
        foreach ($config['clients'] as $name => $options) {
68
            $options['logging'] = $logging ? ($options['logging'] ?? true) : false;
69
70
            $argument = [
71
                'base_uri' => $options['base_url'],
72
                'handler'  => $this->createHandler($container, $name, $options, $profiling)
73
            ];
74
75
            // if present, add default options to the constructor argument for the Guzzle client
76
            if (isset($options['options']) && is_array($options['options'])) {
77
                foreach ($options['options'] as $key => $value) {
78
                    if ($value === null || (is_array($value) && count($value) === 0)) {
79
                        continue;
80
                    }
81
82
                    $argument[$key] = $value;
83
                }
84
            }
85
86
            $client = new Definition($options['class']);
87
            $client->addArgument($argument);
88
            $client->setPublic(true);
89
            $client->setLazy($options['lazy']);
90
91
            // set service name based on client name
92
            $serviceName = sprintf('%s.client.%s', $this->getAlias(), $name);
93
            $container->setDefinition($serviceName, $client);
94
        }
95
96
        $clientsWithLogging = array_filter($config['clients'], function ($options) use ($logging) {
97
            return $options['logging'] !== false && $logging !== false;
98
        });
99
100
        if (count($clientsWithLogging)>0) {
101
            $this->defineTwigDebugExtension($container);
102
            $this->defineDataCollector($container, $config['slow_response_time'] / 1000);
103
            $this->defineFormatter($container);
104
            $this->defineSymfonyLogFormatter($container);
105
            $this->defineSymfonyLogMiddleware($container);
106
        }
107
    }
108
109
    /**
110
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
111
     * @param string $clientName
112
     * @param array $options
113
     * @param bool $profiling
114
     *
115
     * @throws \Symfony\Component\DependencyInjection\Exception\BadMethodCallException
116
     * @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
117
     *
118
     * @return \Symfony\Component\DependencyInjection\Definition
119
     */
120
    protected function createHandler(ContainerBuilder $container, string $clientName, array $options, bool $profiling) : Definition
121
    {
122
        // Event Dispatching service
123
        $eventServiceName = sprintf('eight_points_guzzle.middleware.event_dispatch.%s', $clientName);
124
        $eventService = $this->createEventMiddleware($clientName);
125
        $container->setDefinition($eventServiceName, $eventService);
126
127
        // Create the event Dispatch Middleware
128
        $eventExpression  = new Expression(sprintf("service('%s').dispatchEvent()", $eventServiceName));
129
130
        $handler = new Definition(HandlerStack::class);
131
        $handler->setFactory([HandlerStack::class, 'create']);
132
        if (isset($options['handler'])) {
133
134
            $handlerServiceName = sprintf('eight_points_guzzle.handler.%s', $clientName);
135
            $handlerService = new Definition($options['handler']);
136
            $container->setDefinition($handlerServiceName, $handlerService);
137
138
            $handler->addArgument(new Reference($handlerServiceName));
139
        }
140
        $handler->setPublic(true);
141
        $handler->setLazy($options['lazy']);
142
143
        $handlerStackServiceName = sprintf('eight_points_guzzle.handler_stack.%s', $clientName);
144
        $container->setDefinition($handlerStackServiceName, $handler);
145
146
        if ($profiling) {
147
            $this->defineProfileMiddleware($container, $handler, $clientName);
148
        }
149
150
        foreach ($this->plugins as $plugin) {
151
            if (isset($options['plugin'][$plugin->getPluginName()])) {
152
                $plugin->loadForClient($options['plugin'][$plugin->getPluginName()], $container, $clientName, $handler);
153
            }
154
        }
155
156
        if ($options['logging'] > Logger::LOG_MODE_NONE) {
157
            $loggerName = $this->defineLogger($container, $options['logging'], $clientName);
158
            $this->defineLogMiddleware($container, $handler, $clientName, $loggerName);
159
            $this->defineRequestTimeMiddleware($container, $handler, $clientName, $loggerName);
160
            $this->attachSymfonyLogMiddlewareToHandler($handler);
161
        }
162
163
        // goes on the end of the stack.
164
        $handler->addMethodCall('unshift', [$eventExpression, 'events']);
165
166
        return $handler;
167
    }
168
169
    /**
170
     * @param ContainerBuilder $container
171
     *
172
     * @return void
173
     */
174
    protected function defineTwigDebugExtension(ContainerBuilder $container) : void
175
    {
176
        $twigDebugExtensionDefinition = new Definition(DebugExtension::class);
177
        $twigDebugExtensionDefinition->addTag('twig.extension');
178
        $twigDebugExtensionDefinition->setPublic(false);
179
        $container->setDefinition('eight_points_guzzle.twig_extension.debug', $twigDebugExtensionDefinition);
180
    }
181
182
    /**
183
     * Define Logger
184
     *
185
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
186
     *
187
     * @throws \Symfony\Component\DependencyInjection\Exception\BadMethodCallException
188
     *
189
     * @return void
190
     */
191
    protected function defineLogger(ContainerBuilder $container, int $logMode, string $clientName) : string
192
    {
193
        $loggerDefinition = new Definition('%eight_points_guzzle.logger.class%');
194
        $loggerDefinition->setPublic(false);
195
        $loggerDefinition->setArgument(0, $logMode);
196
        $loggerDefinition->addTag('eight_points_guzzle.logger');
197
198
        $loggerName = sprintf('eight_points_guzzle.%s_logger', $clientName);
199
        $container->setDefinition($loggerName, $loggerDefinition);
200
201
        return $loggerName;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $loggerName returns the type string which is incompatible with the documented return type void.
Loading history...
202
    }
203
204
    /**
205
     * Define Data Collector
206
     *
207
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
208
     * @param float $slowResponseTime
209
     *
210
     * @throws \Symfony\Component\DependencyInjection\Exception\BadMethodCallException
211
     *
212
     * @return void
213
     */
214
    protected function defineDataCollector(ContainerBuilder $container, float $slowResponseTime) : void
215
    {
216
        $dataCollectorDefinition = new Definition('%eight_points_guzzle.data_collector.class%');
217
        $dataCollectorDefinition->addArgument(array_map(function ($loggerId) : Reference {
218
            return new Reference($loggerId);
219
        }, array_keys($container->findTaggedServiceIds('eight_points_guzzle.logger'))));
220
221
        $dataCollectorDefinition->addArgument($slowResponseTime);
222
        $dataCollectorDefinition->setPublic(false);
223
        $dataCollectorDefinition->addTag('data_collector', [
224
            'id' => 'eight_points_guzzle',
225
            'template' => '@EightPointsGuzzle/debug.html.twig',
226
        ]);
227
        $container->setDefinition('eight_points_guzzle.data_collector', $dataCollectorDefinition);
228
    }
229
230
    /**
231
     * Define Formatter
232
     *
233
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
234
     *
235
     * @throws \Symfony\Component\DependencyInjection\Exception\BadMethodCallException
236
     *
237
     * @return void
238
     */
239
    protected function defineFormatter(ContainerBuilder $container) : void
240
    {
241
        $formatterDefinition = new Definition('%eight_points_guzzle.formatter.class%');
242
        $formatterDefinition->setPublic(true);
243
        $container->setDefinition('eight_points_guzzle.formatter', $formatterDefinition);
244
    }
245
246
    /**
247
     * Define Request Time Middleware
248
     *
249
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
250
     * @param \Symfony\Component\DependencyInjection\Definition $handler
251
     * @param string $clientName
252
     *
253
     * @return void
254
     */
255
    protected function defineRequestTimeMiddleware(ContainerBuilder $container, Definition $handler, string $clientName, string $loggerName) : void
256
    {
257
        $requestTimeMiddlewareDefinitionName = sprintf('eight_points_guzzle.middleware.request_time.%s', $clientName);
258
        $requestTimeMiddlewareDefinition = new Definition('%eight_points_guzzle.middleware.request_time.class%');
259
        $requestTimeMiddlewareDefinition->addArgument(new Reference($loggerName));
260
        $requestTimeMiddlewareDefinition->addArgument(new Reference('eight_points_guzzle.data_collector'));
261
        $requestTimeMiddlewareDefinition->setPublic(true);
262
        $container->setDefinition($requestTimeMiddlewareDefinitionName, $requestTimeMiddlewareDefinition);
263
264
        $requestTimeExpression = new Expression(sprintf("service('%s')", $requestTimeMiddlewareDefinitionName));
265
        $handler->addMethodCall('after', ['log', $requestTimeExpression, 'request_time']);
266
    }
267
268
    /**
269
     * Define Log Middleware for client
270
     *
271
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
272
     * @param \Symfony\Component\DependencyInjection\Definition $handler
273
     * @param string $clientName
274
     *
275
     * @return void
276
     */
277
    protected function defineLogMiddleware(ContainerBuilder $container, Definition $handler, string $clientName, string $loggerName) : void
278
    {
279
        $logMiddlewareDefinitionName = sprintf('eight_points_guzzle.middleware.log.%s', $clientName);
280
        $logMiddlewareDefinition = new Definition('%eight_points_guzzle.middleware.log.class%');
281
        $logMiddlewareDefinition->addArgument(new Reference($loggerName));
282
        $logMiddlewareDefinition->addArgument(new Reference('eight_points_guzzle.formatter'));
283
        $logMiddlewareDefinition->setPublic(true);
284
        $container->setDefinition($logMiddlewareDefinitionName, $logMiddlewareDefinition);
285
286
        $logExpression = new Expression(sprintf("service('%s').log()", $logMiddlewareDefinitionName));
287
        $handler->addMethodCall('push', [$logExpression, 'log']);
288
    }
289
290
    /**
291
     * Define Profile Middleware for client
292
     *
293
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
294
     * @param \Symfony\Component\DependencyInjection\Definition $handler
295
     * @param string $clientName
296
     *
297
     * @return void
298
     */
299
    protected function defineProfileMiddleware(ContainerBuilder $container, Definition $handler, string $clientName) : void
300
    {
301
        $profileMiddlewareDefinitionName = sprintf('eight_points_guzzle.middleware.profile.%s', $clientName);
302
        $profileMiddlewareDefinition = new Definition('%eight_points_guzzle.middleware.profile.class%');
303
        $profileMiddlewareDefinition->addArgument(new Reference('debug.stopwatch'));
304
        $profileMiddlewareDefinition->setPublic(true);
305
        $container->setDefinition($profileMiddlewareDefinitionName, $profileMiddlewareDefinition);
306
307
        $profileExpression = new Expression(sprintf("service('%s').profile()", $profileMiddlewareDefinitionName));
308
        $handler->addMethodCall('push', [$profileExpression, 'profile']);
309
    }
310
311
    /**
312
     * @param \Symfony\Component\DependencyInjection\Definition $handler
313
     *
314
     * @return void
315
     */
316
    protected function attachSymfonyLogMiddlewareToHandler(Definition $handler) : void
317
    {
318
        $logExpression = new Expression(sprintf("service('%s')", 'eight_points_guzzle.middleware.symfony_log'));
319
        $handler->addMethodCall('push', [$logExpression, 'symfony_log']);
320
    }
321
322
    /**
323
     * Create Middleware For dispatching events
324
     *
325
     * @param string $name
326
     *
327
     * @return \Symfony\Component\DependencyInjection\Definition
328
     */
329
    protected function createEventMiddleware(string $name) : Definition
330
    {
331
        $eventMiddleWare = new Definition('%eight_points_guzzle.middleware.event_dispatcher.class%');
332
        $eventMiddleWare->addArgument(new Reference('event_dispatcher'));
333
        $eventMiddleWare->addArgument($name);
334
        $eventMiddleWare->setPublic(true);
335
336
        return $eventMiddleWare;
337
    }
338
339
    /**
340
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
341
     *
342
     * @return void
343
     */
344
    protected function defineSymfonyLogFormatter(ContainerBuilder $container) : void
345
    {
346
        $formatterDefinition = new Definition('%eight_points_guzzle.symfony_log_formatter.class%');
347
        $formatterDefinition->setArguments(['%eight_points_guzzle.symfony_log_formatter.pattern%']);
348
        $formatterDefinition->setPublic(true);
349
        $container->setDefinition('eight_points_guzzle.symfony_log_formatter', $formatterDefinition);
350
    }
351
352
    /**
353
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
354
     *
355
     * @return void
356
     */
357
    protected function defineSymfonyLogMiddleware(ContainerBuilder $container) : void
358
    {
359
        $logMiddlewareDefinition = new Definition('%eight_points_guzzle.middleware.symfony_log.class%');
360
        $logMiddlewareDefinition->addArgument(new Reference('logger'));
361
        $logMiddlewareDefinition->addArgument(new Reference('eight_points_guzzle.symfony_log_formatter'));
362
        $logMiddlewareDefinition->setPublic(true);
363
        $logMiddlewareDefinition->addTag('monolog.logger', ['channel' => 'eight_points_guzzle']);
364
        $container->setDefinition('eight_points_guzzle.middleware.symfony_log', $logMiddlewareDefinition);
365
    }
366
367
    /**
368
     * Returns alias of extension
369
     *
370
     * @return string
371
     */
372
    public function getAlias() : string
373
    {
374
        return 'eight_points_guzzle';
375
    }
376
}
377