Last active
February 16, 2018 11:00
-
-
Save shov/7a987ed4d22395cfe54fbf1a75c7fc21 to your computer and use it in GitHub Desktop.
PHP Decorator trait. For a while not correct (catch any throwable and means it's error of calling undefined static method
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
/** | |
* Trait DecoratorTrait | |
* | |
* Have to implemented: | |
* @method getDecoratedObject() | |
* @static $decoratedClass | |
*/ | |
trait DecoratorTrait | |
{ | |
/** | |
* @param $method | |
* @param $args | |
* @return mixed | |
* @throws \Exception | |
*/ | |
public function __call($method, $args) | |
{ | |
if (is_callable([$this->getDecoratedObject(), $method])) { | |
return call_user_func_array([$this->getDecoratedObject(), $method], $args); | |
} | |
throw new \Exception( | |
sprintf("Call undefined method: %s::%s", get_class($this->getDecoratedObject()), $method)); | |
} | |
/** | |
* @param $property | |
* @return null | |
*/ | |
public function __get($property) | |
{ | |
$publicVars = get_object_vars($this->getDecoratedObject()); | |
if (array_key_exists($property, $publicVars)) { | |
return $this->getDecoratedObject()->$property; | |
} | |
return null; | |
} | |
/** | |
* @param $property | |
* @param $value | |
* @return $this | |
*/ | |
public function __set($property, $value) | |
{ | |
$this->getDecoratedObject()->$property = $value; | |
return $this; | |
} | |
/** | |
* @param $method | |
* @param $args | |
* @return mixed | |
* @throws \Exception | |
*/ | |
public static function __callStatic($method, $args) { | |
try { | |
return forward_static_call_array([static::$decoratedClass, $method], $args); | |
} catch (\Throwable $e) { | |
throw new \Exception( | |
sprintf("Call undefined static method: %s::%s", static::$decoratedClass, $method)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment