Skip to content

Instantly share code, notes, and snippets.

@imliam
Last active February 25, 2018 21:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save imliam/e09695cafaf306e097321461f0cb72f8 to your computer and use it in GitHub Desktop.
Save imliam/e09695cafaf306e097321461f0cb72f8 to your computer and use it in GitHub Desktop.
<?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);
}
}
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);
}
}
@imliam
Copy link
Author

imliam commented Feb 24, 2018

Example usage:

$subdomain = pipe('https://blog.sebastiaanluca.com/')
    -> parse_url(PIPE_VALUE, PHP_URL_HOST)
    -> explode('.', PIPE_VALUE)
	-> reset(PIPE_VALUE);

echo $subdomain; // 'blog'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment