]> BookStack Code Mirror - bookstack/blob - app/Sorting/SortSetOperationComparisons.php
Sorting: Fixes during testing of sort rules
[bookstack] / app / Sorting / SortSetOperationComparisons.php
1 <?php
2
3 namespace BookStack\Sorting;
4
5 use BookStack\Entities\Models\Chapter;
6 use BookStack\Entities\Models\Entity;
7
8 /**
9  * Sort comparison function for each of the possible SortSetOperation values.
10  * Method names should be camelCase names for the SortSetOperation enum value.
11  */
12 class SortSetOperationComparisons
13 {
14     public static function nameAsc(Entity $a, Entity $b): int
15     {
16         return $a->name <=> $b->name;
17     }
18
19     public static function nameDesc(Entity $a, Entity $b): int
20     {
21         return $b->name <=> $a->name;
22     }
23
24     public static function nameNumericAsc(Entity $a, Entity $b): int
25     {
26         $numRegex = '/^\d+(\.\d+)?/';
27         $aMatches = [];
28         $bMatches = [];
29         preg_match($numRegex, $a->name, $aMatches);
30         preg_match($numRegex, $b->name, $bMatches);
31         $aVal = floatval(($aMatches[0] ?? 0));
32         $bVal = floatval(($bMatches[0] ?? 0));
33
34         return $aVal <=> $bVal;
35     }
36
37     public static function nameNumericDesc(Entity $a, Entity $b): int
38     {
39         return -(static::nameNumericAsc($a, $b));
40     }
41
42     public static function createdDateAsc(Entity $a, Entity $b): int
43     {
44         return $a->created_at->unix() <=> $b->created_at->unix();
45     }
46
47     public static function createdDateDesc(Entity $a, Entity $b): int
48     {
49         return $b->created_at->unix() <=> $a->created_at->unix();
50     }
51
52     public static function updatedDateAsc(Entity $a, Entity $b): int
53     {
54         return $a->updated_at->unix() <=> $b->updated_at->unix();
55     }
56
57     public static function updatedDateDesc(Entity $a, Entity $b): int
58     {
59         return $b->updated_at->unix() <=> $a->updated_at->unix();
60     }
61
62     public static function chaptersFirst(Entity $a, Entity $b): int
63     {
64         return ($b instanceof Chapter ? 1 : 0) - (($a instanceof Chapter) ? 1 : 0);
65     }
66
67     public static function chaptersLast(Entity $a, Entity $b): int
68     {
69         return ($a instanceof Chapter ? 1 : 0) - (($b instanceof Chapter) ? 1 : 0);
70     }
71 }