]> BookStack Code Mirror - bookstack/blob - app/Sorting/SortSetOperationComparisons.php
Sorting: Added book autosort logic
[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  * TODO - Test to cover each SortSetOperation enum value is covered.
12  */
13 class SortSetOperationComparisons
14 {
15     public static function nameAsc(Entity $a, Entity $b): int
16     {
17         return $a->name <=> $b->name;
18     }
19
20     public static function nameDesc(Entity $a, Entity $b): int
21     {
22         return $b->name <=> $a->name;
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, $aMatches);
31         preg_match($numRegex, $b, $bMatches);
32         return ($aMatches[0] ?? 0) <=> ($bMatches[0] ?? 0);
33     }
34
35     public static function nameNumericDesc(Entity $a, Entity $b): int
36     {
37         return -(static::nameNumericAsc($a, $b));
38     }
39
40     public static function createdDateAsc(Entity $a, Entity $b): int
41     {
42         return $a->created_at->unix() <=> $b->created_at->unix();
43     }
44
45     public static function createdDateDesc(Entity $a, Entity $b): int
46     {
47         return $b->created_at->unix() <=> $a->created_at->unix();
48     }
49
50     public static function updatedDateAsc(Entity $a, Entity $b): int
51     {
52         return $a->updated_at->unix() <=> $b->updated_at->unix();
53     }
54
55     public static function updatedDateDesc(Entity $a, Entity $b): int
56     {
57         return $b->updated_at->unix() <=> $a->updated_at->unix();
58     }
59
60     public static function chaptersFirst(Entity $a, Entity $b): int
61     {
62         return ($b instanceof Chapter ? 1 : 0) - (($a instanceof Chapter) ? 1 : 0);
63     }
64
65     public static function chaptersLast(Entity $a, Entity $b): int
66     {
67         return ($a instanceof Chapter ? 1 : 0) - (($b instanceof Chapter) ? 1 : 0);
68     }
69 }