Passed
Pull Request — master (#7)
by Chito
02:51
created

LampagerPaginator::orderBy()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 9
rs 10
ccs 5
cts 5
cp 1
crap 3
1
<?php
2
3
App::uses('Model', 'Model');
4
App::uses('LampagerTransformer', 'Lampager.Model');
5
6
use Lampager\Paginator as BasePaginator;
7
use Lampager\Query\Order;
8
9
class LampagerPaginator extends BasePaginator
10
{
11
    /** @var Model */
12
    public $builder;
13
14
    /** @var array */
15
    public $query;
16
17
    /** @var LampagerTransformer */
18
    public $transformer;
19
20
    public function __construct(Model $builder, array $query)
21
    {
22 36
        $this->builder = $builder;
23
        $this->fromArray($query);
24 36
        $this->transformer = new LampagerTransformer($this);
25 36
    }
26 36
27 36
    /**
28
     * @param  Model             $builder Model.
29
     * @param  array             $query   Query.
30
     * @return static
31
     */
32
    public static function create(Model $builder, array $query)
33
    {
34 36
        return new static($builder, $query);
35
    }
36 36
37
    /**
38
     * Add cursor parameter name for ORDER BY statement.
39
     *
40
     * @param  string|int $column
41
     * @param  string     $order
42
     * @return $this
43
     */
44
    public function orderBy($column, $order = Order::ASC)
45
    {
46 36
        if (is_int($column)) {
47
            list($column, $order) = explode(' ', $order) + [1 => 'ASC'];
48 36
        }
49 2
        if (strpos($column, '.') === false) {
50
            $column = "{$this->builder->alias}.{$column}";
51 36
        }
52 2
        return parent::orderBy($column, strtolower($order));
53
    }
54 36
55
    /**
56
     * Define options from an associative array.
57
     *
58
     * @param  (bool|int|string[])[] $options
59
     * @return $this
60
     */
61
    public function fromArray(array $options)
62
    {
63 36
        // Not supported in CakePHP 2 version
64
        unset($options['orders']);
65
66 36
        // Merge with existing query
67
        $this->query = array_replace_recursive($this->query ?: [], $options);
68
69 36
        if (isset($options['order'])) {
70
            foreach ($options['order'] as $column => $order) {
71 36
                $this->orderBy($column, $order);
72 36
            }
73 36
        }
74
75
        return parent::fromArray($options);
76
    }
77
}
78