Passed
Push — master ( 654348...8ec1ee )
by Dāvis
03:00
created

Guzzle::buildGuzzleConfig()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 4
nop 2
dl 0
loc 14
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Sludio\HelperBundle\DependencyInjection\Component;
4
5
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
6
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
7
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
8
use Symfony\Component\Config\Definition\Processor;
9
use Symfony\Component\Config\FileLocator;
10
use Symfony\Component\DependencyInjection\ContainerBuilder;
11
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
12
use Symfony\Component\Config\Loader\LoaderInterface;
13
14
class Guzzle
15
{
16
    const NAME = 'sludio_helper.guzzle';
17
18
    public function configure(ContainerBuilder &$container)
19
    {
20
        $dataCollector = $container->getDefinition(self::NAME.'.data_collector.guzzle');
21
        $dataCollector->replaceArgument(0, $container->getParameter(self::NAME.'.profiler')['max_body_size']);
22
23
        if (!$container->getParameter(self::NAME.'.profiler')['enabled']) {
24
            $container->removeDefinition(self::NAME.'.middleware.history');
25
            $container->removeDefinition(self::NAME.'.middleware.stopwatch');
26
            $container->removeDefinition(self::NAME.'.data_collector.guzzle');
27
        }
28
29
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../../Guzzle/Resources/config'));
30
31
        $this->processLoggerConfiguration($container->getParameter(self::NAME.'.logger'), $container);
32
33
        $this->processMockConfiguration($container->getParameter(self::NAME.'.mock'), $container, $loader, $container->getParameter(self::NAME.'.profiler')['enabled']);
34
35
        $this->processCacheConfiguration($container->getParameter(self::NAME.'.cache'), $container, $container->getParameter(self::NAME.'.profiler')['enabled']);
36
37
        $this->processClientsConfiguration($container->getParameter(self::NAME.'.clients'), $container, $container->getParameter(self::NAME.'.profiler')['enabled']);
38
    }
39
40
    private function processLoggerConfiguration(array $config, ContainerBuilder $container)
41
    {
42
        if (!$config['enabled']) {
43
            $container->removeDefinition(self::NAME.'.middleware.logger');
44
            $container->removeDefinition(self::NAME.'.logger.message_formatter');
45
46
            return;
47
        }
48
49
        $loggerDefinition = $container->getDefinition(self::NAME.'.middleware.logger');
50
51
        if ($config['service']) {
52
            $loggerDefinition->replaceArgument(0, new Reference($config['service']));
0 ignored issues
show
Bug introduced by
The type Sludio\HelperBundle\Depe...ion\Component\Reference was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
53
        }
54
55
        if ($config['format']) {
56
            $formatterDefinition = $container->getDefinition(self::NAME.'.logger.message_formatter');
57
            $formatterDefinition->replaceArgument(0, $config['format']);
58
        }
59
60
        if ($config['level']) {
61
            $loggerDefinition->replaceArgument(2, $config['level']);
62
        }
63
    }
64
65
    private function processMockConfiguration(array $config, ContainerBuilder $container, LoaderInterface $loader, $debug)
0 ignored issues
show
Unused Code introduced by
The parameter $loader is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

65
    private function processMockConfiguration(array $config, ContainerBuilder $container, /** @scrutinizer ignore-unused */ LoaderInterface $loader, $debug)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
66
    {
67
        if (!$config['enabled']) {
68
            return;
69
        }
70
71
        $storage = $container->getDefinition(self::NAME.'.mock.storage');
72
        $storage->setArguments([
73
            $config['storage_path'],
74
            $config['request_headers_blacklist'],
75
            $config['response_headers_blacklist'],
76
        ]);
77
78
        $middleware = $container->getDefinition(self::NAME.'.middleware.mock');
79
        $middleware->replaceArgument(1, $config['mode']);
80
81
        $middleware->replaceArgument(2, $debug);
82
    }
83
84
    private function processCacheConfiguration(array $config, ContainerBuilder $container, $debug)
85
    {
86
        if (!$config['enabled']) {
87
            $container->removeDefinition(self::NAME.'.middleware.cache');
88
89
            return;
90
        }
91
92
        $container->getDefinition(self::NAME.'.middleware.cache')->addArgument($debug);
93
94
        $container->setAlias(self::NAME.'.cache_adapter', $config['adapter']);
95
    }
96
97
    private function processClientsConfiguration(array $config, ContainerBuilder $container, $debug)
98
    {
99
        foreach ($config as $name => $options) {
100
            $client = new Definition($options['class']);
0 ignored issues
show
Bug introduced by
The type Sludio\HelperBundle\Depe...on\Component\Definition was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
101
            $client->setLazy($options['lazy']);
102
103
            if (isset($options['config'])) {
104
                if (!is_array($options['config'])) {
105
                    throw new InvalidArgumentException(sprintf('Config for "'.self::NAME.'.client.%s" should be an array, but got %s', $name, gettype($options['config'])));
0 ignored issues
show
Bug introduced by
The type Sludio\HelperBundle\Depe...nvalidArgumentException was not found. Did you mean InvalidArgumentException? If so, make sure to prefix the type with \.
Loading history...
106
                }
107
                $client->addArgument($this->buildGuzzleConfig($options['config'], $debug));
108
            }
109
110
            $attributes = [];
111
112
            if (!empty($options['middleware'])) {
113
                if ($debug) {
114
                    $addDebugMiddleware = true;
115
116
                    foreach ($options['middleware'] as $middleware) {
117
                        if ('!' === ($middleware[0])) {
118
                            $addDebugMiddleware = false;
119
                        }
120
                    }
121
122
                    if ($addDebugMiddleware) {
123
                        $options['middleware'] = array_merge($options['middleware'], [
124
                            'stopwatch',
125
                            'history',
126
                            'logger',
127
                        ]);
128
                    }
129
                }
130
131
                $attributes['middleware'] = implode(' ', array_unique($options['middleware']));
132
            }
133
134
            $client->addTag(MiddlewarePass::CLIENT_TAG, $attributes);
0 ignored issues
show
Bug introduced by
The type Sludio\HelperBundle\Depe...omponent\MiddlewarePass was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
135
136
            $clientServiceId = sprintf(self::NAME.'.client.%s', $name);
137
            $container->setDefinition($clientServiceId, $client);
138
139
            if (isset($options['alias'])) {
140
                $container->setAlias($options['alias'], $clientServiceId);
141
            }
142
        }
143
    }
144
145
    private function buildGuzzleConfig(array $config, $debug)
146
    {
147
        if (isset($config['handler'])) {
148
            $config['handler'] = new Reference($config['handler']);
149
        }
150
151
        if ($debug && function_exists('curl_init')) {
152
            $config['on_stats'] = [
153
                new Reference(self::NAME.'.data_collector.history_bag'),
154
                'addStats',
155
            ];
156
        }
157
158
        return $config;
159
    }
160
}