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
19 changes: 16 additions & 3 deletions src/CascadeContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,24 @@ final class CascadeContainer implements ContainerInterface
/** @var array<string,string> */
private array $aliases = [];

/**
* @param ContainerInterface|array<string,mixed>|null $parent Parent container or initial service instances array map
* @param DependencyResolverInterface|null $resolver
*/
public function __construct(
ContainerInterface | null $parent = null,
DependencyResolverInterface $resolver = null,
ContainerInterface | array | null $parent = null,
DependencyResolverInterface $resolver = null,
) {
$this->parent = $parent ?: new NullContainer();
if (is_array($parent)) {
foreach ($parent as $id => $instance) {
if ( ! is_string($id)) {
throw new InvalidArgumentException('The service ids have to be strings.');
}
$this->instances[$id] = $instance;
}
}

$this->parent = $parent instanceof ContainerInterface ? $parent : new NullContainer();
$this->resolver = $resolver ?: new DependencyResolver($this);
}

Expand Down
11 changes: 11 additions & 0 deletions tests/Feature/CascadeContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@
expect(new CascadeContainer($parent))->toBeInstanceOf(CascadeContainer::class);
});

it('should construct a new instance with initial services', function () {
$container = new CascadeContainer([
'logger' => function (string $message) {
echo $message, PHP_EOL;
},
]);

expect($container->has('logger'))->toBeTrue();
expect($container->get('logger'))->toBeCallable();
});

it('should construct a new instance of CascadeContainer with a custom resolver', function () {
$resolver = new class implements DependencyResolver {
public function resolve(string $className): mixed
Expand Down