| 1 |
<?php |
| 2 |
|
| 3 |
namespace Boxzilla; |
| 4 |
|
| 5 |
use Iterator; |
| 6 |
use Countable; |
| 7 |
|
| 8 |
class Collection implements Iterator, Countable { |
| 9 |
|
| 10 |
protected $elements = array(); |
| 11 |
private $position = 0; |
| 12 |
|
| 13 |
public function __construct( array $elements ) { |
| 14 |
$this->elements = $elements; |
| 15 |
$this->position = 0; |
| 16 |
} |
| 17 |
|
| 18 |
function rewind() { |
| 19 |
$this->position = 0; |
| 20 |
} |
| 21 |
|
| 22 |
function current() { |
| 23 |
return $this->elements[ $this->position ]; |
| 24 |
} |
| 25 |
|
| 26 |
function key() { |
| 27 |
return $this->position; |
| 28 |
} |
| 29 |
|
| 30 |
function next() { |
| 31 |
++$this->position; |
| 32 |
} |
| 33 |
|
| 34 |
function valid() { |
| 35 |
return isset( $this->elements[ $this->position ] ); |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* @param $callback |
| 40 |
* |
| 41 |
* @return array |
| 42 |
*/ |
| 43 |
function map($callback) { |
| 44 |
$result = array(); |
| 45 |
|
| 46 |
foreach( $this->elements as $element ) { |
| 47 |
$result[] = $callback( $element ); |
| 48 |
} |
| 49 |
|
| 50 |
return $result; |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* @param $callback |
| 55 |
* |
| 56 |
* @return null |
| 57 |
*/ |
| 58 |
function find($callback) { |
| 59 |
|
| 60 |
foreach( $this->elements as $element ) { |
| 61 |
if( $callback( $element ) ) { |
| 62 |
return $element; |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
return null; |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* (PHP 5 >= 5.1.0)<br/> |
| 71 |
* Count elements of an object |
| 72 |
* @link http://php.net/manual/en/countable.count.php |
| 73 |
* @return int The custom count as an integer. |
| 74 |
* </p> |
| 75 |
* <p> |
| 76 |
* The return value is cast to an integer. |
| 77 |
*/ |
| 78 |
public function count() { |
| 79 |
return count( $this->elements ); |
| 80 |
} |
| 81 |
} |