Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
Order
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
6
100.00% covered (success)
100.00%
1 / 1
 parse
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
6
1<?php
2declare(strict_types=1);
3/**
4 * Pop PHP Framework (https://www.popphp.org/)
5 *
6 * @link       https://github.com/popphp/popphp-framework
7 * @author     Nick Sagona, III <nick@popphp.org>
8 * @copyright  Copyright (c) 2009-2026 Nick Sagona, III
9 * @license    https://www.popphp.org/license     New BSD License
10 */
11
12/**
13 * @namespace
14 */
15namespace Pop\Db\Sql\Parser;
16
17/**
18 * Order parser class
19 *
20 * @category   Pop
21 * @package    Pop\Db
22 * @author     Nick Sagona, III <nick@popphp.org>
23 * @copyright  Copyright (c) 2009-2026 Nick Sagona, III
24 * @license    https://www.popphp.org/license     New BSD License
25 * @version    7.0.0
26 */
27class Order
28{
29
30    /**
31     * Get the order by values
32     *
33     * A string carrying no direction falls back to ASC, which is SQL's own default for a bare
34     * column. A leading '-' is the shorthand for descending, the same convention that
35     * Model\AbstractDataModel::getOrderBy() applies to its sort parameter.
36     *
37     * @param  string $orderBy
38     * @return array
39     */
40    public static function parse(string $orderBy): array
41    {
42        $by    = null;
43        $order = null;
44
45        if (stripos($orderBy, 'ASC') !== false) {
46            $order = 'ASC';
47            $by    = trim(str_replace('ASC', '', $orderBy));
48        } else if (stripos($orderBy, 'DESC') !== false) {
49            $order = 'DESC';
50            $by    = trim(str_replace('DESC', '', $orderBy));
51        } else if (stripos($orderBy, 'RAND()') !== false) {
52            $order = 'RAND()';
53            $by    = trim(str_replace('RAND()', '', $orderBy));
54        } else if (str_starts_with(trim($orderBy), '-')) {
55            $order = 'DESC';
56            $by    = trim(substr(trim($orderBy), 1));
57        } else {
58            $order = 'ASC';
59            $by    = trim($orderBy);
60        }
61
62        if (str_contains($by, ',')) {
63            $by = array_map('trim', explode(',', $by));
64        }
65
66        return ['by' => $by, 'order' => $order];
67    }
68
69}