DigiComp.FlowSymfonyBridge..../Classes/ObjectManagement/RewindableGenerator.php
Ferdinand Kuhl 04ee933830
All checks were successful
ci/woodpecker/push/code-style Pipeline was successful
ci/woodpecker/push/functional-tests Pipeline was successful
Replacing annotations with attributes
2023-02-18 22:53:05 +01:00

57 lines
1.7 KiB
PHP

<?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
{
#[Flow\Inject(lazy: false)]
protected ObjectManagerInterface $objectManager;
private array $serviceIds;
private \Closure $generator;
public function __construct(array $serviceIds)
{
$this->serviceIds = $serviceIds;
$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
if (\method_exists($object, 'setLogger')) {
$object->setLogger($this->objectManager->get(LoggerInterface::class));
}
yield $object;
}
};
}
public function getIterator(): \Traversable
{
$g = $this->generator;
return $g();
}
public function count(): int
{
return \count($this->serviceIds);
}
}