Last active
February 25, 2018 21:30
-
-
Save imliam/e09695cafaf306e097321461f0cb72f8 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 | |
define('PIPE_VALUE', '__pipe-' . uniqid()); | |
class Pipe implements ArrayAccess, Iterator, Serializable | |
{ | |
public $value; | |
private $position = 0; | |
public function __construct($value) | |
{ | |
$this->value = $value; | |
} | |
public function __call($method, $args) | |
{ | |
if (function_exists($method)) { | |
foreach ($args as $key => $arg) { | |
if ($arg === PIPE_VALUE) { | |
$args[$key] = $this->value; | |
} | |
} | |
$this->value = $method(...$args); | |
return $this; | |
} | |
trigger_error("Function '$method' doesn't exist", E_USER_ERROR); | |
} | |
public function __get($name) | |
{ | |
return $this->value; | |
} | |
public function __toString() | |
{ | |
return $this->value; | |
} | |
public function pipe($value) | |
{ | |
if (is_callable($value) and $value instanceof \Closure) { | |
$this->value = $value($this->value); | |
} | |
return $this; | |
} | |
public function offsetSet($offset, $value) { | |
if (is_null($offset)) { | |
$this->value[] = $value; | |
} else { | |
$this->value[$offset] = $value; | |
} | |
} | |
public function offsetExists($offset) { | |
return isset($this->value[$offset]); | |
} | |
public function offsetUnset($offset) { | |
unset($this->value[$offset]); | |
} | |
public function offsetGet($offset) { | |
return isset($this->value[$offset]) ? $this->value[$offset] : null; | |
} | |
public function rewind() { | |
$this->position = 0; | |
} | |
public function current() { | |
return $this->value[$this->position]; | |
} | |
public function key() { | |
return $this->position; | |
} | |
public function next() { | |
++$this->position; | |
} | |
public function valid() { | |
return isset($this->value[$this->position]); | |
} | |
public function serialize() { | |
return serialize($this->value); | |
} | |
public function unserialize($value) { | |
$this->value = unserialize($value); | |
} | |
} |
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
if (! function_exists('pipe')) { | |
/** | |
* Run functions consecutively by piping through the result of one | |
* into the next. | |
* | |
* @param mixed $value A value | |
* | |
* @return object | |
*/ | |
function pipe($value) | |
{ | |
return new Pipe($value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: