Created
July 4, 2012 11:02
-
-
Save runekaagaard/3046756 to your computer and use it in GitHub Desktop.
A userland implementation of a generator function. A bit like a python context manager too.
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 | |
namespace Functional; | |
error_reporting(E_ALL|E_STRICT); | |
const BEFORE = 1; | |
const NEXT = 2; | |
const AFTER = 3; | |
const FORWARD = 4; | |
const YIELD = 5; | |
class Generator implements \Iterator { | |
private $funcs; | |
private $args; | |
private $key; | |
private $result; | |
public function __construct(array $funcs, array $args) { | |
$this->funcs = $funcs; | |
$this->args = $args; | |
} | |
public function rewind() { | |
$this->key = -1; | |
$this->result = call_user_func_array($this->funcs[BEFORE], | |
$this->args); | |
$this->next(); | |
} | |
public function valid() { | |
return $this->result[YIELD] !== false; | |
} | |
public function current() { | |
return $this->result[YIELD]; | |
} | |
public function key() { | |
return $this->key; | |
} | |
public function next() { | |
$this->result = call_user_func($this->funcs[NEXT], | |
$this->result[FORWARD]); | |
if ($this->result[YIELD] === false) { | |
call_user_func($this->funcs[AFTER], $this->result[FORWARD]); | |
} | |
++$this->key; | |
} | |
} | |
/** | |
* A generator function that lazily yields each line in a file. | |
*/ | |
function get_lines_from_file($file_name) { | |
$funcs = array( | |
BEFORE => function($file_name) { | |
return array(FORWARD => fopen($file_name, 'r')); }, | |
NEXT => function($fh) { | |
return array(FORWARD => $fh, YIELD => fgets($fh)); }, | |
AFTER => function($fh) { fclose($fh); }, | |
); | |
return new Generator($funcs, array($file_name)); | |
} | |
// Output content of this file with padded linenumbers. | |
foreach (get_lines_from_file(__FILE__) as $k => $v) { | |
echo str_pad($k, 8), $v; | |
} | |
echo "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment