]> BookStack Code Mirror - bookstack/blob - app/Sorting/SortSetOperation.php
Sorting: Covered sort set management with tests
[bookstack] / app / Sorting / SortSetOperation.php
1 <?php
2
3 namespace BookStack\Sorting;
4
5 use Closure;
6 use Illuminate\Support\Str;
7
8 enum SortSetOperation: string
9 {
10     case NameAsc = 'name_asc';
11     case NameDesc = 'name_desc';
12     case NameNumericAsc = 'name_numeric_asc';
13     case CreatedDateAsc = 'created_date_asc';
14     case CreatedDateDesc = 'created_date_desc';
15     case UpdateDateAsc = 'updated_date_asc';
16     case UpdateDateDesc = 'updated_date_desc';
17     case ChaptersFirst = 'chapters_first';
18     case ChaptersLast = 'chapters_last';
19
20     /**
21      * Provide a translated label string for this option.
22      */
23     public function getLabel(): string
24     {
25         $key = $this->value;
26         $label = '';
27         if (str_ends_with($key, '_asc')) {
28             $key = substr($key, 0, -4);
29             $label = trans('settings.sort_set_op_asc');
30         } elseif (str_ends_with($key, '_desc')) {
31             $key = substr($key, 0, -5);
32             $label = trans('settings.sort_set_op_desc');
33         }
34
35         $label = trans('settings.sort_set_op_' . $key) . ' ' . $label;
36         return trim($label);
37     }
38
39     public function getSortFunction(): callable
40     {
41         $camelValue = Str::camel($this->value);
42         return SortSetOperationComparisons::$camelValue(...);
43     }
44
45     /**
46      * @return SortSetOperation[]
47      */
48     public static function allExcluding(array $operations): array
49     {
50         $all = SortSetOperation::cases();
51         $filtered = array_filter($all, function (SortSetOperation $operation) use ($operations) {
52             return !in_array($operation, $operations);
53         });
54         return array_values($filtered);
55     }
56
57     /**
58      * Create a set of operations from a string sequence representation.
59      * (values seperated by commas).
60      * @return SortSetOperation[]
61      */
62     public static function fromSequence(string $sequence): array
63     {
64         $strOptions = explode(',', $sequence);
65         $options = array_map(fn ($val) => SortSetOperation::tryFrom($val), $strOptions);
66         return array_filter($options);
67     }
68 }