Passed
Push — master ( e7b285...ac21bd )
by noitran
02:40
created

OrderBy::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Noitran\Repositories\Criteria;
4
5
use Noitran\Repositories\Contracts\Criteria\CriteriaInterface;
6
use Noitran\Repositories\Contracts\Repository\RepositoryInterface;
7
use Illuminate\Database\Eloquent\Builder;
8
use Noitran\Repositories\Exceptions\ValidationException;
9
10
class OrderBy implements CriteriaInterface
11
{
12
    /**
13
     * @var string
14
     */
15
    protected $column;
16
17
    /**
18
     * @var string
19
     */
20
    protected $direction;
21
22
    /**
23
     * Allowed characters for order by column
24
     *
25
     * @var string
26
     */
27
    protected $allowedToContain = '/^[a-z0-9\.\_\-]+$/i';
28
29
    /**
30
     * OrderBy constructor.
31
     *
32
     * @param mixed $orderBy
33
     */
34 2
    public function __construct($orderBy)
35
    {
36 2
        $this->setOrderByParameters($orderBy);
37 2
    }
38
39
    /**
40
     * @param $orderBy
41
     *
42
     * @return void
43
     */
44 1
    public function setOrderByParameters($orderBy): void
45
    {
46 1
        [$column, $direction] = explode(',', $orderBy);
47
48 1
        $this->column = $column;
49 1
        $this->direction = $direction ?? 'asc';
50
51 1
        if (! \in_array($this->direction, ['asc', 'desc'])) {
52
            $this->direction = 'asc';
53
        }
54 1
    }
55
56
    /**
57
     * @param $model
58
     * @param RepositoryInterface $repository
59
     *
60
     * @throws ValidationException
61
     *
62
     * @return Builder
63
     */
64
    public function apply($model, RepositoryInterface $repository): Builder
65
    {
66
        if (empty($this->column)) {
67
            return $model;
68
        }
69
70
        if (! preg_match($this->allowedToContain, $this->column)) {
71
            throw new ValidationException('OrderBy query parameter contains illegal characters.');
72
        }
73
74
        // @todo Implement
75
76
        return $model;
77
    }
78
}
79