Skip to content

Instantly share code, notes, and snippets.

@edhaase
Created June 13, 2016 18:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edhaase/e5731791241e091d79b3418977589ab9 to your computer and use it in GitHub Desktop.
Save edhaase/e5731791241e091d79b3418977589ab9 to your computer and use it in GitHub Desktop.
<?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