Completed
Push — 2.0 ( 6cd6ae...d9081a )
by Rob
11s
created

Configuration   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 173
Duplicated Lines 3.47 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 5
dl 6
loc 173
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
D getConfigTreeBuilder() 6 120 10
A addResolversSections() 0 4 1
A addLoadersSections() 0 4 1
A addConfigurationSections() 0 6 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/*
4
 * This file is part of the `liip/LiipImagineBundle` project.
5
 *
6
 * (c) https://github.com/liip/LiipImagineBundle/graphs/contributors
7
 *
8
 * For the full copyright and license information, please view the LICENSE.md
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Liip\ImagineBundle\DependencyInjection;
13
14
use Liip\ImagineBundle\DependencyInjection\Factory\Loader\LoaderFactoryInterface;
15
use Liip\ImagineBundle\DependencyInjection\Factory\Resolver\ResolverFactoryInterface;
16
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
17
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
18
use Symfony\Component\Config\Definition\ConfigurationInterface;
19
20
class Configuration implements ConfigurationInterface
21
{
22
    /**
23
     * @var ResolverFactoryInterface[]
24
     */
25
    protected $resolversFactories;
26
27
    /**
28
     * @var LoaderFactoryInterface[]
29
     */
30
    protected $loadersFactories;
31
32
    /**
33
     * @param ResolverFactoryInterface[] $resolversFactories
34
     * @param LoaderFactoryInterface[]   $loadersFactories
35
     */
36
    public function __construct(array $resolversFactories, array $loadersFactories)
37
    {
38
        $this->resolversFactories = $resolversFactories;
39
        $this->loadersFactories = $loadersFactories;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function getConfigTreeBuilder()
46
    {
47
        $treeBuilder = new TreeBuilder();
48
        $rootNode = $treeBuilder->root('liip_imagine', 'array');
49
50
        $resolversPrototypeNode = $rootNode
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Config...\Builder\NodeDefinition as the method performNoDeepMerging() does only exist in the following sub-classes of Symfony\Component\Config...\Builder\NodeDefinition: Symfony\Component\Config...der\ArrayNodeDefinition. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
51
            ->children()
52
                ->arrayNode('resolvers')
53
                    ->useAttributeAsKey('name')
54
                    ->prototype('array')
55
                        ->performNoDeepMerging()
56
        ;
57
        $this->addResolversSections($resolversPrototypeNode);
58
59
        $loadersPrototypeNode = $rootNode
60
            ->children()
61
                ->arrayNode('loaders')
62
                    ->useAttributeAsKey('name')
63
                    ->prototype('array')
64
        ;
65
        $this->addLoadersSections($loadersPrototypeNode);
0 ignored issues
show
Compatibility introduced by
$loadersPrototypeNode of type object<Symfony\Component...Builder\NodeDefinition> is not a sub-type of object<Symfony\Component...er\ArrayNodeDefinition>. It seems like you assume a child class of the class Symfony\Component\Config...\Builder\NodeDefinition to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
66
67
        $rootNode
68
            ->beforeNormalization()
69
                ->ifTrue(function ($v) {
70
                    return
71
                        empty($v['loaders']) ||
72
                        empty($v['loaders']['default']) ||
73
                        empty($v['resolvers']) ||
74
                        empty($v['resolvers']['default'])
75
                    ;
76
                })
77
                ->then(function ($v) {
78
                    if (empty($v['loaders'])) {
79
                        $v['loaders'] = [];
80
                    }
81
82
                    if (false == is_array($v['loaders'])) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
83
                        throw new \LogicException('Loaders has to be array');
84
                    }
85
86 View Code Duplication
                    if (false == array_key_exists('default', $v['loaders'])) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
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...
87
                        $v['loaders']['default'] = ['filesystem' => null];
88
                    }
89
90
                    if (empty($v['resolvers'])) {
91
                        $v['resolvers'] = [];
92
                    }
93
94
                    if (false == is_array($v['resolvers'])) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
95
                        throw new \LogicException('Resolvers has to be array');
96
                    }
97
98 View Code Duplication
                    if (false == array_key_exists('default', $v['resolvers'])) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
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...
99
                        $v['resolvers']['default'] = ['web_path' => null];
100
                    }
101
102
                    return $v;
103
                })
104
            ->end()
105
        ;
106
107
        $rootNode
108
            ->fixXmlConfig('filter_set', 'filter_sets')
109
            ->children()
110
                ->scalarNode('driver')->defaultValue('gd')
111
                    ->validate()
112
                        ->ifTrue(function ($v) {
113
                            return !in_array($v, ['gd', 'imagick', 'gmagick']);
114
                        })
115
                        ->thenInvalid('Invalid imagine driver specified: %s')
116
                    ->end()
117
                ->end()
118
                ->scalarNode('cache')->defaultValue('default')->end()
119
                ->scalarNode('cache_base_path')->defaultValue('')->end()
120
                ->scalarNode('data_loader')->defaultValue('default')->end()
121
                ->scalarNode('default_image')->defaultNull()->end()
122
                ->arrayNode('controller')
123
                    ->addDefaultsIfNotSet()
124
                    ->children()
125
                        ->scalarNode('filter_action')->defaultValue('liip_imagine.controller:filterAction')->end()
126
                        ->scalarNode('filter_runtime_action')->defaultValue('liip_imagine.controller:filterRuntimeAction')->end()
127
                    ->end()
128
                ->end()
129
                ->arrayNode('filter_sets')
130
                    ->useAttributeAsKey('name')
131
                    ->prototype('array')
132
                        ->fixXmlConfig('filter', 'filters')
133
                        ->children()
134
                            ->scalarNode('quality')->defaultValue(100)->end()
135
                            ->scalarNode('jpeg_quality')->defaultNull()->end()
136
                            ->scalarNode('png_compression_level')->defaultNull()->end()
137
                            ->scalarNode('png_compression_filter')->defaultNull()->end()
138
                            ->scalarNode('format')->defaultNull()->end()
139
                            ->booleanNode('animated')->defaultFalse()->end()
140
                            ->scalarNode('cache')->defaultNull()->end()
141
                            ->scalarNode('data_loader')->defaultNull()->end()
142
                            ->scalarNode('default_image')->defaultNull()->end()
143
                            ->arrayNode('filters')
144
                                ->useAttributeAsKey('name')
145
                                ->prototype('array')
146
                                    ->useAttributeAsKey('name')
147
                                    ->prototype('variable')->end()
148
                                ->end()
149
                            ->end()
150
                            ->arrayNode('post_processors')
151
                                ->defaultValue([])
152
                                ->useAttributeAsKey('name')
153
                                ->prototype('array')
154
                                    ->useAttributeAsKey('name')
155
                                    ->prototype('variable')->end()
156
                                ->end()
157
                        ->end()
158
                    ->end()
159
                ->end()
160
            ->end()
161
        ->end();
162
163
        return $treeBuilder;
164
    }
165
166
    /**
167
     * @param ArrayNodeDefinition $resolversPrototypeNode
168
     */
169
    private function addResolversSections(ArrayNodeDefinition $resolversPrototypeNode)
170
    {
171
        $this->addConfigurationSections($this->resolversFactories, $resolversPrototypeNode);
172
    }
173
174
    /**
175
     * @param ArrayNodeDefinition $resolversPrototypeNode
176
     */
177
    private function addLoadersSections(ArrayNodeDefinition $resolversPrototypeNode)
178
    {
179
        $this->addConfigurationSections($this->loadersFactories, $resolversPrototypeNode);
180
    }
181
182
    /**
183
     * @param array               $factories
184
     * @param ArrayNodeDefinition $definition
185
     */
186
    private function addConfigurationSections(array $factories, ArrayNodeDefinition $definition)
187
    {
188
        foreach ($factories as $f) {
189
            $f->addConfiguration($definition->children()->arrayNode($f->getName()));
190
        }
191
    }
192
}
193