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

WithSorts::formatSorts()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 13
ccs 8
cts 8
cp 1
crap 3
rs 10
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