ILIAS  release_9 Revision v9.13-25-g2c18ec4c24f
Sorting.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
21 namespace ILIAS\Badge;
22 
24 use Closure;
25 use ilBadge;
27 
28 class Sorting
29 {
30  private readonly string $method;
32  private readonly Closure $compare;
33  private readonly string $direction;
34  private readonly string $key;
35  private readonly string $badgeOrAssignment;
36 
37  public function __construct(string $sort_by = '')
38  {
39  $parts = explode('_', $sort_by);
40  $what = $parts[0] ?? '';
41  $direction = $parts[1] ?? '';
42 
43  $map = [
44  'title' => ['badge', 'getTitle', 'strcasecmp'],
45  'date' => ['assignment', 'getTimestamp', $this->minus()],
46  ];
47  $directions = ['asc' => 'asc', 'desc' => 'desc'];
48 
49  $key = isset($map[$what]) ? $what : key($map);
50  $direction = $directions[$direction] ?? 'asc';
51 
52  $this->badgeOrAssignment = $map[$key][0];
53  $this->method = $map[$key][1];
54  $this->compare = Closure::fromCallable($map[$key][2]);
55  $this->direction = $direction;
56  $this->key = $key . '_' . $direction;
57  }
58 
64  public function compare(array $badge_and_assignment, array $other): int
65  {
66  $method = $this->method;
67  $value = $badge_and_assignment[$this->badgeOrAssignment]->$method();
68  $other = $other[$this->badgeOrAssignment]->$method();
69 
70  return $this->reverse() * ($this->compare)($value, $other);
71  }
72 
73  public function key(): string
74  {
75  return $this->key;
76  }
77 
78  public function label(): string
79  {
80  return $this->options()[$this->key];
81  }
82 
86  public function options(): array
87  {
88  return [
89  'title_asc' => 'sort_by_title_asc',
90  'title_desc' => 'sort_by_title_desc',
91  'date_asc' => 'sort_by_date_asc',
92  'date_desc' => 'sort_by_date_desc',
93  ];
94  }
95 
96  private function reverse(): int
97  {
98  return $this->direction === 'asc' ? 1 : -1;
99  }
100 
101  private function minus(): Closure
102  {
103  return static fn(int $x, int $y): int => $x - $y;
104  }
105 }
readonly Closure $compare
Definition: Sorting.php:32
__construct(string $sort_by='')
Definition: Sorting.php:37
if($clientAssertionType !='urn:ietf:params:oauth:client-assertion-type:jwt-bearer'|| $grantType !='client_credentials') $parts
Definition: ltitoken.php:64
readonly string $key
Definition: Sorting.php:34
readonly string $direction
Definition: Sorting.php:33
readonly string $badgeOrAssignment
Definition: Sorting.php:35
readonly string $method
Definition: Sorting.php:30
compare(array $badge_and_assignment, array $other)
Definition: Sorting.php:64