Completed
Push — 6.0-dev ( 1ef812...ceea66 )
by Simonas
01:30
created

AbstractElasticsearchTestCase   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 102
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 4
dl 0
loc 102
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 3 1
A getDataArray() 0 4 1
A populateElastic() 0 7 2
A tearDown() 0 12 3
A getContainer() 0 10 3
B getIndex() 0 27 7
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 Elasticsearch\Common\Exceptions\BadRequest400Exception;
15
use ONGR\ElasticsearchBundle\Service\IndexService;
16
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
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
    protected static $cachedContainer;
25
26
    /**
27
     * @var IndexService[]
28
     */
29
    private $indexes = [];
30
31
    //You may use setUp() for your personal needs.
32
    protected function setUp()
33
    {
34
    }
35
36
    /**
37
     * Can be overwritten in child class to populate elasticsearch index with the data.
38
     *
39
     * Example:
40
     *      "/This/Should/Be/Index/Document/Namespace" =>
41
     *      [
42
     *          '_doc' => [
43
     *              [
44
     *                  '_id' => 1,
45
     *                  'title' => 'foo',
46
     *              ],
47
     *              [
48
     *                  '_id' => 2,
49
     *                  'title' => 'bar',
50
     *              ]
51
     *          ]
52
     *      ]
53
     *
54
     * @return array
55
     */
56
    protected function getDataArray()
57
    {
58
        return [];
59
    }
60
61
    private function populateElastic(IndexService $indexService, array $documents = [])
62
    {
63
        foreach ($documents as $document) {
64
            $indexService->bulk('index', $document);
65
        }
66
        $indexService->commit();
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    protected function tearDown()
73
    {
74
        parent::tearDown();
75
76
        foreach ($this->indexes as $name => $index) {
77
            try {
78
                $index->dropIndex();
79
            } catch (\Exception $e) {
80
                // Do nothing.
81
            }
82
        }
83
    }
84
85
    protected function getContainer($reinitialize = false, $kernelOptions = []): ContainerInterface
86
    {
87
        if (!self::$cachedContainer && !$reinitialize) {
88
            static::bootKernel($kernelOptions);
89
90
            self::$cachedContainer = static::createClient(['environment' => 'test'])->getContainer();
91
        }
92
93
        return self::$cachedContainer;
94
    }
95
96
    protected function getIndex($namespace, $createIndex = true): IndexService
97
    {
98
        try {
99
            if (!array_key_exists($namespace, $this->indexes)) {
100
                $this->indexes[$namespace] = $this->getContainer()->get($namespace);
101
            }
102
103
            if (!$this->indexes[$namespace]->indexExists() && $createIndex) {
104
                $this->indexes[$namespace]->dropAndCreateIndex();
105
106
                // Populates elasticsearch index with the data
107
                $data = $this->getDataArray();
108
                if (!empty($data[$namespace])) {
109
                    $this->populateElastic($this->indexes[$namespace], $data[$namespace]);
110
                }
111
                $this->indexes[$namespace]->refresh();
112
            }
113
114
            return $this->indexes[$namespace];
115
        } catch (BadRequest400Exception $e) {
116
            throw new \LogicException($e->getMessage());
117
        } catch (\Exception $e) {
118
            throw new \LogicException(
119
                sprintf("There is no Elastic index defined in the '%s' namespace", $namespace)
120
            );
121
        }
122
    }
123
}
124