-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathGroups.php
82 lines (60 loc) · 1.74 KB
/
Groups.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace AC;
final class Groups {
private $groups;
public const SORT_PRIORITY = 1;
public const SORT_SLUG = 2;
public const SORT_LABEL = 3;
public function __construct( array $groups = [] ) {
$this->groups = $groups;
}
public function get_all( $sort_by = null ): array {
switch ( $sort_by ) {
case self::SORT_LABEL :
return $this->sort_groups_by_string( $this->groups, 'label' );
case self::SORT_SLUG :
return $this->sort_groups_by_string( $this->groups, 'slug' );
default :
return $this->sort_groups_by_priority( $this->groups );
}
}
private function sort_groups_by_priority( array $groups ): array {
$aggregated = $sorted = [];
foreach ( $groups as $group ) {
$aggregated[ $group['priority'] ][] = $group;
}
ksort( $aggregated, SORT_NUMERIC );
foreach ( $aggregated as $_groups ) {
$sorted = array_merge( $sorted, $this->sort_groups_by_string( $_groups, 'label' ) );
}
return $sorted;
}
private function sort_groups_by_string( array $groups, string $key ): array {
$sorted = [];
foreach ( $groups as $k => $group ) {
$sorted[ $k ] = $group[ $key ];
}
natcasesort( $sorted );
foreach ( array_keys( $sorted ) as $k ) {
$sorted[ $k ] = $groups[ $k ];
}
return $sorted;
}
public function get( string $slug ): ?array {
return $this->groups[ $slug ] ?? null;
}
public function register_group( string $slug, string $label, int $priority = 10 ): bool {
return $this->add( $slug, $label, $priority );
}
public function add( string $slug, string $label, int $priority = 10 ): bool {
if ( isset( $this->groups[ $slug ] ) ) {
return false;
}
$this->groups[ $slug ] = [
'slug' => $slug,
'label' => $label,
'priority' => $priority,
];
return true;
}
}