|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Yiisoft\Data\Reader; |
| 6 | + |
| 7 | +use function implode; |
| 8 | +use function preg_split; |
| 9 | +use function substr; |
| 10 | +use function trim; |
| 11 | + |
| 12 | +/** |
| 13 | + * @psalm-import-type TOrder from Sort |
| 14 | + */ |
| 15 | +final class OrderHelper |
| 16 | +{ |
| 17 | + /** |
| 18 | + * Create fields order array from an order string. |
| 19 | + * |
| 20 | + * The string consists of comma-separated field names. |
| 21 | + * If the name is prefixed with `-`, field order is descending. |
| 22 | + * Otherwise, the order is ascending. |
| 23 | + * |
| 24 | + * @param string $orderString Logical fields order as comma-separated string. |
| 25 | + * |
| 26 | + * @return array Logical fields order as array. |
| 27 | + * |
| 28 | + * @psalm-return TOrder |
| 29 | + */ |
| 30 | + public static function stringToArray(string $orderString): array |
| 31 | + { |
| 32 | + $order = []; |
| 33 | + $parts = preg_split('/\s*,\s*/', trim($orderString), -1, PREG_SPLIT_NO_EMPTY); |
| 34 | + |
| 35 | + foreach ($parts as $part) { |
| 36 | + if (str_starts_with($part, '-')) { |
| 37 | + $order[substr($part, 1)] = 'desc'; |
| 38 | + } else { |
| 39 | + $order[$part] = 'asc'; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return $order; |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Create an order string based on logical fields order array. |
| 48 | + * |
| 49 | + * The string consists of comma-separated field names. |
| 50 | + * If the name is prefixed with `-`, field order is descending. |
| 51 | + * Otherwise, the order is ascending. |
| 52 | + * |
| 53 | + * @param array $order Logical fields order as array. |
| 54 | + * |
| 55 | + * @return string An order string. |
| 56 | + */ |
| 57 | + public static function arrayToString(array $order): string |
| 58 | + { |
| 59 | + $parts = []; |
| 60 | + foreach ($order as $field => $direction) { |
| 61 | + $parts[] = ($direction === 'desc' ? '-' : '') . $field; |
| 62 | + } |
| 63 | + |
| 64 | + return implode(',', $parts); |
| 65 | + } |
| 66 | +} |
0 commit comments