Skip to content

Commit 8db521a

Browse files
committed
[DependencyInjection] Make ServiceLocator iterable
1 parent 0cd0c49 commit 8db521a

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

src/Symfony/Component/DependencyInjection/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ CHANGELOG
55
---
66

77
* Add argument `$prepend` to `ContainerConfigurator::extension()` to prepend the configuration instead of appending it
8+
* Make `ServiceLocator` iterable
89

910
7.0
1011
---

src/Symfony/Component/DependencyInjection/ServiceLocator.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@
2727
* @template-covariant T of mixed
2828
*
2929
* @implements ServiceProviderInterface<T>
30+
* @implements \IteratorAggregate<string, T>
3031
*/
31-
class ServiceLocator implements ServiceProviderInterface, \Countable
32+
class ServiceLocator implements ServiceProviderInterface, \IteratorAggregate, \Countable
3233
{
3334
use ServiceLocatorTrait {
3435
get as private doGet;
@@ -82,6 +83,13 @@ public function count(): int
8283
return \count($this->getProvidedServices());
8384
}
8485

86+
public function getIterator(): \Traversable
87+
{
88+
foreach (array_keys($this->getProvidedServices()) as $id) {
89+
yield $id => $this->get($id);
90+
}
91+
}
92+
8593
private function createNotFoundException(string $id): NotFoundExceptionInterface
8694
{
8795
if ($this->loading) {

src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,17 @@ public function testProvidesServicesInformation()
101101
'baz' => '?string',
102102
]);
103103
}
104+
105+
public function testIsCountableAndIterable()
106+
{
107+
$locator = $this->getServiceLocator([
108+
'foo' => fn () => 'bar',
109+
'bar' => fn () => 'baz',
110+
]);
111+
112+
$this->assertCount(2, $locator);
113+
$this->assertSame(['foo' => 'bar', 'bar' => 'baz'], iterator_to_array($locator));
114+
}
104115
}
105116

106117
class SomeServiceSubscriber implements ServiceSubscriberInterface

0 commit comments

Comments
 (0)