Debian Codegraph @

vendor/ipl/orm/src/Common/SortUtil.php

raw
1 <?php
2
3 namespace ipl\Orm\Common;
4
5 use ipl\Stdlib\Str;
6
7 class SortUtil
8 {
9 /**
10 * Create the sort column(s) and direction(s) from the given sort spec
11 *
12 * @param string|array $sort
13 *
14 * @return array<int, mixed> Sort column(s) and direction(s) suitable for {@link OrderByInterface::orderBy()}
15 */
16 public static function createOrderBy(string|array $sort): array
17 {
18 $columnsAndDirections = static::explodeSortSpec($sort);
19 $orderBy = [];
20
21 foreach ($columnsAndDirections as $columnAndDirection) {
22 [$column, $direction] = static::splitColumnAndDirection($columnAndDirection);
23
24 $orderBy[] = [$column, $direction];
25 }
26
27 return $orderBy;
28 }
29
30 /**
31 * Explode the given sort spec into its sort parts
32 *
33 * @param string|array $sort
34 *
35 * @return array
36 */
37 public static function explodeSortSpec(string|array $sort): array
38 {
39 return Str::trimSplit(implode(',', (array) $sort));
40 }
41
42 /**
43 * Normalize the given sort spec to a sort string
44 *
45 * @param string|array $sort
46 *
47 * @return string
48 */
49 public static function normalizeSortSpec(string|array $sort): string
50 {
51 return implode(',', static::explodeSortSpec($sort));
52 }
53
54 /**
55 * Explode the given sort part into its sort column and direction
56 *
57 * @param string $sort
58 *
59 * @return array
60 */
61 public static function splitColumnAndDirection(string $sort): array
62 {
63 return Str::symmetricSplit($sort, ' ', 2);
64 }
65 }