Completed
Push — master ( 8de6a8...6dc1a9 )
by Simonas
02:00
created

Configuration::getConfigTreeBuilder()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 25
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 19
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[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 ONGR\ElasticsearchBundle\DependencyInjection;
13
14
use Psr\Log\LogLevel;
15
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
16
use Symfony\Component\Config\Definition\ConfigurationInterface;
17
18
/**
19
 * This is the class that validates and merges configuration from app/config files.
20
 */
21
class Configuration implements ConfigurationInterface
22
{
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function getConfigTreeBuilder()
27
    {
28
        $treeBuilder = new TreeBuilder();
29
        $rootNode = $treeBuilder->root('ongr_elasticsearch');
30
31
        $rootNode
32
            ->children()
33
            ->booleanNode('cache')
34
                ->info(
35
                    'Enables cache handler to store metadata and other data to the cache. '.
36
                    'By default it is enabled in prod environment and disabled in dev.'
37
                )
38
            ->end()
39
            ->booleanNode('profiler')
40
                ->info(
41
                    'Enables ElasticsearchBundle query profiler. Default value is kernel.debug parameter. '.
42
                    'If profiler is disabled the tracer service will be disabled as well.'
43
                )
44
            ->end()
45
            ->append($this->getAnalysisNode())
46
            ->append($this->getManagersNode())
47
            ->end();
48
49
        return $treeBuilder;
50
    }
51
52
    /**
53
     * Analysis configuration node.
54
     *
55
     * @return \Symfony\Component\Config\Definition\Builder\NodeDefinition
56
     */
57
    private function getAnalysisNode()
58
    {
59
        $builder = new TreeBuilder();
60
        $node = $builder->root('analysis');
61
62
        $node
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 addDefaultsIfNotSet() 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...
63
            ->info('Defines analyzers, tokenizers and filters')
64
            ->addDefaultsIfNotSet()
65
            ->children()
66
                ->arrayNode('tokenizer')
67
                    ->defaultValue([])
68
                    ->prototype('variable')->end()
69
                ->end()
70
                ->arrayNode('filter')
71
                    ->defaultValue([])
72
                    ->prototype('variable')->end()
73
                ->end()
74
                ->arrayNode('analyzer')
75
                    ->defaultValue([])
76
                    ->prototype('variable')->end()
77
                ->end()
78
                ->arrayNode('char_filter')
79
                    ->defaultValue([])
80
                    ->prototype('variable')->end()
81
                ->end()
82
            ->end();
83
84
        return $node;
85
    }
86
87
    /**
88
     * Managers configuration node.
89
     *
90
     * @return \Symfony\Component\Config\Definition\Builder\NodeDefinition
91
     */
92
    private function getManagersNode()
93
    {
94
        $builder = new TreeBuilder();
95
        $node = $builder->root('managers');
96
97
        $node
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 requiresAtLeastOneElement() 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...
98
            ->isRequired()
99
            ->requiresAtLeastOneElement()
100
            ->useAttributeAsKey('name')
101
            ->info('Maps managers to connections and bundles')
102
            ->prototype('array')
103
                ->children()
104
                    ->arrayNode('index')
105
                        ->children()
106
                            ->scalarNode('index_name')
107
                                ->isRequired()
108
                                ->info('Sets index name for connection.')
109
                            ->end()
110
                            ->arrayNode('hosts')
111
                                ->info('Defines hosts to connect to.')
112
                                ->defaultValue(['127.0.0.1:9200'])
113
                                ->prototype('scalar')
114
                                ->end()
115
                            ->end()
116
                            ->arrayNode('settings')
117
                                ->defaultValue([])
118
                                ->info('Sets index settings for connection.')
119
                                ->prototype('variable')->end()
120
                            ->end()
121
                            ->arrayNode('analysis')
122
                                ->addDefaultsIfNotSet()
123
                                ->info('Sets index analysis settings for connection.')
124
                                ->children()
125
                                    ->arrayNode('tokenizer')->prototype('scalar')->defaultValue([])->end()->end()
126
                                    ->arrayNode('filter')->prototype('scalar')->defaultValue([])->end()->end()
127
                                    ->arrayNode('analyzer')->prototype('scalar')->defaultValue([])->end()->end()
128
                                    ->arrayNode('char_filter')->prototype('scalar')->defaultValue([])->end()->end()
129
                                ->end()
130
                            ->end()
131
                        ->end()
132
                    ->end()
133
                    ->integerNode('bulk_size')
134
                        ->min(0)
135
                        ->defaultValue(100)
136
                        ->info(
137
                            'Maximum documents size in the bulk container. ' .
138
                            'When the limit is reached it will auto-commit.'
139
                        )
140
                    ->end()
141
                    ->enumNode('commit_mode')
142
                        ->values(['refresh', 'flush', 'none'])
143
                        ->defaultValue('refresh')
144
                        ->info(
145
                            'The default type of commit for bulk queries.'
146
                        )
147
                    ->end()
148
                    ->arrayNode('logger')
149
                        ->info('Enables elasticsearch queries logging')
150
                        ->addDefaultsIfNotSet()
151
                        ->beforeNormalization()
152
                            ->ifTrue(
153
                                function ($v) {
154
                                    return is_bool($v);
155
                                }
156
                            )
157
                            ->then(
158
                                function ($v) {
159
                                    return ['enabled' => $v];
160
                                }
161
                            )
162
                        ->end()
163
                        ->children()
164
                            ->booleanNode('enabled')
165
                                ->info('enables logging')
166
                                ->defaultFalse()
167
                            ->end()
168
                            ->scalarNode('level')
169
                                ->info('Sets PSR logging level.')
170
                                ->defaultValue(LogLevel::WARNING)
171
                                ->validate()
172
                                ->ifNotInArray((new \ReflectionClass('Psr\Log\LogLevel'))->getConstants())
173
                                    ->thenInvalid('Invalid PSR log level.')
174
                                ->end()
175
                            ->end()
176
                            ->scalarNode('log_file_name')
177
                                ->info('Log filename. By default it is a manager name.')
178
                                ->defaultValue(null)
179
                            ->end()
180
                        ->end()
181
                    ->end()
182
                    ->arrayNode('mappings')
183
                        ->info('Maps manager to the bundles. f.e. AppBundle')
184
                        ->prototype('scalar')->end()
185
                    ->end()
186
                    ->booleanNode('force_commit')
187
                        ->info('Forces commit to the elasticsearch on kernel terminate event.')
188
                        ->defaultTrue()
189
                    ->end()
190
                ->end()
191
            ->end();
192
193
        return $node;
194
    }
195
}
196