Completed
Pull Request — 2.x (#167)
by Fabien
01:14
created

SonataCacheExtension::configureCache()   F

Complexity

Conditions 12
Paths 256

Size

Total Lines 98
Code Lines 68

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 98
rs 3.7956
c 0
b 0
f 0
cc 12
eloc 68
nc 256
nop 2

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
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\CacheBundle\DependencyInjection;
13
14
use Symfony\Component\Config\Definition\Processor;
15
use Symfony\Component\Config\FileLocator;
16
use Symfony\Component\DependencyInjection\ContainerBuilder;
17
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
18
use Symfony\Component\DependencyInjection\Reference;
19
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
20
21
/**
22
 * PageExtension.
23
 *
24
 *
25
 * @author     Thomas Rabaix <[email protected]>
26
 */
27
class SonataCacheExtension extends Extension
28
{
29
    /**
30
     * Loads the url shortener configuration.
31
     *
32
     * @param array            $configs   An array of configuration settings
33
     * @param ContainerBuilder $container A ContainerBuilder instance
34
     */
35
    public function load(array $configs, ContainerBuilder $container)
36
    {
37
        $processor = new Processor();
38
        $configuration = new Configuration();
39
        $config = $processor->processConfiguration($configuration, $configs);
40
41
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
42
        $loader->load('cache.xml');
43
        $loader->load('counter.xml');
44
45
        $useOrm = 'auto' == $config['cache_invalidation']['orm_listener'] ?
46
            class_exists('Doctrine\\ORM\\Version') :
47
            $config['cache_invalidation']['orm_listener'];
48
49
        if ($useOrm) {
50
            $loader->load('orm.xml');
51
        }
52
53
        $usePhpcrOdm = 'auto' == $config['cache_invalidation']['phpcr_odm_listener'] ?
54
            class_exists('Doctrine\\PHPCR\\ODM\\Version') :
55
            $config['cache_invalidation']['phpcr_odm_listener'];
56
        if ($usePhpcrOdm) {
57
            $loader->load('phpcr_odm.xml');
58
        }
59
60
        $this->configureInvalidation($container, $config);
61
        if ($useOrm) {
62
            $container->getDefinition('sonata.cache.orm.event_subscriber')
63
                ->addTag('doctrine.event_subscriber')
64
            ;
65
        }
66
        if ($usePhpcrOdm) {
67
            $container->getDefinition('sonata.cache.phpcr_odm.event_subscriber')
68
                ->addTag('doctrine_phpcr.event_subscriber')
69
            ;
70
        }
71
        $this->configureCache($container, $config);
72
        $this->configureCounter($container, $config);
73
    }
74
75
    /**
76
     * @param ContainerBuilder $container
77
     * @param array            $config
78
     */
79
    public function configureInvalidation(ContainerBuilder $container, $config)
80
    {
81
        $cacheManager = $container->getDefinition('sonata.cache.manager');
82
83
        $cacheManager->replaceArgument(0, new Reference($config['cache_invalidation']['service']));
84
85
        $recorder = $container->getDefinition('sonata.cache.model_identifier');
86
        foreach ($config['cache_invalidation']['classes'] as $class => $method) {
87
            $recorder->addMethodCall('addClass', [$class, $method]);
88
        }
89
90
        $cacheManager->addMethodCall('setRecorder', [new Reference($config['cache_invalidation']['recorder'])]);
91
    }
92
93
    /**
94
     * @param ContainerBuilder $container
95
     * @param array            $config
96
     *
97
     * @throws \RuntimeException if the Mongo or Memcached library is not installed
98
     */
99
    public function configureCache(ContainerBuilder $container, $config)
100
    {
101
        if ($config['default_cache']) {
102
            $container->setAlias('sonata.cache', $config['default_cache']);
103
        }
104
105
        if (isset($config['caches']['esi'])) {
106
            $container
107
                ->getDefinition('sonata.cache.esi')
108
                ->replaceArgument(0, $config['caches']['esi']['token'])
109
                ->replaceArgument(1, $config['caches']['esi']['servers'])
110
                ->replaceArgument(3, 3 === $config['caches']['esi']['version'] ? 'ban' : 'purge');
111
        } else {
112
            $container->removeDefinition('sonata.cache.esi');
113
        }
114
115
        if (isset($config['caches']['ssi'])) {
116
            $container
117
                ->getDefinition('sonata.cache.ssi')
118
                ->replaceArgument(0, $config['caches']['ssi']['token'])
119
            ;
120
        } else {
121
            $container->removeDefinition('sonata.cache.ssi');
122
        }
123
124
        if (isset($config['caches']['mongo'])) {
125
            $this->checkMongo();
126
127
            $database = $config['caches']['mongo']['database'];
128
            $servers = [];
129
            foreach ($config['caches']['mongo']['servers'] as $server) {
130
                if ($server['user']) {
131
                    $servers[] = sprintf('%s:%s@%s:%s/%s', $server['user'], $server['password'], $server['host'], $server['port'], $database);
132
                } else {
133
                    $servers[] = sprintf('%s:%s', $server['host'], $server['port']);
134
                }
135
            }
136
137
            $container
138
                ->getDefinition('sonata.cache.mongo')
139
                ->replaceArgument(0, $servers)
140
                ->replaceArgument(1, $database)
141
                ->replaceArgument(2, $config['caches']['mongo']['collection'])
142
            ;
143
        } else {
144
            $container->removeDefinition('sonata.cache.mongo');
145
        }
146
147
        if (isset($config['caches']['memcached'])) {
148
            $this->checkMemcached();
149
150
            $container
151
                ->getDefinition('sonata.cache.memcached')
152
                ->replaceArgument(0, $config['caches']['memcached']['prefix'])
153
                ->replaceArgument(1, $config['caches']['memcached']['servers'])
154
            ;
155
        } else {
156
            $container->removeDefinition('sonata.cache.memcached');
157
        }
158
159
        if (isset($config['caches']['predis'])) {
160
            $this->checkPRedis();
161
162
            $container
163
                ->getDefinition('sonata.cache.predis')
164
                ->replaceArgument(0, $config['caches']['predis']['servers'])
165
            ;
166
        } else {
167
            $container->removeDefinition('sonata.cache.predis');
168
        }
169
170
        if (isset($config['caches']['apc'])) {
171
            $this->checkApc();
172
173
            $container
174
                ->getDefinition('sonata.cache.apc')
175
                ->replaceArgument(1, $config['caches']['apc']['token'])
176
                ->replaceArgument(2, $config['caches']['apc']['prefix'])
177
                ->replaceArgument(3, $this->configureServers($config['caches']['apc']['servers']))
178
                ->replaceArgument(4, $config['caches']['apc']['timeout'])
179
            ;
180
        } else {
181
            $container->removeDefinition('sonata.cache.apc');
182
        }
183
184
        if (isset($config['caches']['symfony'])) {
185
            $container
186
                ->getDefinition('sonata.cache.symfony')
187
                ->replaceArgument(3, $config['caches']['symfony']['token'])
188
                ->replaceArgument(4, $config['caches']['symfony']['php_cache_enabled'])
189
                ->replaceArgument(5, $config['caches']['symfony']['types'])
190
                ->replaceArgument(6, $this->configureServers($config['caches']['symfony']['servers']))
191
                ->replaceArgument(7, $config['caches']['symfony']['timeout'])
192
            ;
193
        } else {
194
            $container->removeDefinition('sonata.cache.symfony');
195
        }
196
    }
197
198
    /**
199
     * @param ContainerBuilder $container
200
     * @param array            $config
201
     *
202
     * @throws \RuntimeException if the Mongo or Memcached library is not installed
203
     */
204
    public function configureCounter(ContainerBuilder $container, $config)
205
    {
206
        if ($config['default_counter']) {
207
            $container->setAlias('sonata.counter', $config['default_counter']);
208
        }
209
210
        if (isset($config['counters']['mongo'])) {
211
            $this->checkMongo();
212
213
            $servers = [];
214
            foreach ($config['counters']['mongo']['servers'] as $server) {
215
                if ($server['user']) {
216
                    $servers[] = sprintf('%s:%s@%s:%s', $server['user'], $server['password'], $server['host'], $server['port']);
217
                } else {
218
                    $servers[] = sprintf('%s:%s', $server['host'], $server['port']);
219
                }
220
            }
221
222
            $container
223
                ->getDefinition('sonata.cache.counter.mongo')
224
                ->replaceArgument(0, $servers)
225
                ->replaceArgument(1, $config['counters']['mongo']['database'])
226
                ->replaceArgument(2, $config['counters']['mongo']['collection'])
227
            ;
228
        } else {
229
            $container->removeDefinition('sonata.cache.counter.mongo');
230
        }
231
232
        if (isset($config['counters']['memcached'])) {
233
            $this->checkMemcached();
234
235
            $container
236
                ->getDefinition('sonata.cache.counter.memcached')
237
                ->replaceArgument(0, $config['counters']['memcached']['prefix'])
238
                ->replaceArgument(1, $config['counters']['memcached']['servers'])
239
            ;
240
        } else {
241
            $container->removeDefinition('sonata.cache.counter.memcached');
242
        }
243
244
        if (isset($config['counters']['predis'])) {
245
            $this->checkPRedis();
246
247
            $container
248
                ->getDefinition('sonata.cache.counter.predis')
249
                ->replaceArgument(0, $config['counters']['predis']['servers'])
250
            ;
251
        } else {
252
            $container->removeDefinition('sonata.cache.counter.predis');
253
        }
254
255
        if (isset($config['counters']['apc'])) {
256
            $this->checkApc();
257
258
            $container
259
                ->getDefinition('sonata.cache.counter.apc')
260
                ->replaceArgument(0, $config['counters']['apc']['prefix'])
261
            ;
262
        } else {
263
            $container->removeDefinition('sonata.cache.counter.apc');
264
        }
265
    }
266
267
    /**
268
     * Returns servers list with hash for basic auth computed if provided.
269
     *
270
     * @param array $servers
271
     *
272
     * @return array
273
     */
274
    public function configureServers(array $servers)
275
    {
276
        return array_map(
277
            function ($item) {
278
                if ($item['basic']) {
279
                    $item['basic'] = base64_encode($item['basic']);
280
                }
281
282
                return $item;
283
            },
284
            $servers
285
        );
286
    }
287
288
    protected function checkMemcached()
289
    {
290
        if (!class_exists('\Memcached', true)) {
291
            throw new \RuntimeException(<<<'HELP'
292
The `sonata.cache.memcached` service is configured, however the Memcached class is not available.
293
294
To resolve this issue, please install the related library : http://php.net/manual/en/book.memcached.php
295
or remove the memcached cache settings from the configuration file.
296
HELP
297
            );
298
        }
299
    }
300
301
    protected function checkApc()
302
    {
303
        if (!function_exists('apc_fetch')) {
304
            throw new \RuntimeException(<<<'HELP'
305
The `sonata.cache.apc` service is configured, however the apc_* functions are not available.
306
307
To resolve this issue, please install the related library : http://php.net/manual/en/book.apc.php
308
or remove the APC cache settings from the configuration file.
309
HELP
310
            );
311
        }
312
    }
313
314
    protected function checkMongo()
315
    {
316
        if (!class_exists('\Mongo', true)) {
317
            throw new \RuntimeException(<<<'HELP'
318
The `sonata.cache.mongo` service is configured, however the Mongo class is not available.
319
320
To resolve this issue, please install the related library : http://php.net/manual/en/book.mongo.php
321
or remove the mongo cache settings from the configuration file.
322
HELP
323
            );
324
        }
325
    }
326
327
    protected function checkPRedis()
328
    {
329
        if (!class_exists('\Predis\Client', true)) {
330
            throw new \RuntimeException(<<<HELP
331
The `sonata.cache.predis` service is configured, however the Predis\Client class is not available.
332
333
Please add the lib in your composer.json file: "predis/predis": "~0.8".
334
HELP
335
            );
336
        }
337
    }
338
}
339