From 4d2d91f85be64f2ad1136c52844f0109fb2dcbd1 Mon Sep 17 00:00:00 2001 From: Mathias Gelhausen Date: Tue, 16 Jun 2020 16:31:52 +0200 Subject: [PATCH] feat: reflection creation via array spec To be able to use the ::class pseudy-constant in test cases when specifiying targets, this commit will allow array specification: ['!' => FQCN::class] --- src/Utils/Instance.php | 15 +++++++++++++-- test/TestUtilsTest/Utils/InstanceTest.php | 3 ++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/Utils/Instance.php b/src/Utils/Instance.php index fc56dca..6566fa8 100644 --- a/src/Utils/Instance.php +++ b/src/Utils/Instance.php @@ -17,6 +17,8 @@ * Creates object instances. * * @author Mathias Gelhausen + * + * @since 2.x create reflection via array spec */ final class Instance { @@ -50,6 +52,9 @@ public static function reflection($fqcnOrObject): \ReflectionClass * if __$fqcn__ is a string and starts with "!", a \ReflectionClass * object is returned. * + * if __$fqcn__ is an array with the key "!", a \ReflectionClass + * object is created from the value of that key (which must be an FQCN or an object) + * * if __$fqcn__ is an array, the first element is used as FQCN and * all other elements are used as constructor arguments - other * arguments passed in are ignored. @@ -58,12 +63,18 @@ public static function reflection($fqcnOrObject): \ReflectionClass * @param mixed ...$arguments * * @return object + * + * @since 2.x Create reflection via array spec (['!' => FQCN/Object]) */ public static function create($fqcn, ...$arguments): object { if (is_array($fqcn)) { - $arguments = array_slice($fqcn, 1); - $fqcn = reset($fqcn); + if (isset($fqcn['!']) && is_string($fqcn['!'])) { + return self::reflection($fqcn['!']); + } else { + $arguments = array_slice($fqcn, 1); + $fqcn = reset($fqcn); + } } if (!is_string($fqcn)) { diff --git a/test/TestUtilsTest/Utils/InstanceTest.php b/test/TestUtilsTest/Utils/InstanceTest.php index a8708e3..94f8fae 100644 --- a/test/TestUtilsTest/Utils/InstanceTest.php +++ b/test/TestUtilsTest/Utils/InstanceTest.php @@ -68,7 +68,8 @@ public function __construct(...$args) [$fqcn, [], $fqcn], [$fqcn, ['arg1'], $fqcn, 'arg1'], [$fqcn, ['arg1'], [$fqcn, 'arg1'], 'arg2'], - [\ReflectionClass::class, false, "!$fqcn"] + [\ReflectionClass::class, false, "!$fqcn"], + [\ReflectionClass::class, false, ['!' => $fqcn]], ]; }