summaryrefslogtreecommitdiff
path: root/src/Support/SortDirections.php
blob: def0f53cec2093ed2708d2dbada5696d094f60a1 (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
<?php

declare(strict_types=1);

namespace Lightscale\LaralightTables\Support;

use SortDirection;

/**
 * Converts between SortDirection and the 'asc'/'desc' strings used by the
 * query builder and the Livewire wire/URL boundary.
 *
 * SortDirection is a pure enum, so it carries no value of its own.
 */
final class SortDirections
{
    public const ASC = 'asc';

    public const DESC = 'desc';

    /**
     * @return 'asc'|'desc'
     */
    public static function value(SortDirection $dir): string
    {
        return match ($dir) {
            SortDirection::Ascending => self::ASC,
            SortDirection::Descending => self::DESC,
        };
    }

    public static function tryFrom(SortDirection|string|null $value): ?SortDirection
    {
        if ($value instanceof SortDirection) {
            return $value;
        }

        return match ($value === null ? null : strtolower($value)) {
            self::ASC => SortDirection::Ascending,
            self::DESC => SortDirection::Descending,
            default => null,
        };
    }
}