Completed
Pull Request — 5.2 (#949)
by Alexander
15:20
created

ManagerFactory::dispatch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 8
Ratio 100 %

Importance

Changes 0
Metric Value
dl 8
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
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\Service;
13
14
use Elasticsearch\ClientBuilder;
15
use ONGR\ElasticsearchBundle\Event\Events;
16
use ONGR\ElasticsearchBundle\Event\PostCreateManagerEvent;
17
use ONGR\ElasticsearchBundle\Event\PreCreateManagerEvent;
18
use ONGR\ElasticsearchBundle\Mapping\MetadataCollector;
19
use ONGR\ElasticsearchBundle\Result\Converter;
20
use PackageVersions\Versions;
21
use Psr\Log\LoggerInterface;
22
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
23
use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
24
use Symfony\Component\Stopwatch\Stopwatch;
25
26
/**
27
 * Elasticsearch Manager factory class.
28
 */
29
class ManagerFactory
30
{
31
    /**
32
     * @var MetadataCollector
33
     */
34
    private $metadataCollector;
35
36
    /**
37
     * @var Converter
38
     */
39
    private $converter;
40
41
    /**
42
     * @var LoggerInterface
43
     */
44
    private $logger;
45
46
    /**
47
     * @var LoggerInterface
48
     */
49
    private $tracer;
50
51
    /**
52
     * @var EventDispatcherInterface
53
     */
54
    private $eventDispatcher;
55
56
    /**
57
     * @var Stopwatch
58
     */
59
    private $stopwatch;
60
61
    /**
62
     * @param MetadataCollector $metadataCollector Metadata collector service.
63
     * @param Converter         $converter         Converter service to transform arrays to objects and visa versa.
64
     * @param LoggerInterface   $tracer
65
     * @param LoggerInterface   $logger
66
     */
67
    public function __construct($metadataCollector, $converter, $tracer = null, $logger = null)
68
    {
69
        $this->metadataCollector = $metadataCollector;
70
        $this->converter = $converter;
71
        $this->tracer = $tracer;
72
        $this->logger = $logger;
73
    }
74
75
    /**
76
     * @param EventDispatcherInterface   $eventDispatcher
77
     */
78
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
79
    {
80
        $this->eventDispatcher = $eventDispatcher;
81
    }
82
83
    /**
84
     * @param Stopwatch $stopwatch
85
     */
86
    public function setStopwatch(Stopwatch $stopwatch)
87
    {
88
        $this->stopwatch = $stopwatch;
89
    }
90
91
    /**
92
     * Factory function to create a manager instance.
93
     *
94
     * @param string $managerName   Manager name.
95
     * @param array  $connection    Connection configuration.
96
     * @param array  $analysis      Analyzers, filters and tokenizers config.
97
     * @param array  $managerConfig Manager configuration.
98
     *
99
     * @return Manager
100
     */
101
    public function createManager($managerName, $connection, $analysis, $managerConfig)
102
    {
103
        $mappings = $this->metadataCollector->getClientMapping($managerConfig['mappings']);
104
105
        $client = ClientBuilder::create();
106
        $client->setHosts($connection['hosts']);
107
108
        if ($this->tracer) {
109
            $client->setTracer($this->tracer);
110
        }
111
112
        if ($this->logger && $managerConfig['logger']['enabled']) {
113
            $client->setLogger($this->logger);
114
        }
115
116
        $indexSettings = [
117
            'index' => $connection['index_name'],
118
            'body' => array_filter(
119
                [
120
                    'settings' => array_merge(
121
                        $connection['settings'],
122
                        [
123
                            'analysis' =>
124
                                $this->metadataCollector->getClientAnalysis($managerConfig['mappings'], $analysis),
125
                        ]
126
                    ),
127
                    'mappings' => $mappings,
128
                ]
129
            ),
130
        ];
131
132
        if (class_exists(Versions::class)) {
133
            $elasticSearchVersion = explode('@', Versions::getVersion('elasticsearch/elasticsearch'))[0];
134
            if (0 === strpos($elasticSearchVersion, 'v')) {
135
                $elasticSearchVersion = substr($elasticSearchVersion, 1);
136
            }
137
            if (version_compare($elasticSearchVersion, '7.0.0', '>=')) {
138
                $indexSettings['include_type_name'] = true;
139
            }
140
        }
141
142
        $this->eventDispatcher &&
143
            $this->dispatch(
144
                Events::PRE_MANAGER_CREATE,
145
                $preCreateEvent = new PreCreateManagerEvent($client, $indexSettings)
146
            );
147
148
        $manager = new Manager(
149
            $managerName,
150
            $managerConfig,
151
            $client->build(),
152
            $preCreateEvent->getIndexSettings(),
0 ignored issues
show
Bug introduced by
The variable $preCreateEvent does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
153
            $this->metadataCollector,
154
            $this->converter
155
        );
156
157
        if (isset($this->stopwatch)) {
158
            $manager->setStopwatch($this->stopwatch);
159
        }
160
161
        $manager->setCommitMode($managerConfig['commit_mode']);
162
        $manager->setEventDispatcher($this->eventDispatcher);
163
        $manager->setCommitMode($managerConfig['commit_mode']);
164
        $manager->setBulkCommitSize($managerConfig['bulk_size']);
165
166
        $this->eventDispatcher &&
167
            $this->dispatch(Events::POST_MANAGER_CREATE, new PostCreateManagerEvent($manager));
168
169
        return $manager;
170
    }
171
172 View Code Duplication
    private function dispatch($eventName, $event)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
173
    {
174
        if (class_exists(LegacyEventDispatcherProxy::class)) {
175
            return $this->eventDispatcher->dispatch($event, $eventName);
176
        } else {
177
            return $this->eventDispatcher->dispatch($eventName, $event);
178
        }
179
    }
180
}
181