<?php

namespace Planaday\Html\Parsers\NodeParsers;

use DOMCdataSection;
use DOMCharacterData;
use DOMNode;
use Planaday\Html\Nodes\NodeData;
use Planaday\Html\Nodes\ParserNode;
use Planaday\Html\Parsers\StringInterpolationParser;
use Planaday\Utility\DependencyInjection\Attributes\Scoped;

#[Scoped]
class TextNodeContentParser implements NodeParser {

	protected NodeData $nodeData;

	public function __construct( protected StringInterpolationParser $preParser ) {
		$this->nodeData = new NodeData();
	}

	public function setNodeData( NodeData $nodeData ): void {
		$this->nodeData = $nodeData;
	}

	public function modifyNode( DOMNode&ParserNode $node ): void {
		if ( !$node instanceof DOMCharacterData ) {
			return;
		}

		$this->preParser->setNodeData( $this->nodeData );

		if ( $node instanceof DOMCdataSection ) {
			$node->data = $this->preParser->parseCode( $node->data );
			return;
		}

		$node->data = $this->preParser->parse( $node->data );
	}
}