Passed
Pull Request — master (#65)
by Zing
05:54
created

WithSorts   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 57
ccs 25
cts 25
cp 1
rs 10
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A enableSorts() 0 19 3
A getSortValue() 0 7 2
A isRequestedSort() 0 3 2
A formatSorts() 0 13 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Zing\QueryBuilder\Concerns;
6
7
use Zing\QueryBuilder\Sort;
8
9
trait WithSorts
10
{
11
    /**
12
     * 排序逻辑.
13
     *
14
     * @param array $sorts
15
     *
16
     * @return mixed
17
     */
18 3
    public function enableSorts($sorts)
19
    {
20 3
        $this->formatSorts($sorts)->each(
21 3
            function (Sort $sort): void {
22 3
                if ($this->isRequestedSort($sort)) {
23 3
                    $sort->sort($this, $this->getSortValue($sort));
24
25 3
                    return;
26
                }
27
28 1
                if ($sort->hasDefaultDirection()) {
29 1
                    $sort->sort($this, $sort->getDefaultDirection());
30
31 1
                    return;
32
                }
33 3
            }
34
        );
35
36 3
        return $this;
37
    }
38
39 3
    protected function isRequestedSort(Sort $sort)
40
    {
41 3
        return $this->request->input('asc') === $sort->getProperty() || $this->request->input('desc') === $sort->getProperty();
42
    }
43
44 3
    protected function getSortValue(Sort $sort)
45
    {
46 3
        if ($this->request->input('desc') === $sort->getProperty()) {
47 1
            return 'desc';
48
        }
49
50 3
        return 'asc';
51
    }
52
53 3
    public function formatSorts($sorts)
54
    {
55 3
        return collect($sorts)->map(
56 3
            function ($sort, $key) {
57 3
                if ($sort instanceof Sort) {
58 1
                    return $sort;
59
                }
60
61 3
                if (is_string($key)) {
62 1
                    return Sort::field($key, $sort);
63
                }
64
65 2
                return Sort::field($sort);
66 3
            }
67
        );
68
    }
69
}
70