1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Horat1us\Yii\Helpers; |
4
|
|
|
|
5
|
|
|
use yii\helpers\ArrayHelper as YiiArrayHelper; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Class ArrayHelper |
9
|
|
|
* @package Horat1us\Yii\Helpers |
10
|
|
|
*/ |
11
|
|
|
class ArrayHelper extends YiiArrayHelper |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @param $items |
15
|
|
|
* @param array $perms |
16
|
|
|
* @return array |
17
|
|
|
*/ |
18
|
1 |
|
public static function permute($items, $perms = []) |
19
|
|
|
{ |
20
|
1 |
|
if (empty($items)) { |
21
|
1 |
|
$return = [$perms]; |
22
|
|
|
} else { |
23
|
1 |
|
$return = []; |
24
|
1 |
|
for ($i = count($items) - 1; $i >= 0; --$i) { |
25
|
1 |
|
$newItems = $items; |
26
|
1 |
|
$newPerms = $perms; |
27
|
1 |
|
list($foo) = array_splice($newItems, $i, 1); |
28
|
1 |
|
array_unshift($newPerms, $foo); |
29
|
1 |
|
$return = array_merge($return, static::permute($newItems, $newPerms)); |
30
|
|
|
} |
31
|
|
|
} |
32
|
1 |
|
return $return; |
33
|
|
|
} |
34
|
|
|
|
35
|
1 |
|
public static function every(array $items, callable $condition): bool |
36
|
|
|
{ |
37
|
|
|
// we need reflection to be able pass native `is_int` and `is_string` as condition |
38
|
1 |
|
$reflection = new \ReflectionFunction($condition); |
39
|
1 |
|
$hasTwoArguments = $reflection->getNumberOfParameters() === 2; |
40
|
1 |
|
foreach ($items as $key => $item) { |
41
|
1 |
|
$arguments = [$item]; |
42
|
1 |
|
$hasTwoArguments && $arguments[] = $key; |
43
|
1 |
|
if (!call_user_func($condition, ...$arguments)) { |
44
|
1 |
|
return false; |
45
|
|
|
} |
46
|
|
|
} |
47
|
1 |
|
return true; |
48
|
|
|
} |
49
|
|
|
|
50
|
1 |
|
public static function some(array $items, callable $condition): bool |
51
|
|
|
{ |
52
|
|
|
// we need reflection to be able pass native `is_int` and `is_string` as condition |
53
|
1 |
|
$reflection = new \ReflectionFunction($condition); |
54
|
1 |
|
$hasTwoArguments = $reflection->getNumberOfParameters() === 2; |
55
|
1 |
|
foreach ($items as $key => $item) { |
56
|
1 |
|
$arguments = [$item]; |
57
|
1 |
|
$hasTwoArguments && $arguments[] = $key; |
58
|
1 |
|
if (call_user_func($condition, ...$arguments)) { |
59
|
1 |
|
return true; |
60
|
|
|
} |
61
|
|
|
} |
62
|
1 |
|
return false; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|