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