Skip to content

Commit

Permalink
ContainerBuilder::addDefinition(null) adds anonymous service
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed May 29, 2018
1 parent ca1089a commit ae60e27
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/DI/ContainerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,15 @@ class ContainerBuilder
/**
* Adds new service definition.
*/
public function addDefinition(string $name, ServiceDefinition $definition = null): ServiceDefinition
public function addDefinition(?string $name, ServiceDefinition $definition = null): ServiceDefinition
{
if ($name === null) {
$name = count($this->definitions) + 1;
while (isset($this->definitions[$name])) {
$name++;
}
}

$this->classListNeedsRefresh = true;
if (!$name) { // builder is not ready for falsy names such as '0'
throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($name)));
Expand Down
22 changes: 22 additions & 0 deletions tests/DI/ContainerBuilder.basic5.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

use Nette\DI;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


$builder = new DI\ContainerBuilder;
$builder->addDefinition('1')
->setFactory('stdClass');
$builder->addDefinition(null)
->setFactory('stdClass');


$container = createContainer($builder);

Assert::type(stdClass::class, $container->getService('1'));
Assert::type(stdClass::class, $container->getService('2'));

0 comments on commit ae60e27

Please sign in to comment.