<?php

declare(strict_types=1);

namespace HTMLSax3\Decorators;

/**
 * Strips the HTML comment markers or CDATA sections from an escape.
 * If XML_OPTIONS_FULL_ESCAPES is on, this decorator is not used.<br />
 * @package HTMLSax3
 * @access protected
 */
class Escape_Stripper
{
	/**
	 * Original handler object
	 * @var object
	 * @access private
	 */
	public object $orig_obj;

	/**
	 * Original handler method
	 * @var string
	 * @access private
	 */
	public string $orig_method;

	/**
	 * Constructs Escape_Stripper
	 * @param object $orig_obj handler object being decorated
	 * @param string $orig_method original handler method
	 * @access protected
	 */
	public function __construct(object &$orig_obj, string $orig_method)
	{
		$this->orig_obj    = &$orig_obj;
		$this->orig_method = $orig_method;
	}

	/**
	 * Breaks the data up by XML entities
	 * @param \HTMLSax3\HTMLSax3 $parser
	 * @param string $data element data
	 * @access protected
	 */
	public function strip(\HTMLSax3\HTMLSax3 $parser, string $data): void
	{
		// Check for HTML comments first
		if (str_starts_with($data, '--'))
		{
			$patterns = [
				'/^\-\-/',    // Opening comment: --
				'/\-\-$/',    // Closing comment: --
			];
			$data = preg_replace($patterns, '', $data);

			// Check for XML CDATA sections (note: don't do both!)
		}
		else if (str_starts_with($data, '['))
		{
			$patterns = [
				'/^\[.*CDATA.*\[/s',    // Opening CDATA
				'/\].*\]$/s',           // Closing CDATA
			];
			$data = preg_replace($patterns, '', $data);
		}

		$this->orig_obj->{$this->orig_method}($this, $data);
	}
}
