ew_base/Classes/ViewHelpers/Array/ExplodeViewHelper.php
2024-05-25 16:24:24 +02:00

90 lines
2.8 KiB
PHP
Executable File

<?php
/*
* This file is developed by evoWeb.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*/
namespace Evoweb\EwBase\ViewHelpers\Array;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
/**
* Explode ViewHelper
*
* Explodes a string by $glue.
*
* {data.header -> ewb:iterator.explode(glue: 'constant:LF')}
*
* <ewb:iterator.explode content="{data.header}" as="as" glue="constant:LF">
* <span>{as}</span>
* </ewb:iterator.explode>
*/
class ExplodeViewHelper extends AbstractViewHelper
{
use CompileWithRenderStatic;
protected static string $method = 'explode';
public function initializeArguments(): void
{
$this->registerArgument(
'as',
'string',
'Template variable name to assign; if not specified the ViewHelper returns the variable instead.',
);
$this->registerArgument('content', 'string', 'String to be exploded by glue');
$this->registerArgument(
'glue',
'string',
'String used as glue in the string to be exploded. Use glue value of "constant:NAMEOFCONSTANT" '
. '(fx "constant:LF" for linefeed as glue)',
false,
','
);
}
public static function renderStatic(
array $arguments,
\Closure $renderChildrenClosure,
RenderingContextInterface $renderingContext
): mixed {
$content = $arguments['content'] ?? $renderChildrenClosure();
$glue = static::resolveGlue($arguments);
$content = call_user_func_array(static::$method, [$glue, $content]);
$as = $arguments['as'];
if ($as !== null) {
$templateVariableContainer = $renderingContext->getVariableProvider();
$templateVariableContainer->add($as, $content);
$output = $renderChildrenClosure();
$templateVariableContainer->remove($as);
} else {
$output = $content;
}
return $output;
}
protected static function resolveGlue(array $arguments): string
{
$glue = $arguments['glue'];
if (str_contains($glue, ':') && strlen($glue) > 1) {
// glue contains a special type identifier, resolve the actual glue
[$type, $value] = explode(':', $glue);
$glue = match ($type) {
'constant' => constant($value),
default => $value,
};
}
return $glue;
}
}