Created
August 3, 2017 06:38
-
-
Save Glutexo/08ca91d5c93afb5777e03e6f2bfa27e2 to your computer and use it in GitHub Desktop.
PHP class that allows method chaining even if some part of the chain returns null
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 | |
class Maybe | |
{ | |
/** | |
* @var mixed|null | |
*/ | |
public $value; | |
/** | |
* @param mixed|null $value | |
*/ | |
public function __construct($value = null) | |
{ | |
$this->value = $value; | |
} | |
/** | |
* @param string $method | |
* @param array $args | |
* @return self|null | |
*/ | |
public function __call($method, array $args) | |
{ | |
if (is_null($this->value)) { | |
$result = null; | |
} else { | |
$result = call_user_func_array([$this->value, $method], $args); | |
} | |
$instance = new self($result); | |
return $instance; | |
} | |
/** | |
* @param string $name | |
* @return mixed|null | |
*/ | |
public function __get($name) { | |
$value = is_null($this->value) ? null : $this->value->$name; | |
return $value; | |
} | |
/** | |
* @param string $name | |
* @param mixed|null $value | |
*/ | |
public function __set($name, $value) { | |
if ( ! is_null($this->value)) { | |
$this->value->$name = $value; | |
} | |
} | |
/** | |
* @param string $name | |
* @return bool | |
*/ | |
public function __isset($name) { | |
$isset = is_null($this->value) ? false : isset($this->value->$name); | |
return $isset; | |
} | |
/** | |
* @param string $name | |
*/ | |
public function __unset($name) { | |
if ( ! is_null($this->value)) { | |
unset($this->value->name); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment