Completed
Pull Request — develop (#167)
by Daniel
25:11
created

Elasticsearch::deleteIndexByQuery()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 14
ccs 8
cts 8
cp 1
rs 9.9666
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
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 Elastica\Type;
28
use TYPO3\CMS\Core\SingletonInterface as Singleton;
29
use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;
30
31
/**
32
 * Outer wrapper to elasticsearch.
33
 */
34
class Elasticsearch implements Singleton, ConnectionInterface
35
{
36
    /**
37
     * @var Elasticsearch\Connection
38
     */
39
    protected $connection;
40
41
    /**
42
     * @var Elasticsearch\IndexFactory
43
     */
44
    protected $indexFactory;
45
46
    /**
47
     * @var Elasticsearch\TypeFactory
48
     */
49
    protected $typeFactory;
50
51
    /**
52
     * @var Elasticsearch\MappingFactory
53
     */
54
    protected $mappingFactory;
55
56
    /**
57
     * @var Elasticsearch\DocumentFactory
58
     */
59
    protected $documentFactory;
60
61
    /**
62
     * @var QueryFactory
63
     */
64
    protected $queryFactory;
65
66
    /**
67
     * @var \TYPO3\CMS\Core\Log\Logger
68
     */
69
    protected $logger;
70
71
    /**
72
     * @var ObjectManagerInterface
73
     */
74
    protected $objectManager;
75
76
    /**
77
     * Inject log manager to get concrete logger from it.
78 50
     *
79
     * @param \TYPO3\CMS\Core\Log\LogManager $logManager
80 50
     */
81 50
    public function injectLogger(\TYPO3\CMS\Core\Log\LogManager $logManager)
82
    {
83
        $this->logger = $logManager->getLogger(__CLASS__);
84
    }
85
86 50
    /**
87
     * @param ObjectManagerInterface $objectManager
88 50
     */
89 50
    public function injectObjectManager(ObjectManagerInterface $objectManager)
90
    {
91
        $this->objectManager = $objectManager;
92
    }
93
94
    /**
95
     * @param Elasticsearch\Connection $connection
96
     * @param Elasticsearch\IndexFactory $indexFactory
97
     * @param Elasticsearch\TypeFactory $typeFactory
98
     * @param Elasticsearch\MappingFactory $mappingFactory
99 50
     * @param Elasticsearch\DocumentFactory $documentFactory
100
     * @param QueryFactory $queryFactory
101
     */
102
    public function __construct(
103
        Elasticsearch\Connection $connection,
104
        Elasticsearch\IndexFactory $indexFactory,
105
        Elasticsearch\TypeFactory $typeFactory,
106
        Elasticsearch\MappingFactory $mappingFactory,
107 50
        Elasticsearch\DocumentFactory $documentFactory,
108 50
        QueryFactory $queryFactory
109 50
    ) {
110 50
        $this->connection = $connection;
111 50
        $this->indexFactory = $indexFactory;
112 50
        $this->typeFactory = $typeFactory;
113 50
        $this->mappingFactory = $mappingFactory;
114
        $this->documentFactory = $documentFactory;
115 2
        $this->queryFactory = $queryFactory;
116
    }
117 2
118 2
    public function addDocument(string $documentType, array $document)
119 2
    {
120 2
        $this->withType(
121 2
            $documentType,
122
            function (Type $type, string $documentType) use ($document) {
123 2
                $type->addDocument($this->documentFactory->getDocument($documentType, $document));
124
            }
125 2
        );
126
    }
127
128 2
    public function deleteDocument(string $documentType, string $identifier)
129 2
    {
130 2
        try {
131 2
            $this->withType(
132 2
                $documentType,
133
                function (Type $type, string $documentType) use ($identifier) {
0 ignored issues
show
Unused Code introduced by
The parameter $documentType is not used and could be removed. ( Ignorable by Annotation )

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

133
                function (Type $type, /** @scrutinizer ignore-unused */ string $documentType) use ($identifier) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
134
                    $type->deleteById($identifier);
135
                }
136
            );
137
        } catch (\Elastica\Exception\NotFoundException $exception) {
138
            $this->logger->debug(
139
                'Tried to delete document in index, which does not exist.',
140 2
                [$documentType, $identifier]
141
            );
142
        }
143
    }
144
145
    public function updateDocument(string $documentType, array $document)
146
    {
147
        $this->withType(
148
            $documentType,
149
            function (Type $type, string $documentType) use ($document) {
150
                $type->updateDocument($this->documentFactory->getDocument($documentType, $document));
151
            }
152 14
        );
153
    }
154 14
155 14
    public function addDocuments(string $documentType, array $documents)
156 14
    {
157 14
        $this->withType(
158 14
            $documentType,
159
            function (Type $type, string $documentType) use ($documents) {
160 14
                $type->addDocuments($this->documentFactory->getDocuments($documentType, $documents));
161
            }
162 2
        );
163
    }
164 2
165
    public function deleteIndex()
166 2
    {
167
        $index = $this->connection->getClient()->getIndex($this->indexFactory->getIndexName());
168
169
        if (!$index->exists()) {
170
            $this->logger->notice(
171
                'Index did not exist, therefore was not deleted.',
172
                [$this->indexFactory->getIndexName()]
173
            );
174 2
            return;
175 2
        }
176
177
        $index->delete();
178
    }
179
180 16
    public function deleteIndexByDocumentType(string $documentType)
181
    {
182 16
        $this->deleteIndexByQuery(Query::create([
183
            'query' => [
184
                'term' => [
185
                    'search_document_type' => $documentType,
186
                ],
187
            ],
188
        ]));
189 16
    }
190 16
191 16
    private function deleteIndexByQuery(Query $query)
192 16
    {
193
        $index = $this->connection->getClient()->getIndex($this->indexFactory->getIndexName());
194 4
        if (!$index->exists()) {
195
            $this->logger->notice(
196 4
                'Index did not exist, therefore items can not be deleted by query.',
197
                [$this->indexFactory->getIndexName(), $query->getQuery()]
198 4
            );
199 4
            return;
200 4
        }
201
        $response = $index->deleteByQuery($query);
202 4
        if ($response->getData()['deleted'] > 0) {
203
            // Refresh index when delete query is invoked
204
            $index->refresh();
205 16
        }
206
    }
207 16
208 16
    public function search(SearchRequestInterface $searchRequest): SearchResultInterface
209 16
    {
210 16
        $this->logger->debug('Search for', [$searchRequest->getSearchTerm()]);
211
212 16
        $search = new \Elastica\Search($this->connection->getClient());
213
        $search->addIndex($this->indexFactory->getIndexName());
214
        $search->setQuery($this->queryFactory->create($searchRequest));
215
216
        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

216
        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...
217
    }
218
219
    /**
220
     * Execute given callback with Elastica Type based on provided documentType
221
     */
222
    private function withType(string $documentType, callable $callback)
223
    {
224
        $type = $this->typeFactory->getType($documentType);
225
        // TODO: Check whether it's to heavy to send it so often e.g. for every single document.
226
        // Perhaps add command controller to submit mapping?!
227
        // Also it's not possible to change mapping without deleting index first.
228
        // Mattes told about a solution.
229
        // So command looks like the best way so far, except we manage mattes solution.
230
        // Still then this should be done once. So perhaps singleton which tracks state and does only once?
231
        $this->mappingFactory->getMapping($documentType)->send();
232
        $callback($type, $documentType);
233
        $type->getIndex()->refresh();
234
    }
235
}
236