Completed
Push — master ( c29061...fba80d )
by Tobias
05:40
created

TranslationExtension::enableWebUi()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 2
crap 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\ContainerBuilder;
15
use Symfony\Component\Config\FileLocator;
16
use Symfony\Component\DependencyInjection\DefinitionDecorator;
17
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
18
use Symfony\Component\DependencyInjection\Reference;
19
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
20
use Symfony\Component\DependencyInjection\Loader;
21
use Symfony\Component\HttpKernel\Kernel;
22
use Translation\Bundle\Service\StorageService;
23
24
/**
25
 * This is the class that loads and manages your bundle configuration.
26
 *
27
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
28
 */
29
class TranslationExtension extends Extension
30
{
31
    /**
32
     * {@inheritdoc}
33
     */
34 1
    public function load(array $configs, ContainerBuilder $container)
35
    {
36 1
        $configuration = new Configuration($container);
37 1
        $config = $this->processConfiguration($configuration, $configs);
38 1
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
39
40 1
        $loader->load('services.yml');
41 1
        $loader->load('extractors.yml');
42
43
        // Add major version to extractor
44 1
        $container->getDefinition('php_translation.extractor.php.visitor.FormTypeChoices')
45 1
            ->addMethodCall('setSymfonyMajorVersion', [Kernel::MAJOR_VERSION]);
46
47 1
        $container->setParameter('php_translation.locales', $config['locales']);
48 1
        $container->setParameter('php_translation.default_locale', isset($config['default_locale']) ? $config['default_locale'] : $container->getParameter('kernel.default_locale'));
49
50 1
        if ($config['webui']['enabled']) {
51 1
            $this->enableWebUi($container, $config);
0 ignored issues
show
Unused Code introduced by
The call to the method Translation\Bundle\Depen...xtension::enableWebUi() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
52 1
        }
53
54 1
        if ($config['symfony_profiler']['enabled']) {
55
            $loader->load('symfony_profiler.yml');
56
            $this->enableSymfonyProfiler($container, $config);
57
        }
58
59 1
        if ($config['edit_in_place']['enabled']) {
60 1
            $loader->load('edit_in_place.yml');
61 1
            $this->enableEditInPlace($container, $config);
62 1
        }
63
64 1
        if ($config['auto_add_missing_translations']['enabled']) {
65
            $loader->load('auto_add.yml');
66
            $container->getDefinition('php_translator.auto_adder')
67
                ->replaceArgument(0, new Reference('php_translation.storage.'.$config['auto_add_missing_translations']['config_name']));
68
        }
69
70 1
        if ($config['fallback_translation']['enabled']) {
71
            $loader->load('auto_translation.yml');
72
            $this->enableFallbackAutoTranslator($container, $config);
73
        }
74
75 1
        $first = null;
76 1
        foreach ($config['configs'] as $name => &$c) {
77
            if ($first === null || $name === 'default') {
78
                $first = $name;
79
            }
80
            if (empty($c['project_root'])) {
81
                $c['project_root'] = dirname($container->getParameter('kernel.root_dir'));
82
            }
83
84
            $storageDefinition = $container->register('php_translation.storage.'.$name, StorageService::class);
85
86
            // Register a file storage
87
            $def = new DefinitionDecorator('php_translation.single_storage.file.abstract');
88
            $def->replaceArgument(2, $c['output_dir'])
89
                ->addTag('php_translation.storage', ['type' => 'local', 'name' => $name]);
90
            $container->setDefinition('php_translation.single_storage.file.'.$name, $def);
91
92
            // Add storages
93
            if (!empty($c['remote_storage'])) {
94
                foreach ($c['remote_storage'] as $serviceId) {
95
                    $storageDefinition->addMethodCall('addRemoteStorage', [new Reference($serviceId)]);
96
                }
97
            }
98
            if (!empty($c['local_storage'])) {
99
                foreach ($c['local_storage'] as $serviceId) {
100
                    $storageDefinition->addMethodCall('addLocalStorage', [new Reference($serviceId)]);
101
                }
102
            }
103 1
        }
104
105 1
        if ($first !== null) {
106
            // Create some aliases for the default storage
107
            $container->setAlias('php_translation.storage', 'php_translation.storage.'.$first);
108
            $container->setAlias('php_translation.storage.default', 'php_translation.storage.'.$first);
109
        }
110
111 1
        $container->getDefinition('php_translation.configuration_manager')
112 1
            ->replaceArgument(0, $config['configs']);
113 1
    }
114
115
    private function enableWebUi(ContainerBuilder $container, $config)
0 ignored issues
show
Unused Code introduced by
The parameter $container is not used and could be removed.

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

Loading history...
Unused Code introduced by
The parameter $config is not used and could be removed.

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

Loading history...
116
    {
117
    }
118
119
    private function enableEditInPlace(ContainerBuilder $container, $config)
120
    {
121
        $name = $config['edit_in_place']['config_name'];
122
123
        if ($name !== 'default' and !isset($config['configs'][$name])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
124
            throw new InvalidArgumentException(sprintf('There is no config named "%s".', $name));
125
        }
126
127
        $activatorRef = new Reference($config['edit_in_place']['activator']);
128
129
        $def = $container->getDefinition('php_translation.edit_in_place.response_listener');
130
        $def->replaceArgument(0, $activatorRef);
131
        $def->replaceArgument(3, $name);
132
133
        $def = $container->getDefinition('php_translator.edit_in_place.xtrans_html_translator');
134
        $def->replaceArgument(1, $activatorRef);
135
    }
136
137
    private function enableSymfonyProfiler(ContainerBuilder $container, $config)
138
    {
139
        $container->setParameter('php_translation.toolbar.allow_edit', $config['symfony_profiler']['allow_edit']);
140
    }
141
142
    private function enableFallbackAutoTranslator(ContainerBuilder $container, $config)
143
    {
144
        $externalTranslatorId = 'php_translation.translator_service.'.$config['fallback_translation']['service'];
145
        $externalTranslatorDef = $container->getDefinition($externalTranslatorId);
146
        $externalTranslatorDef->addTag('php_translation.external_translator');
147
        $externalTranslatorDef->addArgument(new Reference($config['http_client']));
148
        $externalTranslatorDef->addArgument(new Reference($config['message_factory']));
149
150
        $container->setParameter('php_translation.translator_service.api_key', $config['fallback_translation']['api_key']);
151
    }
152
153
    public function getAlias()
154
    {
155
        return 'translation';
156
    }
157
}
158