Merge pull request #41265 from nextcloud/feat/dependencyinjection/optional-services

feat(dependencyinjection): Allow optional (nullable) services
This commit is contained in:
Christoph Wurst 2023-11-03 12:52:17 +01:00 committed by GitHub
commit b038dbe0ae
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 0 deletions

View file

@ -105,6 +105,11 @@ class SimpleContainer implements ArrayAccess, ContainerInterface, IContainer {
try {
return $this->query($resolveName);
} catch (QueryException $e2) {
// Pass null if typed and nullable
if ($parameter->allowsNull() && ($parameterType instanceof ReflectionNamedType)) {
return null;
}
// don't lose the error we got while trying to query by type
throw new QueryException($e->getMessage(), (int) $e->getCode(), $e);
}

View file

@ -50,6 +50,17 @@ class ClassComplexConstructor {
}
}
class ClassNullableUntypedConstructorArg {
public function __construct($class) {
}
}
class ClassNullableTypedConstructorArg {
public $class;
public function __construct(?\Some\Class $class) {
$this->class = $class;
}
}
interface IInterfaceConstructor {
}
class ClassInterfaceConstructor {
@ -243,4 +254,17 @@ class SimpleContainerTest extends \Test\TestCase {
$this->assertNotSame(
$this->container->query('test'), $this->container->query('test1'));
}
public function testQueryUntypedNullable(): void {
$this->expectException(\OCP\AppFramework\QueryException::class);
$this->container->query(ClassNullableUntypedConstructorArg::class);
}
public function testQueryTypedNullable(): void {
/** @var ClassNullableTypedConstructorArg $service */
$service = $this->container->query(ClassNullableTypedConstructorArg::class);
self::assertNull($service->class);
}
}