Created
June 13, 2016 18:50
-
-
Save edhaase/e5731791241e091d79b3418977589ab9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
/** | |
* TempStreamIterator.php | |
* | |
* Caches an iterable into a temporary stream, memory or file backed. | |
* Result is rewindable. | |
* | |
*/ | |
class TempStreamIterator implements \Iterator | |
{ | |
protected $fp; | |
protected $key, $val; | |
public function __construct($t, $memory = 10) { | |
$memory = $memory * 1024 * 1024; | |
$this->fp = fopen("php://temp/maxmemory:$memory", "r+"); | |
foreach($t as $k => $v) { | |
$o = serialize([$k, $v]); | |
fputs($this->fp, "$o\n"); | |
} | |
} | |
public function __destruct() { | |
fclose($this->fp); | |
} | |
public function current() { | |
return $this->val; | |
} | |
public function key() { | |
return $this->key; | |
} | |
public function next() { | |
list($this->key, $this->val) = unserialize(trim(fgets($this->fp))); | |
} | |
public function rewind() { | |
rewind($this->fp); | |
$this->next(); | |
} | |
public function valid() { | |
return ($this->key !== null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment