Skip to content

Commit

Permalink
Make container optional (#198)
Browse files Browse the repository at this point in the history
  • Loading branch information
vjik committed Dec 2, 2023
1 parent 53d1a90 commit bbcd13a
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 7 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Expand Up @@ -2,7 +2,7 @@

## 1.1.1 under development

- no changes in this release.
- Enh #198: Make container optional (@vjik)

## 1.1.0 November 08, 2022

Expand Down
2 changes: 1 addition & 1 deletion src/Factory.php
Expand Up @@ -32,7 +32,7 @@ final class Factory
* @throws InvalidConfigException
*/
public function __construct(
ContainerInterface $container,
?ContainerInterface $container = null,
array $definitions = [],
private bool $validate = true
) {
Expand Down
10 changes: 5 additions & 5 deletions src/FactoryInternalContainer.php
Expand Up @@ -37,12 +37,12 @@ final class FactoryInternalContainer implements ContainerInterface
private array $creatingIds = [];

/**
* @param ContainerInterface $container Container to use for resolving dependencies.
* @param ContainerInterface|null $container Container to use for resolving dependencies.
* @param array<string, mixed> $definitions Definitions to create objects with.
*/
public function __construct(
private ContainerInterface $container,
private array $definitions = []
private ?ContainerInterface $container,
private array $definitions
) {
}

Expand All @@ -69,7 +69,7 @@ public function get($id): mixed
return $this->build($id);
}

if ($this->container->has($id)) {
if ($this->container?->has($id)) {
return $this->container->get($id);
}

Expand All @@ -78,7 +78,7 @@ public function get($id): mixed

public function has($id): bool
{
return $this->hasDefinition($id) || $this->container->has($id);
return $this->hasDefinition($id) || $this->container?->has($id);
}

public function create(DefinitionInterface $definition): mixed
Expand Down
12 changes: 12 additions & 0 deletions tests/Unit/FactoryTest.php
Expand Up @@ -54,6 +54,18 @@

final class FactoryTest extends TestCase
{
public function testBase(): void
{
$factory = new Factory();

$object1 = $factory->create(ColorRed::class);
$object2 = $factory->create(ColorRed::class);

$this->assertInstanceOf(ColorRed::class, $object1);
$this->assertInstanceOf(ColorRed::class, $object2);
$this->assertNotSame($object1, $object2);
}

public function testWithDefinitions(): void
{
$container = new SimpleContainer();
Expand Down

0 comments on commit bbcd13a

Please sign in to comment.