Skip to content

Commit

Permalink
Added "autowire" method to container's class
Browse files Browse the repository at this point in the history
  • Loading branch information
divineniiquaye committed Mar 18, 2021
1 parent ca81202 commit 2d2b40f
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Traits/AutowireTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,25 @@ public function call($callback, array $args = [])
return $callback(...$this->autowireArguments($callable, $args));
}

/**
* Add classes/interfaces for autowiring a service.
*
* @param string $id The registered service id
* @param string[] $types
*
* @return static
*/
public function autowire(string $id, array $types)
{
if (!$this->offsetExists($id)) {
throw new ContainerResolutionException("Service id '{$id}' is not found in container");
}

$this->resolver->autowire($id, $types);

return $this;
}

/**
* Add a class or interface that should be excluded from autowiring.
*
Expand Down
30 changes: 30 additions & 0 deletions tests/ContainerAutowireTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,36 @@ public function testThatAFallbackContainerSupportAutowiring(): void
$this->assertNotSame($rade[AppContainer::class], $rade->get(ContainerInterface::class));
}

public function testContainerAutwoireMethod(): void
{
$rade = new Container();
$rade->set('service', $rade->lazy(Fixtures\Constructor::class));
$rade->autowire('service', [Fixtures\Service::class]);
$service = fn (Fixtures\Service $service) => $service;

$this->assertInstanceOf(Fixtures\Service::class, $one = $rade->get('service'));
$this->assertSame($one, $rade->get(Fixtures\Service::class));
$this->assertSame($one, $rade->call($service));
$this->assertNotSame($one, $rade->get(Fixtures\Constructor::class));

unset($rade['service']);

try {
$rade->call($service);
} catch (ContainerResolutionException $e) {
$this->assertEquals(
$e->getMessage(),
'Parameter $service in Rade\DI\Tests\ContainerAutowireTest::Rade\DI\Tests\{closure}() typehint(s) ' .
'\'Rade\DI\Tests\Fixtures\Service\' not found, and no default value specified.'
);
}

$this->expectExceptionMessage('Service id \'service\' is not found in container');
$this->expectException(ContainerResolutionException::class);

$rade->autowire('service', [Fixtures\Service::class]);
}

public function testAutowiringWithUnionType(): void
{
if (PHP_VERSION_ID < 80000) {
Expand Down

0 comments on commit 2d2b40f

Please sign in to comment.