Skip to content

Instantly share code, notes, and snippets.

@smichaelsen
Created May 25, 2021 13:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smichaelsen/680e3870f5330c560023161364ce3a34 to your computer and use it in GitHub Desktop.
Save smichaelsen/680e3870f5330c560023161364ce3a34 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace MyVendor\MyExt\ViewHelpers;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
class SignatureViewHelper extends AbstractViewHelper
{
protected const ALWAYS_ALLOWED = ['settings'];
public function initializeArguments()
{
$this->registerArgument('required', 'string', 'Comma separated list of variables that have to be defined in the variables context when this ViewHelper is called', false);
$this->registerArgument('allowed', 'string', 'Comma separated list of variables that can be defined in the variable context', false);
$this->registerArgument('defaultValues', 'array', '', false);
}
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
{
if ($arguments['required']) {
$requiredVariables = GeneralUtility::trimExplode(',', $arguments['required'], true);
foreach ($requiredVariables as $requiredVariableName) {
if (!$renderingContext->getVariableProvider()->exists($requiredVariableName)) {
throw new \Exception('Required fluid variable ' . $requiredVariableName . ' is not available', 1621947254);
}
}
}
if ($arguments['allowed']) {
$allowedVariables = [
...GeneralUtility::trimExplode(',', (string)$arguments['required'], true),
...GeneralUtility::trimExplode(',', $arguments['allowed'], true),
...self::ALWAYS_ALLOWED,
];
foreach ($renderingContext->getVariableProvider()->getAllIdentifiers() as $variableName) {
if (!in_array($variableName, $allowedVariables)) {
throw new \Exception('Variable ' . $variableName . ' was provided but not allowed', 1621948774);
}
}
}
if ($arguments['defaultValues']) {
foreach ($arguments['defaultValues'] as $variableName => $defaultValue) {
if (!$renderingContext->getVariableProvider()->exists($variableName)) {
$renderingContext->getVariableProvider()->add($variableName, $defaultValue);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment