From 6e29e663ee70bb0830b16cfd958bd84473ee9eef Mon Sep 17 00:00:00 2001 From: fadrian06 Date: Sun, 4 Feb 2024 19:12:01 -0400 Subject: [PATCH] Added Exception for call instance methods when a Class constructor require parameters --- flight/Engine.php | 2 +- flight/core/Dispatcher.php | 25 ++++++++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/flight/Engine.php b/flight/Engine.php index c62df84..58b0859 100644 --- a/flight/Engine.php +++ b/flight/Engine.php @@ -145,7 +145,7 @@ class Engine ]; foreach ($methods as $name) { - $this->dispatcher->set($name, [$this, '_' . $name]); + $this->dispatcher->set($name, [$this, "_$name"]); } // Default configuration settings diff --git a/flight/core/Dispatcher.php b/flight/core/Dispatcher.php index a0f24aa..d91b4b2 100644 --- a/flight/core/Dispatcher.php +++ b/flight/core/Dispatcher.php @@ -7,6 +7,7 @@ namespace flight\core; use Closure; use Exception; use InvalidArgumentException; +use ReflectionClass; use TypeError; /** @@ -193,7 +194,12 @@ class Dispatcher */ public static function execute($callback, array &$params = []) { - if (is_string($callback) && !function_exists($callback)) { + $isInvalidFunctionName = ( + is_string($callback) + && !function_exists($callback) + ); + + if ($isInvalidFunctionName) { throw new InvalidArgumentException('Invalid callback specified.'); } @@ -231,6 +237,23 @@ class Dispatcher [$class, $method] = $func; if (is_string($class) && class_exists($class)) { + $constructor = (new ReflectionClass($class))->getConstructor(); + $constructorParamsNumber = 0; + + if ($constructor !== null) { + $constructorParamsNumber = count($constructor->getParameters()); + } + + if ($constructorParamsNumber > 0) { + $exceptionMessage = "Method '$class::$method' cannot be called statically. "; + $exceptionMessage .= sprintf( + "$class::__construct require $constructorParamsNumber parameter%s", + $constructorParamsNumber > 1 ? 's' : '' + ); + + throw new InvalidArgumentException($exceptionMessage, E_ERROR); + } + $class = new $class(); }