Skip to content

Commit

Permalink
ServiceDefinition: setup: prepends @self in depth
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Oct 18, 2023
1 parent 0e8aa52 commit 3ebef83
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 8 deletions.
21 changes: 13 additions & 8 deletions src/DI/Definitions/ServiceDefinition.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,15 +177,20 @@ public function complete(Nette\DI\Resolver $resolver): void

$this->creator = $resolver->completeStatement($this->creator);

foreach ($this->setup as &$setup) {
if (
is_string($setup->getEntity())
&& strpbrk($setup->getEntity(), ':@?\\') === false
) { // auto-prepend @self
$setup = new Statement([new Reference(Reference::Self), $setup->getEntity()], $setup->arguments);
}
foreach ($this->setup as $i => $setup) {
$this->setup[$i] = $resolver->completeStatement($this->prependSelf($setup), true);
}
}

$setup = $resolver->completeStatement($setup, true);

private function prependSelf(Statement $setup): Statement
{
if (is_string($member = $setup->getEntity()) && preg_match('~^\$?[a-z][a-zA-Z0-9[\]]*$~', $member)) {
return new Statement([new Reference(Reference::Self), $member], $setup->arguments);
} elseif (is_array($setup->getEntity()) && $setup->getEntity()[0] instanceof Statement) {
return new Statement([$this->prependSelf($setup->getEntity()[0]), $setup->getEntity()[1]], $setup->arguments);
} else {
return $setup;
}
}

Expand Down
3 changes: 3 additions & 0 deletions tests/DI/Compiler.services.setup.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class Lorem
public function test(...$args)
{
Notes::add(__METHOD__ . ' ' . implode(' ', $args));
return new self;
}
}

Expand Down Expand Up @@ -79,6 +80,8 @@ Assert::same([
'globtest 7',
'Ipsum::test a',
'Ipsum::test 10 b',
'Lorem::test outer',
'Lorem::test inner',
], Notes::fetch());

Assert::same(8, $container->getService('lorem')->test);
Expand Down
1 change: 1 addition & 0 deletions tests/DI/files/compiler.services.setup.neon
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ services:
# rich
- Ipsum(a)::test
- Ipsum(b)::test(10)
- test(outer)::test(inner)

# object
- \Ipsum(@self)
Expand Down

0 comments on commit 3ebef83

Please sign in to comment.