Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ca47fd0

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

File tree

4 files changed

+46
-1
lines changed

4 files changed

+46
-1
lines changed

src/Symfony/Component/DependencyInjection/CHANGELOG.md

+1
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
---
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\DependencyInjection;
13+
14+
use Psr\Container\ContainerInterface as PsrContainerInterface;
15+
16+
/**
17+
* @author Kevin Bond <[email protected]>
18+
*
19+
* @template-covariant T of mixed
20+
*
21+
* @extends \IteratorAggregate<string, T>
22+
*/
23+
interface ServiceCollectionInterface extends PsrContainerInterface, \IteratorAggregate, \Countable
24+
{
25+
}

src/Symfony/Component/DependencyInjection/ServiceLocator.php

+9-1
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

+11
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)