Created
April 22, 2015 12:39
-
-
Save gooh/4b8f9eec685f0641834d to your computer and use it in GitHub Desktop.
Universal Data Container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class DataCollection implements \IteratorAggregate | |
{ | |
private $data; | |
public function __construct($data) | |
{ | |
$this->data = $data; | |
} | |
public function getIterator() | |
{ | |
if (is_callable($this->data)) { | |
return new static( | |
call_user_func_array($this->data, func_get_args()) | |
); | |
} | |
if (is_array($this->data)) { | |
return new \ArrayIterator($this->data); | |
} | |
if ($this->data instanceof \IteratorAggregate) { | |
return $this->data->getIterator(); | |
} | |
if ($this->data instanceof \Iterator) { | |
return $this->data; | |
} | |
} | |
} | |
$array = new DataCollection([1,2,3,4,5]); | |
$callback = new DataCollection(function() { return [1,2,3,4,5]; }); | |
$generator = new DataCollection(function() { for($i = 1; $i < 6; $i++) yield $i; }); | |
print_r(iterator_to_array($array)); | |
print_r(iterator_to_array($callback)); | |
print_r(iterator_to_array($generator)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment