Completed
Branch v2 (10e463)
by Alexey
02:41
created

Hydrator   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 1
dl 0
loc 64
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A hydrateResponse() 0 7 1
C extractDocuments() 0 22 7
A filter() 0 4 1
A extractTotal() 0 8 2
1
<?php namespace Bardex\Elastic;
2
3
4
class Hydrator implements IHydrator
5
{
6
7
    /**
8
     * Создать из ответа ElasticSearch экземпляр SearchResult
9
     * @param array $response
10
     * @return SearchResult
11
     */
12
    public function hydrateResponse(array $response)
13
    {
14
        $results = $this->extractDocuments($response);
15
        $total = $this->extractTotal($response);
16
        $searchResult = new SearchResult($results, $total);
17
        return $searchResult;
18
    }
19
20
    /**
21
     * Выбрать документы из ответа ES-сервера и добавить script fields.
22
     * @param array $response - ответ ES сервера.
23
     * @return array - возвращает набор документов
24
     */
25
    protected function extractDocuments(array $response)
26
    {
27
        $results = [];
28
        if (isset($response['hits']['hits'])) {
29
            foreach ($response['hits']['hits'] as $hit) {
30
                $row = $hit['_source'];
31
                if (isset($hit['fields'])) { // script fields
32
                    foreach ($hit['fields'] as $field => $data) {
33
                        if (count($data) == 1) {
34
                            $row[$field] = array_shift($data);
35
                        } else {
36
                            $row[$field] = $data;
37
                        }
38
                    }
39
                }
40
                if ($this->filter($row)) {
41
                    $results[] = $row;
42
                }
43
            }
44
        }
45
        return $results;
46
    }
47
48
    protected function filter($row)
49
    {
50
        return $row;
51
    }
52
53
54
    /**
55
     * Выбрать из ответа ES-сервера количество найденных документов.
56
     * @param array $response - ответ ES сервера.
57
     * @return integer - возвращает количество найденных документов.
58
     */
59
    protected function extractTotal(array $response)
60
    {
61
        $total = 0;
62
        if (isset($response['hits']['total'])) {
63
            $total = $response['hits']['total'];
64
        }
65
        return $total;
66
    }
67
}