Skip to content
This repository has been archived by the owner on Jan 24, 2024. It is now read-only.

Commit

Permalink
soft autowire
Browse files Browse the repository at this point in the history
  • Loading branch information
wolfy-j committed Feb 2, 2017
1 parent 5e63007 commit bf0ac0e
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
6 changes: 6 additions & 0 deletions source/Spiral/Core/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

use Interop\Container\ContainerInterface;
use ReflectionFunctionAbstract as ContextFunction;
use Spiral\Core\Container\Autowire;
use Spiral\Core\Container\InjectableInterface;
use Spiral\Core\Container\InjectorInterface;
use Spiral\Core\Container\SingletonInterface;
Expand Down Expand Up @@ -206,6 +207,11 @@ final public function resolveArguments(
throw new ContainerException($e->getMessage(), $e->getCode(), $e);
}

if (array_key_exists($name, $parameters) && $parameters[$name] instanceof Autowire) {
$arguments[] = $parameters[$name]->resolve($this);
continue;
}

//No declared type or scalar type or array
if (empty($class)) {
//Provided from outside
Expand Down
57 changes: 57 additions & 0 deletions source/Spiral/Core/Container/Autowire.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php
/**
* components
*
* @author Wolfy-J
*/

namespace Spiral\Core\Container;

use Interop\Container\ContainerInterface;

/**
* Provides ability to delegate option to container.
*/
final class Autowire
{
/**
* Delegation target
*
* @var mixed
*/
private $alias;

/**
* Autowire constructor.
*
* @param string $alias
*/
public function __construct(string $alias)
{
$this->alias = $alias;
}

/**
* @param \Interop\Container\ContainerInterface $container
*
* @return mixed
*
* @throws \Interop\Container\Exception\NotFoundException No entry was found for this
* identifier.
* @throws \Interop\Container\Exception\ContainerException Error while retrieving the entry.
*/
public function resolve(ContainerInterface $container)
{
return $container->get($this->alias);
}

/**
* @param $an_array
*
* @return static
*/
public static function __set_state($an_array)
{
return new static($an_array['alias']);
}
}
14 changes: 14 additions & 0 deletions tests/Core/AutowiringTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -303,4 +303,18 @@ public function testAutowireOptionalString()

$this->assertInstanceOf(TypedClass::class, $object);
}

public function testAutowireDelegate()
{
$container = new Container();

$container->bind('sample-binding', $s = new SampleClass());

$object = $container->make(SoftDependedClass::class, [
'name' => 'some-name',
'sample' => new Container\Autowire('sample-binding')
]);

$this->assertSame($s, $object->getSample());
}
}

0 comments on commit bf0ac0e

Please sign in to comment.