Completed
Push — master ( 007b29...22a5db )
by smiley
02:01
created

Enumerable::__each()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Trait Enumerable
4
 *
5
 * @filesource   Enumerable.php
6
 * @created      28.06.2017
7
 * @package      chillerlan\Traits
8
 * @author       Smiley <[email protected]>
9
 * @copyright    2017 Smiley
10
 * @license      MIT
11
 */
12
13
namespace chillerlan\Traits;
14
15
/**
16
 * @link http://api.prototypejs.org/language/Enumerable/
17
 */
18
trait Enumerable{
19
20
	/**
21
	 * @var array
22
	 */
23
	protected $array = [];
24
25
	/**
26
	 * @var int
27
	 */
28
	protected $offset = 0;
29
30
	/**
31
	 * @link http://api.prototypejs.org/language/Enumerable/prototype/toArray/
32
	 *
33
	 * @return array
34
	 *
35
	 * @codeCoverageIgnore
36
	 */
37
	public function __toArray():array {
38
		return $this->array;
39
	}
40
41
	/**
42
	 * @link http://api.prototypejs.org/language/Enumerable/prototype/each/
43
	 *
44
	 * @param callable $callback
45
	 *
46
	 * @return $this
47
	 */
48
	public function __each($callback){
49
		$this->__map($callback);
50
51
		return $this;
52
	}
53
54
	/**
55
	 * @link http://api.prototypejs.org/language/Enumerable/prototype/collect/
56
	 * @link http://api.prototypejs.org/language/Enumerable/prototype/map/
57
	 *
58
	 * @param callable $callback
59
	 *
60
	 * @return array
61
	 * @throws \chillerlan\Traits\TraitException
62
	 */
63
	public function __map($callback):array {
64
65
		if(!is_callable($callback)){
66
			throw new TraitException('invalid callback');
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return array. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
67
		}
68
69
		$return = [];
70
71
		foreach($this->array as $index => $element){
72
			$return[$index] = call_user_func_array($callback, [$element, $index]);
73
		}
74
75
		return $return;
76
	}
77
78
	/**
79
	 * @link http://api.prototypejs.org/language/Array/prototype/reverse/
80
	 *
81
	 * @return $this
82
	 */
83
	public function __reverse(){
84
		$this->array = array_reverse($this->array);
85
		$this->offset = 0;
86
87
		return $this;
88
	}
89
90
}
91