Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.