<?php

declare(strict_types=1);

namespace App\Framework\View\Processors;

use App\Framework\Template\Processing\DomProcessor;
use App\Framework\View\DomWrapper;
use App\Framework\View\RenderContext;
use Dom\Node;

final class RemoveEmptyLinesProcessor implements DomProcessor
{
    public function process(DomWrapper $dom, RenderContext $context): DomWrapper
    {
        $this->removeEmptyTextNodes($dom->document);

        return $dom;
    }

    private function removeEmptyTextNodes(Node $node): void
    {
        for ($i = $node->childNodes->length - 1; $i >= 0; $i--) {
            $child = $node->childNodes->item($i);

            // Wenn es ein Text-Node ist und nur aus Whitespace besteht
            if ($child->nodeType === XML_TEXT_NODE && preg_match('/^\s*$/', $child->nodeValue)) {
                $node->removeChild($child);
            } elseif ($child->hasChildNodes()) {
                // Rekursion in die Tiefe
                $this->removeEmptyTextNodes($child);
            }
        }
    }
}
