Completed
Push — master ( 09a07f...8de6a8 )
by Simonas
01:54
created

Configuration::getConnectionsNode()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 40
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 40
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 36
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
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
18
19
/**
20
 * This is the class that validates and merges configuration from app/config files.
21
 */
22
class Configuration implements ConfigurationInterface
23
{
24
    /**
25
     * {@inheritdoc}
26
     */
27
    public function getConfigTreeBuilder()
28
    {
29
        $treeBuilder = new TreeBuilder();
30
        $rootNode = $treeBuilder->root('ongr_elasticsearch');
31
32
        $rootNode
33
            ->children()
34
            ->booleanNode('cache')
35
                ->info(
36
                    'Enables cache handler to store metadata and other data to the cache. '.
37
                    'By default it is enabled in prod environment and disabled in dev.'
38
                )
39
            ->end()
40
            ->append($this->getAnalysisNode())
41
            ->append($this->getConnectionsNode())
42
            ->append($this->getManagersNode())
43
            ->end();
44
45
        return $treeBuilder;
46
    }
47
48
    /**
49
     * Analysis configuration node.
50
     *
51
     * @return \Symfony\Component\Config\Definition\Builder\NodeDefinition
52
     */
53
    private function getAnalysisNode()
54
    {
55
        $builder = new TreeBuilder();
56
        $node = $builder->root('analysis');
57
58
        $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...
59
            ->info('Defines analyzers, tokenizers and filters')
60
            ->addDefaultsIfNotSet()
61
            ->children()
62
                ->arrayNode('tokenizer')
63
                    ->defaultValue([])
64
                    ->prototype('variable')->end()
65
                ->end()
66
                ->arrayNode('filter')
67
                    ->defaultValue([])
68
                    ->prototype('variable')->end()
69
                ->end()
70
                ->arrayNode('analyzer')
71
                    ->defaultValue([])
72
                    ->prototype('variable')->end()
73
                ->end()
74
            ->end();
75
76
        return $node;
77
    }
78
79
    /**
80
     * Connections configuration node.
81
     *
82
     * @return \Symfony\Component\Config\Definition\Builder\NodeDefinition
83
     *
84
     * @throws InvalidConfigurationException
85
     */
86
    private function getConnectionsNode()
87
    {
88
        $builder = new TreeBuilder();
89
        $node = $builder->root('connections');
90
91
        $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...
92
            ->defaultValue([])
93
            ->requiresAtLeastOneElement()
94
            ->info('Defines connections to indexes and its settings.')
95
            ->prototype('array')
96
                ->children()
97
                    ->arrayNode('hosts')
98
                        ->info('Defines hosts to connect to.')
99
                        ->defaultValue(['127.0.0.1:9200'])
100
                        ->prototype('scalar')
101
                        ->end()
102
                    ->end()
103
                    ->scalarNode('index_name')
104
                        ->isRequired()
105
                        ->info('Sets index name for connection.')
106
                    ->end()
107
                    ->arrayNode('settings')
108
                        ->defaultValue([])
109
                        ->info('Sets index settings for connection.')
110
                        ->prototype('variable')->end()
111
                    ->end()
112
                    ->arrayNode('analysis')
113
                        ->addDefaultsIfNotSet()
114
                        ->info('Sets index analysis settings for connection.')
115
                        ->children()
116
                            ->arrayNode('tokenizer')->prototype('scalar')->defaultValue([])->end()->end()
117
                            ->arrayNode('filter')->prototype('scalar')->defaultValue([])->end()->end()
118
                            ->arrayNode('analyzer')->prototype('scalar')->defaultValue([])->end()->end()
119
                        ->end()
120
                    ->end()
121
                ->end()
122
            ->end();
123
124
        return $node;
125
    }
126
127
    /**
128
     * Managers configuration node.
129
     *
130
     * @return \Symfony\Component\Config\Definition\Builder\NodeDefinition
131
     */
132
    private function getManagersNode()
133
    {
134
        $builder = new TreeBuilder();
135
        $node = $builder->root('managers');
136
137
        $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...
138
            ->isRequired()
139
            ->requiresAtLeastOneElement()
140
            ->useAttributeAsKey('name')
141
            ->info('Maps managers to connections and bundles')
142
            ->prototype('array')
143
                ->children()
144
                    ->scalarNode('connection')
145
                        ->info('Sets connection for manager.')
146
                    ->end()
147
                    ->arrayNode('index')
148
                        ->children()
149
                            ->scalarNode('index_name')
150
                                ->isRequired()
151
                                ->info('Sets index name for connection.')
152
                            ->end()
153
                            ->arrayNode('hosts')
154
                                ->info('Defines hosts to connect to.')
155
                                ->defaultValue(['127.0.0.1:9200'])
156
                                ->prototype('scalar')
157
                                ->end()
158
                            ->end()
159
                            ->arrayNode('auth')
160
                                ->info('holds information for http authentication.')
161
                                ->children()
162
                                    ->scalarNode('username')
163
                                        ->isRequired()
164
                                        ->example('john')
165
                                    ->end()
166
                                    ->scalarNode('password')
167
                                        ->isRequired()
168
                                        ->example('mytopsecretpassword')
169
                                    ->end()
170
                                    ->scalarNode('option')
171
                                        ->defaultValue('Basic')
172
                                        ->info('authentication type')
173
                                    ->end()
174
                                ->end()
175
                            ->end()
176
                            ->arrayNode('settings')
177
                                ->defaultValue([])
178
                                ->info('Sets index settings for connection.')
179
                                ->prototype('variable')->end()
180
                            ->end()
181
                            ->arrayNode('analysis')
182
                                ->addDefaultsIfNotSet()
183
                                ->info('Sets index analysis settings for connection.')
184
                                ->children()
185
                                    ->arrayNode('tokenizer')->prototype('scalar')->defaultValue([])->end()->end()
186
                                    ->arrayNode('filter')->prototype('scalar')->defaultValue([])->end()->end()
187
                                    ->arrayNode('analyzer')->prototype('scalar')->defaultValue([])->end()->end()
188
                                ->end()
189
                            ->end()
190
                        ->end()
191
                    ->end()
192
                    ->integerNode('bulk_size')
193
                        ->min(0)
194
                        ->defaultValue(100)
195
                        ->info(
196
                            'Maximum documents size in the bulk container. ' .
197
                            'When the limit is reached it will auto-commit.'
198
                        )
199
                    ->end()
200
                    ->enumNode('commit_mode')
201
                        ->values(['refresh', 'flush', 'none'])
202
                        ->defaultValue('refresh')
203
                        ->info(
204
                            'The type of commit to the elasticsearch'
205
                        )
206
                    ->end()
207
                    ->arrayNode('logger')
208
                        ->info('Enables elasticsearch queries logging')
209
                        ->addDefaultsIfNotSet()
210
                        ->beforeNormalization()
211
                            ->ifTrue(
212
                                function ($v) {
213
                                    return is_bool($v);
214
                                }
215
                            )
216
                            ->then(
217
                                function ($v) {
218
                                    return ['enabled' => $v];
219
                                }
220
                            )
221
                        ->end()
222
                        ->children()
223
                            ->booleanNode('enabled')
224
                                ->info('enables logging')
225
                                ->defaultFalse()
226
                            ->end()
227
                            ->scalarNode('level')
228
                                ->info('Sets PSR logging level')
229
                                ->defaultValue(LogLevel::WARNING)
230
                                ->validate()
231
                                ->ifNotInArray((new \ReflectionClass('Psr\Log\LogLevel'))->getConstants())
232
                                    ->thenInvalid('Invalid PSR log level.')
233
                                ->end()
234
                            ->end()
235
                            ->scalarNode('log_file_name')
236
                                ->info('Log filename, by default it is a manager name')
237
                                ->defaultValue(null)
238
                            ->end()
239
                        ->end()
240
                    ->end()
241
                    ->arrayNode('mappings')
242
                        ->info('Maps manager to bundles. f.e. AcmeDemoBundle')
243
                        ->prototype('scalar')->end()
244
                    ->end()
245
                    ->booleanNode('force_commit')
246
                        ->info('Forces commit to elasticsearch on kernel terminate')
247
                        ->defaultTrue()
248
                    ->end()
249
                ->end()
250
            ->end();
251
252
        return $node;
253
    }
254
}
255