summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorChristoph Wurst <ChristophWurst@users.noreply.github.com>2023-11-03 12:52:17 +0100
committerGitHub <noreply@github.com>2023-11-03 12:52:17 +0100
commitb038dbe0aef8c8680bd4f9075f00d8303338f518 (patch)
tree34cfe503e36a0222c2df58f0b9a7af69cb3836dd
parentba93afbddd4930408129e863957fd7b631582ae2 (diff)
parent78842348b281a02374fd21ba12644e2a1bb5a99d (diff)
downloadnextcloud-server-b038dbe0aef8c8680bd4f9075f00d8303338f518.tar.gz
nextcloud-server-b038dbe0aef8c8680bd4f9075f00d8303338f518.zip
Merge pull request #41265 from nextcloud/feat/dependencyinjection/optional-services
feat(dependencyinjection): Allow optional (nullable) services
-rw-r--r--lib/private/AppFramework/Utility/SimpleContainer.php5
-rw-r--r--tests/lib/AppFramework/Utility/SimpleContainerTest.php24
2 files changed, 29 insertions, 0 deletions
diff --git a/lib/private/AppFramework/Utility/SimpleContainer.php b/lib/private/AppFramework/Utility/SimpleContainer.php
index 7aa5cb83926..ecd8485cd7b 100644
--- a/lib/private/AppFramework/Utility/SimpleContainer.php
+++ b/lib/private/AppFramework/Utility/SimpleContainer.php
@@ -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);
}
diff --git a/tests/lib/AppFramework/Utility/SimpleContainerTest.php b/tests/lib/AppFramework/Utility/SimpleContainerTest.php
index 61b3299671b..054012bdd5d 100644
--- a/tests/lib/AppFramework/Utility/SimpleContainerTest.php
+++ b/tests/lib/AppFramework/Utility/SimpleContainerTest.php
@@ -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);
+ }
}