Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
feat(dependencyinjection): Allow optional (nullable) services
Allows working with classes that might or might not be available.

Signed-off-by: Christoph Wurst <[email protected]>
  • Loading branch information
ChristophWurst committed Nov 3, 2023
commit 78842348b281a02374fd21ba12644e2a1bb5a99d
5 changes: 5 additions & 0 deletions lib/private/AppFramework/Utility/SimpleContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,11 @@ private function buildClass(ReflectionClass $class) {
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);
}
Expand Down
24 changes: 24 additions & 0 deletions tests/lib/AppFramework/Utility/SimpleContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@ public function __construct(ClassSimpleConstructor $class, $test) {
}
}

class ClassNullableUntypedConstructorArg {
public function __construct($class) {
}
}
class ClassNullableTypedConstructorArg {
public $class;
public function __construct(?\Some\Class $class) {
$this->class = $class;
}
}

interface IInterfaceConstructor {
}
class ClassInterfaceConstructor {
Expand Down Expand Up @@ -243,4 +254,17 @@ public function testRegisterAliasFactory() {
$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);
}
}