From 8d796def05d0fc190e29299797a8c81e716f6399 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Fri, 23 Oct 2020 14:56:32 +0200 Subject: [PATCH] added PHP 8 attribute Inject --- src/DI/Attributes/Inject.php | 18 ++++++++++++++++++ src/DI/DependencyChecker.php | 2 +- src/DI/Extensions/InjectExtension.php | 5 +++-- ...njectExtension.getInjectProperties().php74} | 17 ++++++++++++++++- 4 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 src/DI/Attributes/Inject.php rename tests/DI/{InjectExtension.getInjectProperties().php74.phptx => InjectExtension.getInjectProperties().php74} (68%) diff --git a/src/DI/Attributes/Inject.php b/src/DI/Attributes/Inject.php new file mode 100644 index 000000000..325e2b291 --- /dev/null +++ b/src/DI/Attributes/Inject.php @@ -0,0 +1,18 @@ +getDocComment(), PHP_VERSION_ID < 80000 ? ($type ? [$type->getName(), $type->allowsNull()] : null) - : (string) $type, + : [(string) $type, count($prop->getAttributes(Attributes\Inject::class))], ]; } } diff --git a/src/DI/Extensions/InjectExtension.php b/src/DI/Extensions/InjectExtension.php index 64e0458d5..90bcdc8d0 100644 --- a/src/DI/Extensions/InjectExtension.php +++ b/src/DI/Extensions/InjectExtension.php @@ -112,9 +112,10 @@ public static function getInjectProperties(string $class): array $res = []; foreach (get_class_vars($class) as $name => $foo) { $rp = new \ReflectionProperty($class, $name); - if (DI\Helpers::parseAnnotation($rp, 'inject') !== null) { + $hasAttr = PHP_VERSION_ID >= 80000 && $rp->getAttributes(DI\Attributes\Inject::class); + if ($hasAttr || DI\Helpers::parseAnnotation($rp, 'inject') !== null) { if ($type = Reflection::getPropertyType($rp)) { - } elseif ($type = DI\Helpers::parseAnnotation($rp, 'var')) { + } elseif (!$hasAttr && ($type = DI\Helpers::parseAnnotation($rp, 'var'))) { $type = Reflection::expandClassName($type, Reflection::getPropertyDeclaringClass($rp)); } $res[$name] = $type; diff --git a/tests/DI/InjectExtension.getInjectProperties().php74.phptx b/tests/DI/InjectExtension.getInjectProperties().php74 similarity index 68% rename from tests/DI/InjectExtension.getInjectProperties().php74.phptx rename to tests/DI/InjectExtension.getInjectProperties().php74 index 54284b66e..b176c8579 100644 --- a/tests/DI/InjectExtension.getInjectProperties().php74.phptx +++ b/tests/DI/InjectExtension.getInjectProperties().php74 @@ -32,6 +32,15 @@ namespace A } } +namespace E +{ + class EClass + { + #[\Nette\DI\Attributes\Inject] + public EInjected $varA; + } +} + namespace { use Nette\DI\Extensions\InjectExtension; @@ -44,5 +53,11 @@ namespace 'varA' => 'A\AInjected', 'varB' => 'A\B\BInjected', 'varC' => 'A\AInjected', - ], InjectExtension::getInjectProperties('A\AClass')); + ], InjectExtension::getInjectProperties(A\AClass::class)); + + if (PHP_VERSION_ID >= 80000) { + Assert::same([ + 'varA' => 'E\EInjected', + ], InjectExtension::getInjectProperties(E\EClass::class)); + } }