Completed
Branch devel (9c998f)
by Alexey
02:01
created

Query::fetchRaw()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 0
1
<?php
2
3
namespace Bardex\Elastic;
4
5
6
use Elasticsearch\Client as ElasticClient;
7
use Psr\Log\LoggerInterface;
8
use Psr\Log\NullLogger;
9
10
/**
11
 * Class Query
12
 * @package Bardex\Elastic
13
 * @author Alexey Sumin <[email protected]>
14
 */
15
abstract class Query implements \JsonSerializable
16
{
17
    /**
18
     * @var LoggerInterface $logger
19
     */
20
    protected $logger;
21
22
    /**
23
     * @var ElasticClient $client
24
     */
25
    protected $elastic;
26
27
    /**
28
     * Получить собранный elasticsearch-запрос
29
     * @return array
30
     */
31
    abstract public function getQuery();
32
33
34
    /**
35
     * Отправить запрос на конкретный endpoint elasticsearch-сервера
36
     * @param array $query
37
     * @return array
38
     */
39
    abstract protected function executeQuery(array $query);
40
41
42
    /**
43
     * Конструктор
44
     * @param ElasticClient $elastic
45
     */
46
    public function __construct(ElasticClient $elastic)
47
    {
48
        $this->elastic = $elastic;
49
        $this->logger = new NullLogger;
50
    }
51
52
53
    /**
54
     * Добавить Psr-совместимый логгер
55
     * @param LoggerInterface $logger
56
     * @return Query $this
57
     */
58
    public function setLogger(LoggerInterface $logger)
59
    {
60
        $this->logger = $logger;
61
        return $this;
62
    }
63
64
65
    /**
66
     * Выполнить запрос к ES и вернуть результаты поиска.
67
     * @return SearchResult - возвращает набор документов
68
     */
69
    public function fetchAll()
70
    {
71
        $response = $this->fetchRaw();
72
        $result = $this->createSearchResult($response);
73
        return $result;
74
    }
75
76
77
    /**
78
     * Выполнить запрос к ES и вернуть необработанный результат (с мета-данными).
79
     * @return array возвращает необработанный ответ ES
80
     */
81
    public function fetchRaw()
82
    {
83
        // build query
84
        $query = $this->getQuery();
85
86
        $start = microtime(1);
87
88
        // send query to elastic
89
        $result = $this->executeQuery($query);
90
91
        // measure time
92
        $time = round((microtime(1) - $start) * 1000);
0 ignored issues
show
Unused Code introduced by
$time is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
93
94
        return $result;
95
    }
96
97
98
    /**
99
     * Создать из ответа ES-сервера экземляр SearchResult
100
     * @param array $response
101
     * @return SearchResult
102
     */
103
    protected function createSearchResult(array $response)
104
    {
105
        $results  = $this->extractDocuments($response);
106
        $total    = $this->extractTotal($response);
107
        $searchResult = new SearchResult($results, $total);
108
        return $searchResult;
109
    }
110
111
    /**
112
     * Выбрать документы из ответа ES-сервера и добавить script fields.
113
     * @param array $response - ответ ES сервера.
114
     * @return array - возвращает набор документов
115
     */
116
    protected function extractDocuments(array $response)
117
    {
118
        $results = [];
119
        if (isset($response['hits']['hits'])) {
120
            foreach ($response['hits']['hits'] as $hit) {
121
                $row = $hit['_source'];
122
                if (isset($hit['fields'])) { // script fields
123
                    foreach ($hit['fields'] as $field => $data) {
124
                        if (count($data) == 1) {
125
                            $row[$field] = array_shift($data);
126
                        } else {
127
                            $row[$field] = $data;
128
                        }
129
                    }
130
                }
131
                $results[] = $row;
132
            }
133
        }
134
        return $results;
135
    }
136
137
138
    /**
139
     * Выбрать из ответа ES-сервера количество найденных документов.
140
     * @param array $response - ответ ES сервера.
141
     * @return integer - возвращает количество найденных документов.
142
     */
143
    protected function extractTotal(array $response)
144
    {
145
        $total = 0;
146
        if (isset($response['hits']['total'])) {
147
            $total = $response['hits']['total'];
148
        }
149
        return $total;
150
    }
151
152
153
    /**
154
     * Имплементация \JsonSerializable
155
     * @return array
156
     */
157
    public function jsonSerialize()
158
    {
159
        return $this->getQuery();
160
    }
161
}