summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/sql/src/OrderBy.php
blob: 0721ad5a9d6254e5fa72ea62b54dcc0ac4def818 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php

namespace ipl\Sql;

/**
 * Trait for the ORDER BY part of a query
 */
trait OrderBy
{
    /** @var array ORDER BY part of the query */
    protected $orderBy;

    public function hasOrderBy()
    {
        return $this->orderBy !== null;
    }

    public function getOrderBy()
    {
        return $this->orderBy;
    }

    public function orderBy($orderBy, $direction = null)
    {
        if (! is_array($orderBy)) {
            $orderBy = [$orderBy];
        }

        foreach ($orderBy as $column => $dir) {
            if (is_int($column)) {
                $column = $dir;
                $dir = $direction;
            }

            if (is_array($column) && count($column) === 2) {
                list($column, $dir) = $column;
            }

            if ($dir === SORT_ASC) {
                $dir = 'ASC';
            } elseif ($dir === SORT_DESC) {
                $dir = 'DESC';
            }

            $this->orderBy[] = [$column, $dir];
        }

        return $this;
    }

    public function resetOrderBy()
    {
        $this->orderBy = null;

        return $this;
    }

    /**
     * Clone the properties provided by this trait
     *
     * Shall be called by using classes in their __clone()
     */
    protected function cloneOrderBy()
    {
        if ($this->orderBy !== null) {
            foreach ($this->orderBy as &$orderBy) {
                if ($orderBy[0] instanceof ExpressionInterface || $orderBy[0] instanceof Select) {
                    $orderBy[0] = clone $orderBy[0];
                }
            }
            unset($orderBy);
        }
    }
}