<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use Internetgalerie\IgDatapoolFe\Utility\NeedfulThings;

/**
 * Validation results view helper
 *
 * @api
 * @author     Markus Baumgartner <mb@stylesheep.ch>, Internetgalerie AG
 * @package    IgDatapoolFE
 * @subpackage ViewHelpers
 */
class ValidationResultsViewHelper extends \Internetgalerie\IgCoreViewhelpers\ViewHelpers\Form\ValidationResultsViewHelper
{
    public function initializeArguments(): void
    {
        parent::initializeArguments();
    }


    /**
     * Iterates through selected errors of the request.
     *
     * @return string Rendered string
     * @api
     */
    public function render(): string
    {
        if (($res = trim((string) parent::render($this->arguments['for'], $this->arguments['as']))) != '') {
            return $res;
        }
        //$validationResults = $this->renderingContext->getRequest()->getOriginalRequestMappingResults()->forProperty($for)->getFlattenedErrors();
        $for = $this->arguments['for'];
        $validationResults = $this->renderingContext->getRequest()->getAttribute('extbase')->getOriginalRequestMappingResults()->forProperty($for)->getFlattenedErrors();
        if (!$validationResults) {
            return '';
        }
        $out = '<ul class="dp-errorBox">';

        foreach ($validationResults as $field => $result) {
            $label = NeedfulThings::getFieldLabelByProperty($field);

            foreach ($result as $error) {
                $out .= '<li>' . ($label != '' ? (htmlspecialchars((string) $label) . ': ') : '') . htmlspecialchars((string) $error->render()) . '</li>';
            }
        }
        $out .= '</ul>';
        return $out;
    }
}
