Completed
Push — master ( 83a9fe...bdaaf9 )
by Tobias
07:57
created

TranslationExtension::load()   F

Complexity

Conditions 15
Paths 800

Size

Total Lines 74
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 41.116

Importance

Changes 0
Metric Value
dl 0
loc 74
rs 2.7027
c 0
b 0
f 0
ccs 21
cts 41
cp 0.5122
cc 15
eloc 43
nc 800
nop 2
crap 41.116

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 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 1
     */
34
    public function load(array $configs, ContainerBuilder $container)
35 1
    {
36 1
        $configuration = new Configuration($container);
37 1
        $config = $this->processConfiguration($configuration, $configs);
38
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
39 1
40 1
        $loader->load('services.yml');
41
        $loader->load('extractors.yml');
42
43 1
        // Add major version to extractor
44 1
        $container->getDefinition('php_translation.extractor.php.visitor.FormTypeChoices')
45
            ->addMethodCall('setSymfonyMajorVersion', [Kernel::MAJOR_VERSION]);
46 1
47 1
        $container->setParameter('php_translation.locales', $config['locales']);
48
        $container->setParameter('php_translation.default_locale', isset($config['default_locale']) ? $config['default_locale'] : $container->getParameter('kernel.default_locale'));
49 1
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
        }
53 1
54
        if ($config['symfony_profiler']['enabled']) {
55
            $loader->load('symfony_profiler.yml');
56
            $this->enableSymfonyProfiler($container, $config);
57
        }
58 1
59
        if ($config['edit_in_place']['enabled']) {
60
            $loader->load('edit_in_place.yml');
61
            $this->enableEditInPlace($container, $config);
62
        }
63 1
64 1
        if ($config['fallback_translation']['enabled']) {
65
            $loader->load('auto_translation.yml');
66
            $this->enableFallbackAutoTranslator($container, $config);
67
        }
68
69
        $first = null;
70
        foreach ($config['configs'] as $name => &$c) {
71
            if ($first === null || $name === 'default') {
72
                $first = $name;
73
            }
74
            if (empty($c['project_root'])) {
75
                $c['project_root'] = dirname($container->getParameter('kernel.root_dir'));
76
            }
77
78
            $storageDefinition = $container->register('php_translation.storage.'.$name, StorageService::class);
79
80
            // Register a file storage
81
            $def = new DefinitionDecorator('php_translation.single_storage.file.abstract');
82
            $def->replaceArgument(2, $c['output_dir'])
83
                ->addTag('php_translation.storage', ['type' => 'local', 'name' => $name]);
84
            $container->setDefinition('php_translation.single_storage.file.'.$name, $def);
85
86
            // Add storages
87
            if (!empty($c['remote_storage'])) {
88
                foreach ($c['remote_storage'] as $serviceId) {
89
                    $storageDefinition->addMethodCall('addRemoteStorage', [new Reference($serviceId)]);
90
                }
91 1
            }
92
            if (!empty($c['local_storage'])) {
93 1
                foreach ($c['local_storage'] as $serviceId) {
94
                    $storageDefinition->addMethodCall('addLocalStorage', [new Reference($serviceId)]);
95
                }
96
            }
97
        }
98
99 1
        if ($first !== null) {
100 1
            // Create some aliases for the default storage
101 1
            $container->setAlias('php_translation.storage', 'php_translation.storage.'.$first);
102
            $container->setAlias('php_translation.storage.default', 'php_translation.storage.'.$first);
103
        }
104
105
        $container->getDefinition('php_translation.configuration_manager')
106
            ->replaceArgument(0, $config['configs']);
107
    }
108
109
    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...
110
    {
111
    }
112
113
    private function enableEditInPlace(ContainerBuilder $container, $config)
114
    {
115
        $name = $config['edit_in_place']['config_name'];
116
117
        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...
118
            throw new InvalidArgumentException(sprintf('There is no config named "%s".', $name));
119
        }
120
121
        $activatorRef = new Reference($config['edit_in_place']['activator']);
122
123
        $def = $container->getDefinition('php_translation.edit_in_place.response_listener');
124
        $def->replaceArgument(0, $activatorRef);
125
        $def->replaceArgument(3, $name);
126
127
        $def = $container->getDefinition('php_translator.edit_in_place.xtrans_html_translator');
128
        $def->replaceArgument(1, $activatorRef);
129
    }
130
131
    private function enableSymfonyProfiler(ContainerBuilder $container, $config)
132
    {
133
        $container->setParameter('php_translation.toolbar.allow_edit', $config['symfony_profiler']['allow_edit']);
134
    }
135
136
    private function enableFallbackAutoTranslator(ContainerBuilder $container, $config)
137
    {
138
        $externalTranslatorId = 'php_translation.translator_service.'.$config['fallback_translation']['service'];
139
        $externalTranslatorDef = $container->getDefinition($externalTranslatorId);
140
        $externalTranslatorDef->addTag('php_translation.external_translator');
141
        $externalTranslatorDef->addArgument(new Reference($config['http_client']));
142
        $externalTranslatorDef->addArgument(new Reference($config['message_factory']));
143
144
        $container->setParameter('php_translation.translator_service.api_key', $config['fallback_translation']['api_key']);
145
    }
146
147
    public function getAlias()
148
    {
149
        return 'translation';
150
    }
151
}
152