Created
October 25, 2017 16:50
-
-
Save aliselcuk/207f380c0c2809abf34ce7c323c5c16c to your computer and use it in GitHub Desktop.
a PHP trait to abort your methods (optionally)
This file contains hidden or 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
| 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