Skip to content

Instantly share code, notes, and snippets.

@derekmd
Last active October 17, 2021 10:25
Show Gist options
  • Save derekmd/b6f1923bb55a714d90a86838125572f2 to your computer and use it in GitHub Desktop.
Save derekmd/b6f1923bb55a714d90a86838125572f2 to your computer and use it in GitHub Desktop.
Laravel global helper function `optional()`
<?php
use App\Support\Optional;
if (!function_exists('optional')) {
/**
* Allow arrow-syntax access of optional objects by using a higher-order
* proxy object. The eliminates some need of ternary and null coalesce
* operators in Blade templates.
*
* @param mixed|null $value
*
* @return Optional
*/
function optional($value)
{
return new Optional($value);
}
}
<?php
namespace App\Support;
class Optional
{
/**
* The target being transformed.
* Use _ prefix to avoid namespace conflict on __get()
*
* @var mixed
*/
protected $_target;
/**
* Create a new transform proxy instance.
*
* @param mixed $target
*/
public function __construct($target)
{
$this->_target = $target;
}
/**
* Dynamically pass property fetching to the target when it's present.
*
* @param string $property
*
* @return mixed
*/
public function __get($property)
{
if (is_object($this->_target)) {
return $this->_target->{$property};
}
}
/**
* Dynamically pass method calls to the target when it's present.
*
* @param string $method
* @param array $parameters
*
* @return mixed
*/
public function __call($method, $parameters)
{
if (is_object($this->_target)) {
return $this->_target->{$method}(...$parameters);
}
}
/**
* Allow optional(null)->present()->prop to return null without a decorated
* null dereference exception.
*
* @return Optional|mixed
*/
public function present()
{
if (is_object($this->_target)) {
return $this->_target->present(...func_get_args());
}
return new Optional(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment