Completed
Push — master ( 785877...e6b000 )
by Tobias
17:05
created

TranslationExtension   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 218
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 94.12%

Importance

Changes 0
Metric Value
wmc 29
lcom 1
cbo 10
dl 0
loc 218
ccs 112
cts 119
cp 0.9412
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
C load() 0 48 8
C handleConfigNode() 0 56 10
A enableWebUi() 0 17 3
A enableEditInPlace() 0 18 3
A enableSymfonyProfiler() 0 4 1
A enableFallbackAutoTranslator() 0 10 1
A getAlias() 0 4 1
A createChildDefinition() 0 8 2
1
<?php
2
3
/*
4
 * This file is part of the PHP Translation package.
5
 *
6
 * (c) PHP Translation team <[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 Translation\Bundle\DependencyInjection;
13
14
use Symfony\Component\DependencyInjection\Alias;
15
use Symfony\Component\DependencyInjection\ContainerBuilder;
16
use Symfony\Component\Config\FileLocator;
17
use Symfony\Component\DependencyInjection\ChildDefinition;
18
use Symfony\Component\DependencyInjection\DefinitionDecorator;
19
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
20
use Symfony\Component\DependencyInjection\Reference;
21
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
22
use Symfony\Component\DependencyInjection\Loader;
23
use Symfony\Component\HttpKernel\Kernel;
24
use Translation\Bundle\Model\Configuration as ConfigurationModel;
25
26
/**
27
 * This is the class that loads and manages your bundle configuration.
28
 *
29
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
30
 */
31
class TranslationExtension extends Extension
32
{
33
    /**
34
     * {@inheritdoc}
35
     */
36 22
    public function load(array $configs, ContainerBuilder $container)
37
    {
38 22
        $configuration = new Configuration($container);
39 22
        $config = $this->processConfiguration($configuration, $configs);
40 22
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
41
42 22
        $loader->load('services.yml');
43 22
        $loader->load('extractors.yml');
44
45
        // Add major version to extractor
46 22
        $container->getDefinition('php_translation.extractor.php.visitor.FormTypeChoices')
47 22
            ->addMethodCall('setSymfonyMajorVersion', [Kernel::MAJOR_VERSION]);
48
49 22
        $container->setParameter('php_translation.locales', $config['locales']);
50 22
        $container->setParameter('php_translation.default_locale', isset($config['default_locale']) ? $config['default_locale'] : $container->getParameter('kernel.default_locale'));
51 22
        $this->handleConfigNode($container, $config);
52
53 22
        if ($config['webui']['enabled']) {
54 15
            $this->enableWebUi($container, $config);
55 15
        } else {
56 7
            $container->setParameter('php_translation.webui.enabled', false);
57
        }
58
59 22
        if ($config['symfony_profiler']['enabled']) {
60 22
            $loader->load('symfony_profiler.yml');
61 22
            $this->enableSymfonyProfiler($container, $config);
62 22
        }
63
64 22
        if ($config['edit_in_place']['enabled']) {
65 15
            $loader->load('edit_in_place.yml');
66 15
            $this->enableEditInPlace($container, $config);
67 15
        }
68
69 22
        if ($config['auto_add_missing_translations']['enabled']) {
70 1
            $loader->load('auto_add.yml');
71 1
            $container->getDefinition('php_translator.auto_adder')
72 1
                ->replaceArgument(0, new Reference('php_translation.storage.'.$config['auto_add_missing_translations']['config_name']));
73 1
        }
74
75 22
        if ($config['fallback_translation']['enabled']) {
76 1
            $loader->load('auto_translation.yml');
77 1
            $this->enableFallbackAutoTranslator($container, $config);
78 1
        }
79
80 22
        if ('test' === getenv('ENV')) {
81 22
            $loader->load('services_test.yml');
82 22
        }
83 22
    }
84
85
    /**
86
     * Handle the config node to prepare the config manager.
87
     *
88
     * @param ContainerBuilder $container
89
     * @param array            $config
90
     */
91 22
    private function handleConfigNode(ContainerBuilder $container, array $config)
92
    {
93 22
        $configurationManager = $container->getDefinition('php_translation.configuration_manager');
94
        // $first will be the "default" configuration.
95 22
        $first = null;
96 22
        foreach ($config['configs'] as $name => &$c) {
97 22
            if (null === $first || 'default' === $name) {
98 22
                $first = $name;
99 22
            }
100 22
            if (empty($c['project_root'])) {
101
                // Add a project root of none is set.
102 12
                $c['project_root'] = dirname($container->getParameter('kernel.root_dir'));
103 12
            }
104 22
            $c['name'] = $name;
105 22
            $c['locales'] = $config['locales'];
106 22
            $configurationServiceId = 'php_translation.configuration.'.$name;
107 22
            $configDef = $container->register($configurationServiceId, ConfigurationModel::class);
108 22
            $configDef->setPublic(false)->addArgument($c);
109 22
            $configurationManager->addMethodCall('addConfiguration', [$name, new Reference($configurationServiceId)]);
110
111
            /*
112
             * Configure storage chain service
113
             */
114 22
            $storageDefinition = $this->createChildDefinition('php_translation.storage.abstract');
115 22
            $storageDefinition->replaceArgument(2, new Reference($configurationServiceId));
116 22
            $storageDefinition->setPublic(true);
117 22
            $container->setDefinition('php_translation.storage.'.$name, $storageDefinition);
118
119
            // Add storages
120 22
            foreach ($c['remote_storage'] as $serviceId) {
121
                $storageDefinition->addMethodCall('addRemoteStorage', [new Reference($serviceId)]);
122 22
            }
123
124 22
            foreach ($c['local_storage'] as $serviceId) {
125 22
                if ('php_translation.local_file_storage.abstract' !== $serviceId) {
126
                    $storageDefinition->addMethodCall('addLocalStorage', [new Reference($serviceId)]);
127
128
                    continue;
129
                }
130
131 22
                $def = $this->createChildDefinition($serviceId);
132 22
                $def->replaceArgument(2, [$c['output_dir']])
133 22
                    ->replaceArgument(3, [$c['local_file_storage_options']])
134 22
                    ->addTag('php_translation.storage', ['type' => 'local', 'name' => $name]);
135 22
                $container->setDefinition('php_translation.single_storage.file.'.$name, $def);
136 22
            }
137 22
        }
138
139 22
        if (null !== $first) {
140
            // Create some aliases for the default storage
141 22
            $container->setAlias('php_translation.storage', new Alias('php_translation.storage.'.$first, true));
142 22
            if ('default' !== $first) {
143 10
                $container->setAlias('php_translation.storage.default', 'php_translation.storage.'.$first);
144 10
            }
145 22
        }
146 22
    }
147
148
    /**
149
     * Handle config for WebUI.
150
     *
151
     * @param ContainerBuilder $container
152
     * @param array            $config
153
     */
154 15
    private function enableWebUi(ContainerBuilder $container, array $config)
155
    {
156 15
        $container->setParameter('php_translation.webui.enabled', true);
157 15
        $container->setParameter('php_translation.webui.allow_create', $config['webui']['allow_create']);
158 15
        $container->setParameter('php_translation.webui.allow_delete', $config['webui']['allow_delete']);
159
160 15
        $path = $config['webui']['file_base_path'];
161 15
        if (null === $path) {
162 15
            if ($container->hasParameter('kernel.project_dir')) {
163
                $path = $container->getParameter('kernel.project_dir');
164
            } else {
165 15
                $path = $container->getParameter('kernel.root_dir').'/..';
166
            }
167 15
        }
168
169 15
        $container->setParameter('php_translation.webui.file_base_path', rtrim($path, '/').'/');
170 15
    }
171
172
    /**
173
     * Handle config for EditInPlace.
174
     *
175
     * @param ContainerBuilder $container
176
     * @param array            $config
177
     */
178 15
    private function enableEditInPlace(ContainerBuilder $container, array $config)
179
    {
180 15
        $name = $config['edit_in_place']['config_name'];
181
182 15
        if ('default' !== $name && !isset($config['configs'][$name])) {
183
            throw new InvalidArgumentException(sprintf('There is no config named "%s".', $name));
184
        }
185
186 15
        $activatorRef = new Reference($config['edit_in_place']['activator']);
187
188 15
        $def = $container->getDefinition('php_translation.edit_in_place.response_listener');
189 15
        $def->replaceArgument(0, $activatorRef);
190 15
        $def->replaceArgument(3, $name);
191 15
        $def->replaceArgument(4, $config['edit_in_place']['show_untranslatable']);
192
193 15
        $def = $container->getDefinition('php_translator.edit_in_place.xtrans_html_translator');
194 15
        $def->replaceArgument(1, $activatorRef);
195 15
    }
196
197
    /**
198
     * Handle config for Symfony Profiler.
199
     *
200
     * @param ContainerBuilder $container
201
     * @param array            $config
202
     */
203 22
    private function enableSymfonyProfiler(ContainerBuilder $container, array $config)
204
    {
205 22
        $container->setParameter('php_translation.toolbar.allow_edit', $config['symfony_profiler']['allow_edit']);
206 22
    }
207
208
    /**
209
     * Handle config for fallback auto translate.
210
     *
211
     * @param ContainerBuilder $container
212
     * @param array            $config
213
     */
214 1
    private function enableFallbackAutoTranslator(ContainerBuilder $container, array $config)
215
    {
216 1
        $externalTranslatorId = 'php_translation.translator_service.'.$config['fallback_translation']['service'];
217 1
        $externalTranslatorDef = $container->getDefinition($externalTranslatorId);
218 1
        $externalTranslatorDef->addTag('php_translation.external_translator');
219 1
        $externalTranslatorDef->addArgument(new Reference($config['http_client']));
220 1
        $externalTranslatorDef->addArgument(new Reference($config['message_factory']));
221
222 1
        $container->setParameter('php_translation.translator_service.api_key', $config['fallback_translation']['api_key']);
223 1
    }
224
225
    /**
226
     * {@inheritdoc}
227
     */
228 22
    public function getAlias()
229
    {
230 22
        return 'translation';
231
    }
232
233
    /**
234
     * To avoid BC break for Symfony 3.3+.
235
     *
236
     * @param $parent
237
     *
238
     * @return ChildDefinition|DefinitionDecorator
239
     */
240 22
    private function createChildDefinition($parent)
241
    {
242 22
        if (class_exists('Symfony\Component\DependencyInjection\ChildDefinition')) {
243
            return new ChildDefinition($parent);
244
        }
245
246 22
        return new DefinitionDecorator($parent);
247
    }
248
}
249