-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathArrayOrder.php
More file actions
103 lines (84 loc) · 2.4 KB
/
ArrayOrder.php
File metadata and controls
103 lines (84 loc) · 2.4 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
namespace DrupalCodeBuilder\Utility;
/**
* Provides helpers for setting the order of array items.
*
* @ingroup utility
*/
class ArrayOrder {
/**
* Moves an item to the front of an array, specifying by value.
*
* @param array &$array
* The array to change.
* @param mixed $value
* The value to move.
*
* @throws \InvalidArgumentException
* Throws an exception if the value is not in the array.
*/
public static function moveValueToFront(array &$array, mixed $value): void {
$key = array_find($array, $value);
if ($key === FALSE) {
throw new \InvalidArgumentException('Value not found in array.');
}
static::moveKeyToFront($array, $key);
}
/**
* Moves an item to the front of an array, specifying by key.
*
* @param array &$array
* The array to change.
* @param mixed $key
* The key to move.
*
* @throws \InvalidArgumentException
* Throws an exception if the key is not in the array.
*/
public static function moveKeyToFront(array &$array, mixed $key): void {
if (!isset($array[$key])) {
throw new \InvalidArgumentException('Key not found in array.');
}
$value = $array[$key];
unset($array[$key]);
InsertArray::insertBefore($array, array_key_first($array), [$key => $value]);
}
/**
* Moves an item to the end of an array, specifying by value.
*
* @param array &$array
* The array to change.
* @param mixed $value
* The value to move.
*
* @throws \InvalidArgumentException
* Throws an exception if the value is not in the array.
*/
public static function moveValueToEnd(array &$array, mixed $value): void {
$key = array_find($array, $value);
if ($key === FALSE) {
throw new \InvalidArgumentException('Value not found in array.');
}
unset($array[$key]);
$array[$key] = $value;
}
/**
* Moves an item to the end of an array, specifying by key.
*
* @param array &$array
* The array to change.
* @param mixed $key
* The key to move.
*
* @throws \InvalidArgumentException
* Throws an exception if the key is not in the array.
*/
public static function moveKeyToEnd(array &$array, mixed $key): void {
if (!isset($array[$key])) {
throw new \InvalidArgumentException('Key not found in array.');
}
$value = $array[$key];
unset($array[$key]);
$array[$key] = $value;
}
}