Skip to content

Instantly share code, notes, and snippets.

@imliam
Last active January 11, 2018 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imliam/680b8efdb3793bb365a8215de3ba4957 to your computer and use it in GitHub Desktop.
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.
<?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;
}
}
@imliam
Copy link
Author

imliam commented Jan 10, 2018

Example usage (with Carbon):

    use Carbon\Carbon;

    $date = Carbon::now(); // A new Carbon object for the current datetime.
    safe($date, 'Never')->diffForHumans(); // Returns "1 second ago"

    $date = null;
    safe($date, 'Never')->diffForHumans(); // Returns "Never"

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