|
1
|
|
|
<?php |
|
2
|
|
|
namespace TRex\Collection; |
|
3
|
|
|
|
|
4
|
|
|
trait CollectionFilterTrait |
|
5
|
|
|
{ |
|
6
|
|
|
/** |
|
7
|
|
|
* @param callable|null $filter |
|
8
|
|
|
* @param int $flag (only for php version >= 5.6) |
|
9
|
|
|
* @return $this |
|
|
|
|
|
|
10
|
|
|
*/ |
|
11
|
1 |
|
public function filter(callable $filter = null, $flag = 0) |
|
12
|
|
|
{ |
|
13
|
1 |
|
if (defined('HHVM_VERSION')) { |
|
14
|
|
|
if (version_compare(HHVM_VERSION, '3.8.1', '>=')) { |
|
15
|
|
|
return new $this(array_filter((array)$this, $filter, $flag)); |
|
16
|
|
|
} |
|
17
|
|
|
} else { |
|
18
|
1 |
|
if (version_compare(phpversion(), '5.6.0', '>=')) { |
|
19
|
|
|
return new $this(array_filter((array)$this, $filter, $flag)); |
|
20
|
|
|
} |
|
21
|
|
|
} |
|
22
|
1 |
|
return new $this(array_filter((array)$this, $filter)); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Executes the callback for every value. |
|
27
|
|
|
* Returns a collection with the result of each callback call. |
|
28
|
|
|
* |
|
29
|
|
|
* @param callable $callback |
|
30
|
|
|
* @param array $args |
|
31
|
|
|
* @return $this |
|
|
|
|
|
|
32
|
|
|
*/ |
|
33
|
3 |
|
public function each(callable $callback, array $args = []) |
|
34
|
|
|
{ |
|
35
|
3 |
|
return new $this(array_map( |
|
36
|
3 |
|
function ($value) use ($callback, $args) { |
|
37
|
3 |
|
return call_user_func($callback, $value, $args) ?: $value; |
|
38
|
3 |
|
}, |
|
39
|
|
|
(array)$this |
|
40
|
3 |
|
)); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Extracts the sequence of elements. |
|
45
|
|
|
* Starts at index $startIndex and stop after $length keys. |
|
46
|
|
|
* |
|
47
|
|
|
* @param int $startIndex |
|
48
|
|
|
* @param int $length |
|
49
|
|
|
* @param bool $areKeysPreserved |
|
50
|
|
|
* @return mixed |
|
|
|
|
|
|
51
|
|
|
*/ |
|
52
|
3 |
|
public function extract($startIndex, $length = 0, $areKeysPreserved = true) |
|
53
|
|
|
{ |
|
54
|
3 |
|
$collection = (array)$this; |
|
55
|
3 |
|
$length = $length ?: count($collection); |
|
56
|
3 |
|
return new $this(array_slice($collection, $startIndex, $length, $areKeysPreserved)); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* @param int $length |
|
61
|
|
|
* @return $this |
|
|
|
|
|
|
62
|
|
|
*/ |
|
63
|
1 |
|
public function rand($length = 1) |
|
64
|
|
|
{ |
|
65
|
1 |
|
$keys = (array)array_rand((array)$this, $length); |
|
66
|
1 |
|
$result = new $this; |
|
67
|
1 |
|
foreach ($this as $key => $value) { |
|
|
|
|
|
|
68
|
1 |
|
if (in_array($key, $keys)) { |
|
69
|
1 |
|
$result[$key] = $value; |
|
70
|
1 |
|
} |
|
71
|
1 |
|
} |
|
72
|
1 |
|
return $result; |
|
73
|
|
|
} |
|
74
|
|
|
} |
This check compares the return type specified in the
@returnannotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.