Skip to content

Commit

Permalink
added PHP 8 attribute Inject
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Nov 4, 2020
1 parent c5ba31b commit 8d796de
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 4 deletions.
18 changes: 18 additions & 0 deletions src/DI/Attributes/Inject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/

declare(strict_types=1);

namespace Nette\DI\Attributes;

use Attribute;


#[Attribute(Attribute::TARGET_PROPERTY)]
class Inject
{
}
2 changes: 1 addition & 1 deletion src/DI/DependencyChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ class_uses($name),
$prop->getDocComment(),
PHP_VERSION_ID < 80000
? ($type ? [$type->getName(), $type->allowsNull()] : null)
: (string) $type,
: [(string) $type, count($prop->getAttributes(Attributes\Inject::class))],
];
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/DI/Extensions/InjectExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ namespace A
}
}

namespace E
{
class EClass
{
#[\Nette\DI\Attributes\Inject]
public EInjected $varA;
}
}

namespace
{
use Nette\DI\Extensions\InjectExtension;
Expand All @@ -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));
}
}

0 comments on commit 8d796de

Please sign in to comment.