Skip to content

Commit

Permalink
Merge branch 'merge-containers'
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan Vegner committed Jan 9, 2018
2 parents 4501be9 + a9641d1 commit 9524a01
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/Container.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<?php

namespace SD\DependencyInjection;

class Container {
Expand Down Expand Up @@ -61,6 +60,19 @@ public function inject($consumer) {
return $this->injectRecursive($consumer);
}

public static function merge(self ...$containers): self {
$merged = new self();
foreach ($containers as $container) {
foreach ($container->initializers as $name => $initializer) {
$merged->initializers[$name] = $initializer;
}
foreach ($container->services as $name => $service) {
$merged->services[$name] = $service;
}
}
return $merged;
}

// Public for compatibility mode only.
public function get($name) {
$this->usedNames = [];
Expand Down
15 changes: 15 additions & 0 deletions tests/ContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,19 @@ public function testConnect() {
$this->assertEquals($name, $service->getName(), 'Must inject name from config');
$this->assertEquals($container, $service->getContainer(), 'Must inject container by setter');
}

public function testMerge() {
$post = new \stdClass();
$request = new \stdClass();
$postContainer = new Container([
'post' => $post,
]);
$requestContainer = new Container([
'request' => $request,
]);
$mergedContainer = Container::merge($postContainer, $requestContainer);
$consumer = $mergedContainer->inject(new MultiConsumer());
$this->assertSame($post, $consumer->getPost(), 'Must inject post from post container');
$this->assertSame($request, $consumer->getRequest(), 'Must inject request from request container');
}
}
29 changes: 29 additions & 0 deletions tests/MultiConsumer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php
namespace tests;

use SD\DependencyInjection\DeclarerInterface;

class MultiConsumer implements DeclarerInterface {
private $post;
private $request;

public function declareDependencies() {
return ['post', 'request'];
}

public function setPost($post) {
$this->post = $post;
}

public function getPost() {
return $this->post;
}

public function setRequest($request) {
$this->request = $request;
}

public function getRequest() {
return $this->request;
}
}

0 comments on commit 9524a01

Please sign in to comment.