feat(dependencyinjection): Allow optional (nullable) services

Allows working with classes that might or might not be available.

Signed-off-by: Christoph Wurst <christoph@winzerhof-wurst.at>
pull/41265/head
Christoph Wurst 7 months ago
parent ba93afbddd
commit 78842348b2
No known key found for this signature in database
GPG Key ID: CC42AC2A7F0E56D8

@ -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);
}

@ -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);
}
}

Loading…
Cancel
Save