Skip to content

Instantly share code, notes, and snippets.

@aliselcuk
Created October 25, 2017 16:50
Show Gist options
  • Select an option

  • Save aliselcuk/207f380c0c2809abf34ce7c323c5c16c to your computer and use it in GitHub Desktop.

Select an option

Save aliselcuk/207f380c0c2809abf34ce7c323c5c16c to your computer and use it in GitHub Desktop.
a PHP trait to abort your methods (optionally)
trait EnforcableTrait
{
/** @return $this */
public function must($otherwise = null)
{
return (new class ($this, $otherwise)
{
private $parent;
private $otherwise;
public function __construct($parent, $otherwise)
{
$this->parent = $parent;
$this->otherwise = $otherwise;
}
public function __call($name, $arguments)
{
if (!$res = call_user_func_array([$this->parent, $name], $arguments)) {
$this->__fail();
}
return $res;
}
private function __fail() {
if ($this->otherwise instanceof \Exception) {
throw $this->otherwise;
}
throw new \Exception($this->otherwise ?: 'Argument not found');
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment