OrderBy   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Test Coverage

Coverage 81.25%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 15
c 1
b 0
f 0
dl 0
loc 65
ccs 13
cts 16
cp 0.8125
rs 10

3 Methods

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