Skip to content

Commit

Permalink
Container: component name may be number or null
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Apr 21, 2020
1 parent d91eb52 commit 66409cf
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
7 changes: 5 additions & 2 deletions src/ComponentModel/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ public function addComponent(IComponent $component, ?string $name, string $inser
{
if ($name === null) {
$name = $component->getName();
if ($name === null) {
throw new Nette\InvalidStateException("Missing component's name.");
}
}

if (!preg_match(self::NAME_REGEXP, $name)) {
Expand All @@ -65,7 +68,7 @@ public function addComponent(IComponent $component, ?string $name, string $inser
if (isset($this->components[$insertBefore])) {
$tmp = [];
foreach ($this->components as $k => $v) {
if ($k === $insertBefore) {
if ((string) $k === $insertBefore) {
$tmp[$name] = $component;
}
$tmp[$k] = $v;
Expand Down Expand Up @@ -136,7 +139,7 @@ final public function getComponent(string $name, bool $throw = true): ?IComponen

} elseif ($throw) {
$hint = Nette\Utils\ObjectHelpers::getSuggestion(array_merge(
array_keys($this->components),
array_map('strval', array_keys($this->components)),
array_map('lcfirst', preg_filter('#^createComponent([A-Z0-9].*)#', '$1', get_class_methods($this)))
), $name);
throw new Nette\InvalidArgumentException("Component with name '$name' does not exist" . ($hint ? ", did you mean '$hint'?" : '.'));
Expand Down
1 change: 1 addition & 0 deletions tests/ComponentModel/Container.suggestions.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class TestContainer extends Container

$cont = new TestContainer;
$cont->addComponent(new TestContainer, 'form');
$cont->addComponent(new TestContainer, '0');

Assert::exception(function () use ($cont) {
$comp = $cont->getComponent('from');
Expand Down
9 changes: 8 additions & 1 deletion tests/ComponentModel/Container.zeroname.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,12 @@ require __DIR__ . '/../bootstrap.php';


$container = new Container;
$container->addComponent(new Container, '0');
$container->addComponent($c0 = new Container, '0');
Assert::same($c0, $container->getComponent('0'));
Assert::same('0', $container->getComponent('0')->getName());

$container->addComponent($c1 = new Container, '1', '0');
Assert::same(
[1 => $c1, 0 => $c0],
(array) $container->getComponents()
);

0 comments on commit 66409cf

Please sign in to comment.