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

AbstractElasticsearchTestCase::tearDown()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
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\Test;
13
14
use ONGR\ElasticsearchBundle\Service\Manager;
15
use ONGR\ElasticsearchBundle\Tests\WebTestCase;
16
use Symfony\Bridge\PhpUnit\SetUpTearDownTrait;
17
use Symfony\Component\DependencyInjection\ContainerInterface;
18
19
/**
20
 * Base test which creates unique connection to test with.
21
 */
22
abstract class AbstractElasticsearchTestCase extends WebTestCase
23
{
24
    use SetUpTearDownTrait;
25
26
    /**
27
     * @var Manager[] Holds used managers.
28
     */
29
    private $managers = [];
30
31
    /**
32
     * @var ContainerInterface
33
     */
34
    protected static $container;
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    protected function doSetUp()
40
    {
41
        self::$container = null;
42
        foreach ($this->getDataArray() as $manager => $data) {
43
            // Create index and populate data
44
            $this->getManager($manager);
45
        }
46
    }
47
48
    /**
49
     * Can be overwritten in child class to populate elasticsearch index with the data.
50
     *
51
     * Example:
52
     *      "manager_name" =>
53
     *      [
54
     *          'type_name' => [
55
     *              [
56
     *                  '_id' => 1,
57
     *                  'title' => 'foo',
58
     *              ],
59
     *              [
60
     *                  '_id' => 2,
61
     *                  'title' => 'bar',
62
     *              ]
63
     *          ]
64
     *      ]
65
     *
66
     * @return array
67
     */
68
    protected function getDataArray()
69
    {
70
        return [];
71
    }
72
73
    /**
74
     * Ignores versions specified.
75
     *
76
     * Returns two dimensional array, first item in sub array is version to ignore, second is comparator,
77
     * last test name. If no test name is provided it will be used on all test class.
78
     *
79
     * Comparator types can be found in `version_compare` documentation.
80
     *
81
     * Example: [
82
     *   ['1.2.7', '<='],
83
     *   ['1.2.9', '==', 'testSmth']
84
     * ]
85
     *
86
     * @return array
87
     */
88
    protected function getIgnoredVersions()
89
    {
90
        return [];
91
    }
92
93
    /**
94
     * Ignores version specified.
95
     *
96
     * @param Manager $manager
97
     */
98
    private function ignoreVersions(Manager $manager)
99
    {
100
        $currentVersion = $manager->getVersionNumber();
101
        $ignore = null;
102
103
        foreach ($this->getIgnoredVersions() as $ignoredVersion) {
104
            if (version_compare($currentVersion, $ignoredVersion[0], $ignoredVersion[1]) === true) {
105
                $ignore = true;
106
                if (isset($ignoredVersion[2])) {
107
                    if ($ignoredVersion[2] === $this->getName()) {
108
                        break;
109
                    }
110
                    $ignore = false;
111
                }
112
            }
113
        }
114
115
        if ($ignore === true) {
116
            $this->markTestSkipped("Elasticsearch version {$currentVersion} not supported by this test.");
117
        }
118
    }
119
120
    /**
121
     * Removes manager from local cache and drops its index.
122
     *
123
     * @param string $name
124
     */
125
    protected function removeManager($name)
126
    {
127
        if (isset($this->managers[$name])) {
128
            $this->managers[$name]->dropIndex();
129
            unset($this->managers[$name]);
130
        }
131
    }
132
133
    /**
134
     * Populates elasticsearch with data.
135
     *
136
     * @param Manager $manager
137
     * @param array   $data
138
     */
139
    private function populateElasticsearchWithData($manager, array $data)
140
    {
141
        if (!empty($data)) {
142
            foreach ($data as $type => $documents) {
143
                foreach ($documents as $document) {
144
                    $manager->bulk('index', $type, $document);
145
                }
146
            }
147
            $manager->commit();
148
            $manager->refresh();
149
        }
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155
    protected function doTearDown()
156
    {
157
        parent::tearDown();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (tearDown() instead of doTearDown()). Are you sure this is correct? If so, you might want to change this to $this->tearDown().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
158
159
        foreach ($this->managers as $name => $manager) {
160
            try {
161
                $manager->dropIndex();
162
            } catch (\Exception $e) {
163
                // Do nothing.
164
            }
165
        }
166
    }
167
168
    /**
169
     * Returns service container.
170
     *
171
     * @param array $kernelOptions Options used passed to kernel if it needs to be initialized.
172
     *
173
     * @return ContainerInterface
174
     */
175
    protected function getContainer($kernelOptions = [])
176
    {
177
        if (null === self::$container) {
178
            self::bootKernel($kernelOptions);
179
            self::$container = static::$kernel->getContainer();
180
        }
181
182
        return self::$container;
183
    }
184
185
    /**
186
     * Returns manager instance with injected connection if does not exist creates new one.
187
     *
188
     * @param string $name Manager name
189
     *
190
     * @return Manager
191
     *
192
     * @throws \LogicException
193
     */
194
    protected function getManager($name = 'default')
195
    {
196
        $serviceName = sprintf('es.manager.%s', $name);
197
198
        // Looks for cached manager.
199
        if (array_key_exists($name, $this->managers)) {
200
            $this->ignoreVersions($this->managers[$name]);
201
202
            return $this->managers[$name];
203
        } elseif ($this->getContainer()->has($serviceName)) {
204
            /** @var Manager $manager */
205
            $manager = $this->getContainer()->get($serviceName);
206
            $this->managers[$name] = $manager;
207
        } else {
208
            throw new \LogicException(sprintf("Manager '%s' does not exist", $name));
209
        }
210
211
        $this->ignoreVersions($manager);
212
        $manager->dropAndCreateIndex();
213
214
        // Populates elasticsearch index with data
215
        $data = $this->getDataArray();
216
        if (!empty($data[$name])) {
217
            $this->populateElasticsearchWithData($manager, $data[$name]);
218
        }
219
220
        return $manager;
221
    }
222
}
223