Last active
January 11, 2018 17:13
-
-
Save imliam/680b8efdb3793bb365a8215de3ba4957 to your computer and use it in GitHub Desktop.
Safely attempt to call methods on something you believe to be an object.
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 | |
if (! function_exists('safe')) { | |
/** | |
* Safely attempt to call methods and properties on something you believe | |
* to be an object but may be null, using a hidden anonymous class for | |
* syntactical sugar to keep your application logic looking simple | |
* and clean. | |
* | |
* @param object $value The suspected object. | |
* @param string $fallback The fallback to return when used as a string. | |
* @param closure $fallback A function to be executed once used as a string. | |
* | |
* @return object | |
*/ | |
function safe($value, $fallback = '') | |
{ | |
if (is_null($value)) { | |
return new class($fallback) { | |
private $fallbackMethod = []; | |
public function __construct($fallback) | |
{ | |
if (is_callable($fallback)) { | |
$this->fallbackMethod = [$fallback]; | |
} else { | |
$this->fallback = $fallback; | |
} | |
} | |
public function __toString() | |
{ | |
if (count($this->fallbackMethod)) { | |
return $this->fallbackMethod[0](); | |
} | |
return $this->fallback; | |
} | |
public function __get($name) | |
{ | |
return $this; | |
} | |
public function __set($name, $value) | |
{ | |
$this->{$name} = $value; | |
return $this; | |
} | |
public function __isset($name) | |
{ | |
return false; | |
} | |
public function __unset($name) | |
{ | |
unset($this->{$name}); | |
} | |
public function __call($name, $arguments) | |
{ | |
return $this; | |
} | |
public static function __callStatic($name, $arguments) | |
{ | |
return self; | |
} | |
public function __invoke($data) | |
{ | |
return $this; | |
} | |
}; | |
} | |
return $value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage (with Carbon):