Entity dynamic method calling improved

This commit is contained in:
fbsanchez 2021-09-16 21:16:49 +02:00
parent d7452d19e8
commit b33be80be3

View File

@ -153,6 +153,17 @@ abstract class Entity
/** /**
* Dynamically call methods in this object. * Dynamically call methods in this object.
* *
* To dynamically switch between community methods and prioritize
* enterprise ones, define method visibility as 'protected' in both
* classes.
*
* For instance, in following situation:
* protected PandoraFMS\Agent::test()
* protected PandoraFMS\Enterprise\Agent::test()
*
* If enterprise is available, then PandoraFMS\Enterprise\Agent::test()
* will be executed, community method otherwise.
*
* @param string $methodName Name of target method or attribute. * @param string $methodName Name of target method or attribute.
* @param array $params Arguments for target method. * @param array $params Arguments for target method.
* *
@ -161,41 +172,42 @@ abstract class Entity
*/ */
public function __call(string $methodName, ?array $params=null) public function __call(string $methodName, ?array $params=null)
{ {
// Prioritize written methods over dynamic ones.
if (method_exists($this, $methodName) === true) {
return call_user_func_array(
$this->{$methodName},
$params
);
}
// Enterprise capabilities. // Enterprise capabilities.
// Prioritize enterprise written methods over dynamic fields.
if (\enterprise_installed() === true if (\enterprise_installed() === true
&& $this->enterprise !== null && $this->enterprise !== null
&& method_exists($this->enterprise, $methodName) === true && method_exists($this->enterprise, $methodName) === true
) { ) {
$obj = $this->enterprise;
$callback = function (...$parameters) use ($obj, $methodName) {
return $obj->$methodName(...$parameters);
};
return call_user_func_array( return call_user_func_array(
[ $callback,
$this->enterprise,
$methodName,
],
$params $params
); );
} }
if (array_key_exists($methodName, $this->fields) === true) { if (method_exists($this, $methodName) === false) {
if (empty($params) === true) { if (array_key_exists($methodName, $this->fields) === true) {
return $this->fields[$methodName]; if (empty($params) === true) {
} else { return $this->fields[$methodName];
$this->fields[$methodName] = $params[0]; } else {
$this->fields[$methodName] = $params[0];
}
return null;
} }
return null; throw new \Exception(
get_class($this).' error, method '.$methodName.' does not exist'
);
} }
throw new \Exception( // Do not return nor throw exceptions after this point, allow php
get_class($this).' error, method '.$methodName.' does not exist' // default __call behaviour to continue working with object method
); // defined.
} }