Completed
Push — master ( 99f6c2...5bcbf0 )
by Pavel
05:52
created

IndexRestRequest::getQuery()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 3
nop 0
dl 0
loc 11
ccs 0
cts 6
cp 0
crap 20
rs 9.2
c 0
b 0
f 0
1
<?php namespace Pz\LaravelDoctrine\Rest\Request;
2
3
use Illuminate\Validation\Factory;
4
use Doctrine\ORM\Query\Expr\OrderBy;
5
6
use Pz\LaravelDoctrine\Rest\RestRequest;
7
use Pz\Doctrine\Rest\Request\IndexRequestInterface;
8
9
class IndexRestRequest extends RestRequest implements IndexRequestInterface
10
{
11
    /**
12
     * @return array
13
     */
14 1
    public function rules()
15
    {
16
        return [
17
            // Query
18 1
            'filter'        => 'string',
19
20
            // Pagination
21
            'page'          => 'array',
22
            'page.offset'   => 'required_with:page|numeric',
23
            'page.limit'    => 'required_with:page|numeric',
24
25
            // Sorting
26
            'sort'          => 'string',
27
        ];
28
    }
29
30
    /**
31
     * @return string
32
     */
33 1
    public function ability()
34
    {
35 1
         return 'index';
36
    }
37
38
    /**
39
     * @return int
40
     */
41
    public function getStart()
42
    {
43
        return $this->input('page.offset', 0);
44
    }
45
46
    /**
47
     * @return int
48
     */
49
    public function getLimit()
50
    {
51
        return $this->input('page.limit', 50);
52
    }
53
54
    /**
55
     * @return array|null
56
     */
57
    public function getOrderBy()
58
    {
59
        if ($fields = explode(',', $this->get('sort'))) {
60
            $orderBy = [];
61
62
            foreach ($fields as $field) {
63
                if (empty($field)) continue;
64
65
                $direction = 'ASC';
66
                if ($field[0] === '-') {
67
                    $field = substr($field, 1);
68
                    $direction = 'DESC';
69
                }
70
71
                $orderBy[$field] = $direction;
72
            }
73
74
            return $orderBy;
75
        }
76
77
        return null;
78
    }
79
80
    /**
81
     * @return mixed|null
82
     */
83
    public function getQuery()
84
    {
85
        if ($query = $this->get('filter')) {
86
            if (is_string($query) && (null !== ($json = json_decode($query, true)))) {
87
                return $json;
88
            }
89
90
            return $query;
91
        }
92
93
        return null;
94
    }
95
}
96