Skip to content

Commit 66409cf

Browse files
committed
Container: component name may be number or null
1 parent d91eb52 commit 66409cf

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

src/ComponentModel/Container.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ public function addComponent(IComponent $component, ?string $name, string $inser
4040
{
4141
if ($name === null) {
4242
$name = $component->getName();
43+
if ($name === null) {
44+
throw new Nette\InvalidStateException("Missing component's name.");
45+
}
4346
}
4447

4548
if (!preg_match(self::NAME_REGEXP, $name)) {
@@ -65,7 +68,7 @@ public function addComponent(IComponent $component, ?string $name, string $inser
6568
if (isset($this->components[$insertBefore])) {
6669
$tmp = [];
6770
foreach ($this->components as $k => $v) {
68-
if ($k === $insertBefore) {
71+
if ((string) $k === $insertBefore) {
6972
$tmp[$name] = $component;
7073
}
7174
$tmp[$k] = $v;
@@ -136,7 +139,7 @@ final public function getComponent(string $name, bool $throw = true): ?IComponen
136139

137140
} elseif ($throw) {
138141
$hint = Nette\Utils\ObjectHelpers::getSuggestion(array_merge(
139-
array_keys($this->components),
142+
array_map('strval', array_keys($this->components)),
140143
array_map('lcfirst', preg_filter('#^createComponent([A-Z0-9].*)#', '$1', get_class_methods($this)))
141144
), $name);
142145
throw new Nette\InvalidArgumentException("Component with name '$name' does not exist" . ($hint ? ", did you mean '$hint'?" : '.'));

tests/ComponentModel/Container.suggestions.phpt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ class TestContainer extends Container
3838

3939
$cont = new TestContainer;
4040
$cont->addComponent(new TestContainer, 'form');
41+
$cont->addComponent(new TestContainer, '0');
4142

4243
Assert::exception(function () use ($cont) {
4344
$comp = $cont->getComponent('from');

tests/ComponentModel/Container.zeroname.phpt

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,12 @@ require __DIR__ . '/../bootstrap.php';
1414

1515

1616
$container = new Container;
17-
$container->addComponent(new Container, '0');
17+
$container->addComponent($c0 = new Container, '0');
18+
Assert::same($c0, $container->getComponent('0'));
1819
Assert::same('0', $container->getComponent('0')->getName());
20+
21+
$container->addComponent($c1 = new Container, '1', '0');
22+
Assert::same(
23+
[1 => $c1, 0 => $c0],
24+
(array) $container->getComponents()
25+
);

0 commit comments

Comments
 (0)