SortStringParser   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 17
c 1
b 0
f 0
dl 0
loc 44
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B buildSortFromString() 0 36 8
1
<?php namespace Nord\Lumen\Elasticsearch\Parsers;
2
3
use Nord\Lumen\Elasticsearch\Search\Sort\AbstractSort;
4
use Nord\Lumen\Elasticsearch\Search\Sort\DocSort;
5
use Nord\Lumen\Elasticsearch\Search\Sort\FieldSort;
6
use Nord\Lumen\Elasticsearch\Search\Sort\ScoreSort;
7
8
/**
9
 * Example: "name:asc" => [['name' => ['order' => 'asc']]]
10
 */
11
class SortStringParser extends AbstractStringParser
12
{
13
14
    /**
15
     * @param string $string
16
     *
17
     * @return AbstractSort[]
18
     */
19
    public function buildSortFromString($string)
20
    {
21
        $sorts = [];
22
23
        if (!empty($string)) {
24
            foreach ($this->parse($string) as $item) {
25
26
                /*
27
                 * Position map:
28
                 * - 0 = field name
29
                 * - 1 = order (asc/desc)
30
                 * - 2 = mode (min/max/sum/avg/median)
31
                 */
32
33
                if (isset($item[0])) {
34
                    if ($item[0] === '_score') {
35
                        $sort = new ScoreSort();
36
                    } elseif ($item[0] === '_doc') {
37
                        $sort = new DocSort();
38
                    } else {
39
                        $sort = (new FieldSort())->setField($item[0]);
40
                    }
41
42
                    if (isset($item[1])) {
43
                        $sort->setOrder($item[1]);
44
                    }
45
                    if (isset($item[2])) {
46
                        $sort->setMode($item[2]);
47
                    }
48
49
                    $sorts[] = $sort;
50
                }
51
            }
52
        }
53
54
        return $sorts;
55
    }
56
}
57