<?php

declare(strict_types=1);

namespace Vendor\MyExtension\ViewHelpers\Page;

use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

/**
 * Get a page row property, inherited up through the rootline.
 *
 * When a value is NULL or an empty string "", then the parent page's
 * value is used.
 *
 * The column must be in the rootline already.
 * This can be configured via TYPO3_CONF_VARS[FE][addRootLineFields].
 */
class InheritedPropertyViewHelper extends AbstractViewHelper
{
    protected $escapeOutput = false;

    public function initializeArguments(): void
    {
        $this->registerArgument(
            'column',
            'string',
            'Page row column name',
            true,
        );
        $this->registerArgument(
            'default',
            'string',
            'Fallback value when all pages have an empty value',
            true,
        );
    }

    public function render(): mixed
    {
        $column = $this->arguments['column'];
        $rootLine = $this->getRootLine();

        foreach ($rootLine as $pageRow) {
            if (!array_key_exists($column, $pageRow)) {
                throw new \OutOfRangeException(
                    'Column is not part of the rootline: ' . $column,
                    1758882723
                );
            }

            if ($pageRow[$column] !== null && $pageRow[$column] !== '') {
                return $pageRow[$column];
            }
        }

        return $this->arguments['default'];
    }

    protected function getRootLine(): array
    {
        return $this->getFrontendController()->rootLine;
    }

    protected function getFrontendController(): TypoScriptFrontendController
    {
        return $GLOBALS['TSFE'];
    }
}
