Passed
Pull Request — develop (#167)
by Daniel
05:05
created

Elasticsearch::deleteIndexByQuery()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.576

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 14
ccs 6
cts 10
cp 0.6
rs 9.9666
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3.576
1
<?php
2
3
namespace Codappix\SearchCore\Connection;
4
5
/*
6
 * Copyright (C) 2016  Daniel Siepmann <[email protected]>
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21
 * 02110-1301, USA.
22
 */
23
24
use Codappix\SearchCore\Connection\Elasticsearch\SearchResult;
25
use Codappix\SearchCore\Domain\Search\QueryFactory;
26
use Elastica\Query;
27
use TYPO3\CMS\Core\SingletonInterface as Singleton;
28
use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;
29
30
/**
31
 * Outer wrapper to elasticsearch.
32
 */
33
class Elasticsearch implements Singleton, ConnectionInterface
34
{
35
    /**
36
     * @var Elasticsearch\Connection
37
     */
38
    protected $connection;
39
40
    /**
41
     * @var Elasticsearch\IndexFactory
42
     */
43
    protected $indexFactory;
44
45
    /**
46
     * @var Elasticsearch\TypeFactory
47
     */
48
    protected $typeFactory;
49
50
    /**
51
     * @var Elasticsearch\MappingFactory
52
     */
53
    protected $mappingFactory;
54
55
    /**
56
     * @var Elasticsearch\DocumentFactory
57
     */
58
    protected $documentFactory;
59
60
    /**
61
     * @var QueryFactory
62
     */
63
    protected $queryFactory;
64
65
    /**
66
     * @var \TYPO3\CMS\Core\Log\Logger
67
     */
68
    protected $logger;
69
70
    /**
71
     * @var ObjectManagerInterface
72
     */
73
    protected $objectManager;
74
75
    /**
76
     * Inject log manager to get concrete logger from it.
77
     *
78
     * @param \TYPO3\CMS\Core\Log\LogManager $logManager
79
     */
80 52
    public function injectLogger(\TYPO3\CMS\Core\Log\LogManager $logManager)
81
    {
82 52
        $this->logger = $logManager->getLogger(__CLASS__);
83 52
    }
84
85
    /**
86
     * @param ObjectManagerInterface $objectManager
87
     */
88 52
    public function injectObjectManager(ObjectManagerInterface $objectManager)
89
    {
90 52
        $this->objectManager = $objectManager;
91 52
    }
92
93
    /**
94
     * @param Elasticsearch\Connection $connection
95
     * @param Elasticsearch\IndexFactory $indexFactory
96
     * @param Elasticsearch\TypeFactory $typeFactory
97
     * @param Elasticsearch\MappingFactory $mappingFactory
98
     * @param Elasticsearch\DocumentFactory $documentFactory
99
     * @param QueryFactory $queryFactory
100
     */
101 52
    public function __construct(
102
        Elasticsearch\Connection $connection,
103
        Elasticsearch\IndexFactory $indexFactory,
104
        Elasticsearch\TypeFactory $typeFactory,
105
        Elasticsearch\MappingFactory $mappingFactory,
106
        Elasticsearch\DocumentFactory $documentFactory,
107
        QueryFactory $queryFactory
108
    ) {
109 52
        $this->connection = $connection;
110 52
        $this->indexFactory = $indexFactory;
111 52
        $this->typeFactory = $typeFactory;
112 52
        $this->mappingFactory = $mappingFactory;
113 52
        $this->documentFactory = $documentFactory;
114 52
        $this->queryFactory = $queryFactory;
115 52
    }
116
117 2
    public function addDocument(string $documentType, array $document)
118
    {
119 2
        $this->withType(
120 2
            $documentType,
121 2
            function ($type) use ($documentType, $document) {
122 2
                $type->addDocument($this->documentFactory->getDocument($documentType, $document));
123 2
            }
124
        );
125 2
    }
126
127 2
    public function deleteDocument(string $documentType, string $identifier)
128
    {
129
        try {
130 2
            $this->withType(
131 2
                $documentType,
132 2
                function ($type) use ($identifier) {
133 2
                    $type->deleteById($identifier);
134 2
                }
135
            );
136
        } catch (\Elastica\Exception\NotFoundException $exception) {
137
            $this->logger->debug(
138
                'Tried to delete document in index, which does not exist.',
139
                [$documentType, $identifier]
140
            );
141
        }
142 2
    }
143
144
    public function updateDocument(string $documentType, array $document)
145
    {
146
        $this->withType(
147
            $documentType,
148
            function ($type) use ($documentType, $document) {
149
                $type->updateDocument($this->documentFactory->getDocument($documentType, $document));
150
            }
151
        );
152
    }
153
154 16
    public function addDocuments(string $documentType, array $documents)
155
    {
156 16
        $this->withType(
157 16
            $documentType,
158 16
            function ($type) use ($documentType, $documents) {
159 16
                $type->addDocuments($this->documentFactory->getDocuments($documentType, $documents));
160 16
            }
161
        );
162 16
    }
163
164 2
    public function deleteIndex()
165
    {
166 2
        $index = $this->connection->getClient()->getIndex($this->indexFactory->getIndexName());
167
168 2
        if (!$index->exists()) {
169
            $this->logger->notice(
170
                'Index did not exist, therefore was not deleted.',
171
                [$this->indexFactory->getIndexName()]
172
            );
173
            return;
174
        }
175
176 2
        $index->delete();
177 2
    }
178
179 2
    public function deleteIndexByDocumentType(string $documentType)
180
    {
181 2
        $query = Query::create([
182
            'query' => [
183
                'term' => [
184 2
                    'search_document_type' => $documentType
185
                ]
186
            ]
187
        ]);
188 2
        $this->deleteIndexByQuery($query);
189 2
    }
190
191 2
    public function deleteIndexByQuery(Query $query)
192
    {
193 2
        $index = $this->connection->getClient()->getIndex($this->indexFactory->getIndexName());
194 2
        if (!$index->exists()) {
195
            $this->logger->notice(
196
                'Index did not exist, therefore items can not be deleted by query.',
197
                [$this->indexFactory->getIndexName(), $query->getQuery()]
198
            );
199
            return;
200
        }
201 2
        $response = $index->deleteByQuery($query);
202 2
        if ($response->getData()['deleted'] > 0) {
203
            // Refresh index when delete query is invoked
204 2
            $index->refresh();
205
        }
206 2
    }
207
208
    /**
209
     * Execute given callback with Elastica Type based on provided documentType
210
     */
211 18
    protected function withType(string $documentType, callable $callback)
212
    {
213 18
        $type = $this->getType($documentType);
214
        // TODO: Check whether it's to heavy to send it so often e.g. for every single document.
215
        // Perhaps add command controller to submit mapping?!
216
        // Also it's not possible to change mapping without deleting index first.
217
        // Mattes told about a solution.
218
        // So command looks like the best way so far, except we manage mattes solution.
219
        // Still then this should be done once. So perhaps singleton which tracks state and does only once?
220 18
        $this->mappingFactory->getMapping($type, $documentType)->send();
221 18
        $callback($type);
222 18
        $type->getIndex()->refresh();
223 18
    }
224
225 4
    public function search(SearchRequestInterface $searchRequest): SearchResultInterface
226
    {
227 4
        $this->logger->debug('Search for', [$searchRequest->getSearchTerm()]);
228
229 4
        $search = new \Elastica\Search($this->connection->getClient());
230 4
        $search->addIndex($this->indexFactory->getIndexName());
231 4
        $search->setQuery($this->queryFactory->create($searchRequest));
232
233 4
        return $this->objectManager->get(SearchResult::class, $searchRequest, $search->search());
0 ignored issues
show
Unused Code introduced by
The call to TYPO3\CMS\Extbase\Object...ManagerInterface::get() has too many arguments starting with $searchRequest. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

233
        return $this->objectManager->/** @scrutinizer ignore-call */ get(SearchResult::class, $searchRequest, $search->search());

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
234
    }
235
236 18
    protected function getType($documentType): \Elastica\Type
237
    {
238 18
        return $this->typeFactory->getType(
239 18
            $this->indexFactory->getIndex(
240 18
                $this->connection,
241 18
                $documentType
242
            ),
243 18
            'document'
244
        );
245
    }
246
}
247