Skip to content

Commit

Permalink
feat(dependencyinjection): Allow optional (nullable) services
Browse files Browse the repository at this point in the history
Allows working with classes that might or might not be available.

Signed-off-by: Christoph Wurst <christoph@winzerhof-wurst.at>
  • Loading branch information
ChristophWurst committed Nov 3, 2023
1 parent ba93afb commit 7884234
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
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);
}
}

0 comments on commit 7884234

Please sign in to comment.