DigiComp.FlowSymfonyBridge..../Classes/ObjectManagement/RewindableGenerator.php

58 lines
1.7 KiB
PHP
Raw Permalink Normal View History

<?php
namespace DigiComp\FlowSymfonyBridge\Messenger\ObjectManagement;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\ObjectManagement\ObjectManagerInterface;
use Neos\Utility\PositionalArraySorter;
use Psr\Log\LoggerInterface;
/**
* Helper for dependency injection. It allows to defer object construction until the list is actually iterated.
*
* It filters out service ids which have been set to NULL to make deleting services possible, without overwriting the
* complete array, allowing to use string keys.
*/
class RewindableGenerator implements \IteratorAggregate, \Countable
{
2023-02-18 22:53:05 +01:00
#[Flow\Inject(lazy: false)]
protected ObjectManagerInterface $objectManager;
private array $serviceIds;
private \Closure $generator;
public function __construct(array $serviceIds)
{
$this->serviceIds = $serviceIds;
2022-09-18 13:17:53 +02:00
$sortedServiceIds = \array_keys(
(new PositionalArraySorter($serviceIds))->toArray()
);
$this->generator = function () use ($sortedServiceIds) {
foreach ($sortedServiceIds as $serviceId) {
if ($serviceId === null) {
continue;
}
$object = $this->objectManager->get($serviceId);
// TODO: Thats a quite poor solution to dynamically inject the logger - but it is easy
2022-09-18 13:17:53 +02:00
if (\method_exists($object, 'setLogger')) {
$object->setLogger($this->objectManager->get(LoggerInterface::class));
}
yield $object;
}
};
}
2023-02-18 22:53:05 +01:00
public function getIterator(): \Traversable
{
$g = $this->generator;
return $g();
}
2023-02-18 22:53:05 +01:00
public function count(): int
{
2022-09-18 13:17:53 +02:00
return \count($this->serviceIds);
}
}