1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Trait Enumerable |
4
|
|
|
* |
5
|
|
|
* @filesource Enumerable.php |
6
|
|
|
* @created 30.05.2017 |
7
|
|
|
* @package chillerlan\Database\Traits |
8
|
|
|
* @author Smiley <[email protected]> |
9
|
|
|
* @copyright 2017 Smiley |
10
|
|
|
* @license MIT |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
namespace chillerlan\Database\Traits; |
14
|
|
|
|
15
|
|
|
use chillerlan\Database\DBException; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @link http://api.prototypejs.org/language/Enumerable/ |
19
|
|
|
*/ |
20
|
|
|
trait Enumerable{ |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var array |
24
|
|
|
*/ |
25
|
|
|
protected $array = []; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var int |
29
|
|
|
*/ |
30
|
|
|
protected $offset = 0; |
31
|
|
|
|
32
|
|
|
/************* |
33
|
|
|
* prototype * |
34
|
|
|
*************/ |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @link http://api.prototypejs.org/language/Enumerable/prototype/toArray/ |
38
|
|
|
* |
39
|
|
|
* @return array |
40
|
|
|
*/ |
41
|
|
|
public function __toArray():array { |
42
|
|
|
return $this->array; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @link http://api.prototypejs.org/language/Enumerable/prototype/each/ |
47
|
|
|
* |
48
|
|
|
* @param callable $callback |
49
|
|
|
* |
50
|
|
|
* @return $this |
51
|
|
|
*/ |
52
|
|
|
public function __each($callback){ |
53
|
|
|
$this->__map($callback); |
54
|
|
|
|
55
|
|
|
return $this; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @link http://api.prototypejs.org/language/Enumerable/prototype/collect/ |
60
|
|
|
* @link http://api.prototypejs.org/language/Enumerable/prototype/map/ |
61
|
|
|
* |
62
|
|
|
* @param callable $callback |
63
|
|
|
* |
64
|
|
|
* @return array |
65
|
|
|
* @throws \Exception |
66
|
|
|
*/ |
67
|
|
|
public function __map($callback):array { |
68
|
|
|
|
69
|
|
|
if(!is_callable($callback)){ |
70
|
|
|
throw new DBException('invalid callback'); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
$return = []; |
74
|
|
|
|
75
|
|
|
foreach($this->array as $index => $element){ |
76
|
|
|
$return[$index] = call_user_func_array($callback, [$element, $index]); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return $return; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @link http://api.prototypejs.org/language/Enumerable/prototype/pluck/ |
84
|
|
|
* |
85
|
|
|
* @param string $property |
86
|
|
|
* |
87
|
|
|
* @return array |
88
|
|
|
*/ |
89
|
|
|
public function __pluck(string $property):array { |
90
|
|
|
return array_column($this->array, $property); |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
/** |
94
|
|
|
* @link http://api.prototypejs.org/language/Array/prototype/reverse/ |
95
|
|
|
* |
96
|
|
|
* @return $this |
97
|
|
|
*/ |
98
|
|
|
public function __reverse(){ |
99
|
|
|
$this->array = array_reverse($this->array); |
100
|
|
|
$this->offset = 0; |
101
|
|
|
|
102
|
|
|
return $this; |
103
|
|
|
} |
104
|
|
|
|
105
|
|
|
|
106
|
|
|
} |
107
|
|
|
|