Skip to content

Commit

Permalink
Merge 7ee0fcf into 806ca40
Browse files Browse the repository at this point in the history
  • Loading branch information
downace committed Jul 4, 2019
2 parents 806ca40 + 7ee0fcf commit c372c6f
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
4 changes: 4 additions & 0 deletions doc/container.md
Expand Up @@ -30,6 +30,10 @@ You can set entries directly on the container:
```php
$container->set('foo', 'bar');
$container->set('MyInterface', \DI\create('MyClass'));

// Use \DI\value if you need to set a closure as raw value,
// because closures are interpreted as factories by default
$container->set('myClosure', \DI\value(function() { /* ... */ }));
```

However it is recommended to use definition files. See the [definition documentation](definition.md).
Expand Down
5 changes: 4 additions & 1 deletion src/Container.php
Expand Up @@ -16,6 +16,7 @@
use DI\Definition\Source\MutableDefinitionSource;
use DI\Definition\Source\ReflectionBasedAutowiring;
use DI\Definition\Source\SourceChain;
use DI\Definition\ValueDefinition;
use DI\Invoker\DefinitionParameterResolver;
use DI\Proxy\ProxyFactory;
use InvalidArgumentException;
Expand Down Expand Up @@ -282,7 +283,9 @@ public function set(string $name, $value)
$value = new FactoryDefinition($name, $value);
}

if ($value instanceof Definition) {
if ($value instanceof ValueDefinition) {
$this->resolvedEntries[$name] = $value->getValue();
} elseif ($value instanceof Definition) {
$value->setName($name);
$this->setDefinition($name, $value);
} else {
Expand Down
23 changes: 23 additions & 0 deletions tests/IntegrationTest/ContainerSetTest.php
Expand Up @@ -7,6 +7,7 @@
use DI\ContainerBuilder;
use function DI\create;
use function DI\get;
use function DI\value;

/**
* Tests the set() method from the container.
Expand Down Expand Up @@ -58,6 +59,28 @@ public function array_entries_can_be_overridden_by_values(ContainerBuilder $buil
$this->assertSame('hello', $container->get('foo'));
}

/**
* @see https://github.com/PHP-DI/PHP-DI/issues/674
* @test
* @dataProvider provideContainer
*/
public function value_definitions_are_interpreted_as_raw_values(ContainerBuilder $builder)
{
$container = $builder->build();

$foo = 'foo';
$bar = new ContainerSetTest\Dummy();
$baz = function() {};

$container->set('foo', value($foo));
$container->set('bar', value($bar));
$container->set('baz', value($baz));

$this->assertSame($foo, $container->get('foo'));
$this->assertSame($bar, $container->get('bar'));
$this->assertSame($baz, $container->get('baz'));
}

/**
* @test
* @dataProvider provideContainer
Expand Down

0 comments on commit c372c6f

Please sign in to comment.