Completed
Push — master ( ed6da2...694cab )
by Aaron
02:49
created

CacheExtension::load()   B

Complexity

Conditions 6
Paths 24

Size

Total Lines 36
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 6.0052

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 18
cts 19
cp 0.9474
rs 8.439
c 0
b 0
f 0
cc 6
eloc 18
nc 24
nop 2
crap 6.0052
1
<?php
2
3
/*
4
 * This file is part of php-cache\cache-bundle package.
5
 *
6
 * (c) 2015 Aaron Scherer <[email protected]>, Tobias Nyholm <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Cache\CacheBundle\DependencyInjection;
13
14
use Cache\Bridge\Doctrine\DoctrineCacheBridge;
15
use Cache\CacheBundle\Bridge\SymfonyValidatorBridge;
16
use Cache\CacheBundle\Command\CacheFlushCommand;
17
use Cache\CacheBundle\Factory\DoctrineBridgeFactory;
18
use Cache\CacheBundle\Factory\RouterFactory;
19
use Cache\CacheBundle\Factory\SessionHandlerFactory;
20
use Cache\CacheBundle\Factory\ValidationFactory;
21
use Cache\CacheBundle\Routing\CachingRouter;
22
use Cache\SessionHandler\Psr6SessionHandler;
23
use Symfony\Component\Config\FileLocator;
24
use Symfony\Component\DependencyInjection\ContainerBuilder;
25
use Symfony\Component\DependencyInjection\Definition;
26
use Symfony\Component\DependencyInjection\Loader;
27
use Symfony\Component\DependencyInjection\Reference;
28
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
29
30
/**
31
 * @author Aaron Scherer <[email protected]>
32
 * @author Tobias Nyholm <[email protected]>
33
 */
34
class CacheExtension extends Extension
35
{
36
    /**
37
     * Loads the configs for Cache and puts data into the container.
38
     *
39
     * @param array            $configs   Array of configs
40
     * @param ContainerBuilder $container Container Object
41
     */
42 2
    public function load(array $configs, ContainerBuilder $container)
43
    {
44 2
        $config = $this->processConfiguration(new Configuration(), $configs);
45
46 2
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
47
48
        // Make sure config values are in the parameters
49 2
        foreach (['router', 'session', 'doctrine', 'logging', 'annotation', 'serializer', 'validation'] as $section) {
50 2
            if ($config[$section]['enabled']) {
51 2
                $container->setParameter('cache.'.$section, $config[$section]);
52
            }
53
        }
54
55 2
        if ($config['doctrine']['enabled']) {
56
            $this->verifyDoctrineBridgeExists('doctrine');
57
        }
58
59 2
        $this->registerServices($container, $config);
60
61
        // Add toolbar and data collector if we are debugging
62 2
        if (!isset($config['data_collector']['enabled'])) {
63 2
            $config['data_collector']['enabled'] = $container->getParameter('kernel.debug');
64
        }
65
66 2
        if ($config['data_collector']['enabled']) {
67 1
            $loader->load('data-collector.yml');
68
        }
69
70
        // Get a list of the psr-6 services we are using.
71 2
        $serviceIds = [];
72 2
        $this->findServiceIds($config, $serviceIds);
73 2
        $container->setParameter('cache.provider_service_ids', $serviceIds);
74
75 2
        $container->register(CacheFlushCommand::class, CacheFlushCommand::class)
76 2
            ->addTag('console.command', ['command' => 'cache:flush']);
77 2
    }
78
79
    /**
80
     * Find service ids that we configured. These services should be tagged so we can use them in the debug toolbar.
81
     *
82
     * @param array $config
83
     * @param array $serviceIds
84
     */
85 2
    protected function findServiceIds(array $config, array &$serviceIds)
86
    {
87 2
        foreach ($config as $name => $value) {
88 2
            if (is_array($value)) {
89 2
                $this->findServiceIds($value, $serviceIds);
90 2
            } elseif ($name === 'service_id') {
91 2
                $serviceIds[] = $value;
92
            }
93
        }
94 2
    }
95
96
    /**
97
     * Make sure the DoctrineBridge is installed.
98
     *
99
     * @param string $name
100
     *
101
     * @throws \Exception
102
     */
103 1
    private function verifyDoctrineBridgeExists($name)
104
    {
105 1
        if (!class_exists('Cache\Bridge\Doctrine\DoctrineCacheBridge')) {
106
            throw new \Exception(
107
                sprintf(
108
                    'You need the DoctrineCacheBridge to be able to use "%s". Please run "composer require cache/psr-6-doctrine-bridge" to install the missing dependency.',
109
                    $name
110
                )
111
            );
112
        }
113 1
    }
114
115
    /**
116
     * @return string
117
     */
118 2
    public function getAlias()
119
    {
120 2
        return 'cache';
121
    }
122
123
    /**
124
     * Register services. All service ids will start witn "cache.service.".
125
     *
126
     * @param ContainerBuilder $container
127
     * @param                  $config
128
     *
129
     * @throws \Exception
130
     */
131 2
    private function registerServices(ContainerBuilder $container, $config)
132
    {
133 2 View Code Duplication
        if ($config['annotation']['enabled']) {
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...
134 1
            $this->verifyDoctrineBridgeExists('annotation');
135 1
            $container->register('cache.service.annotation', DoctrineCacheBridge::class)
136 1
                ->setFactory([DoctrineBridgeFactory::class, 'get'])
137 1
                ->addArgument(new Reference($config['annotation']['service_id']))
138 1
                ->addArgument($config['annotation'])
139 1
                ->addArgument(['annotation']);
140
        }
141
142 2 View Code Duplication
        if ($config['serializer']['enabled']) {
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...
143 1
            $this->verifyDoctrineBridgeExists('serializer');
144 1
            $container->register('cache.service.serializer', DoctrineCacheBridge::class)
145 1
                ->setFactory([DoctrineBridgeFactory::class, 'get'])
146 1
                ->addArgument(new Reference($config['serializer']['service_id']))
147 1
                ->addArgument($config['serializer'])
148 1
                ->addArgument(['serializer']);
149
        }
150
151 2 View Code Duplication
        if ($config['validation']['enabled']) {
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...
152 1
            $container->register('cache.service.validation', SymfonyValidatorBridge::class)
153 1
                ->setFactory([ValidationFactory::class, 'get'])
154 1
                ->addArgument(new Reference($config['validation']['service_id']))
155 1
                ->addArgument($config['validation']);
156
        }
157
158 2 View Code Duplication
        if ($config['session']['enabled']) {
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...
159 1
            $container->register('cache.service.session', Psr6SessionHandler::class)
160 1
                ->setFactory([SessionHandlerFactory::class, 'get'])
161 1
                ->addArgument(new Reference($config['session']['service_id']))
162 1
                ->addArgument($config['session']);
163
        }
164
165 2
        if ($config['router']['enabled']) {
166 2
            $container->register('cache.service.router', CachingRouter::class)
167 2
                ->setFactory([RouterFactory::class, 'get'])
168 2
                ->setDecoratedService('router', null, 10)
169 2
                ->addArgument(new Reference($config['router']['service_id']))
170 2
                ->addArgument(new Reference('cache.service.router.inner'))
171 2
                ->addArgument($config['router']);
172
        }
173 2
    }
174
}
175