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 25, 2020
1 parent b0600fa commit 9b4240b
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 2 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
{
}
1 change: 1 addition & 0 deletions src/DI/DependencyChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ class_uses($name),
$prop->name,
$prop->getDocComment(),
Reflection::getPropertyTypes($prop),
PHP_VERSION_ID >= 80000 ? count($prop->getAttributes(Attributes\Inject::class)) : null,
];
}
}
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'))) {
if (strpos($type, '|') !== false) {
throw new Nette\InvalidStateException('The ' . Reflection::toString($rp) . ' is not expected to have a union type.');
}
Expand Down
10 changes: 10 additions & 0 deletions tests/DI/InjectExtension.getInjectProperties().php80.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,17 @@ class AClass
public AClass|\stdClass $var;
}

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


Assert::exception(function () {
InjectExtension::getInjectProperties(AClass::class);
}, Nette\InvalidStateException::class, 'The AClass::$var is not expected to have a union type.');

Assert::same([
'varA' => 'EInjected',
], InjectExtension::getInjectProperties(EClass::class));

0 comments on commit 9b4240b

Please sign in to comment.