DigiComp.FluidRenderFunctions/Classes/ViewHelpers/ApplyRenderFunctionViewHelper.php

49 lines
1.6 KiB
PHP
Raw Normal View History

2024-06-01 23:15:35 +02:00
<?php
declare(strict_types=1);
namespace DigiComp\FluidRenderFunctions\ViewHelpers;
use DigiComp\FluidRenderFunctions\InvokeRenderFunctionInterface;
use DigiComp\FluidRenderFunctions\Utils\GeneratorClosureIterator;
use DigiComp\FluidRenderFunctions\Utils\RenderableProxy;
use Neos\FluidAdaptor\Core\ViewHelper\AbstractViewHelper;
class ApplyRenderFunctionViewHelper extends AbstractViewHelper
{
public function initializeArguments(): void
{
parent::initializeArguments();
$this->registerArgument('in', 'mixed', 'subject to apply the render function to');
$this->registerArgument('function', InvokeRenderFunctionInterface::class, 'render function to use', true);
$this->registerArgument(
'force',
'bool',
'if set, it will be applied to the provided in, if not, it will be applied to each item for '
. 'iterables instead',
false,
false
);
}
public function render()
{
$in = $this->arguments['in'];
if ($in === null) {
$in = $this->renderChildren();
}
if (\is_iterable($in) && $this->arguments['force'] === false) {
return new GeneratorClosureIterator(fn () => $this->getProxyGenerator($this->arguments['function'], $in));
} else {
return new RenderableProxy($this->arguments['function'], $in);
}
}
protected function getProxyGenerator(InvokeRenderFunctionInterface $function, iterable $objects): \Generator
{
foreach ($objects as $object) {
yield new RenderableProxy($function, $object);
}
}
}