<?php
/**
 * Utility Dom Class
 *
 * @package errigal-pro
 * @since 1.2.0
 */

namespace Errigal\Shared;

defined( 'ABSPATH' ) || exit;

use Errigal\Shared\Errigal_Validator as Validator;
use DOMDocument;
use DOMElement;

/**
 * This class is in charge of providing DOM functions.
 *
 * @since 1.2.0
 */
class Errigal_Utility_Dom {
	/**
	 * Creates instance of DOMDocument.
	 *
	 * @since 1.2.0
	 *
	 * @return DOMDocument
	 */
	public static function create_dom() {
		return new DOMDocument( '1.0', 'UTF-8' );
	}

	/**
	 * Creates instance of DOMDocument from XML.
	 *
	 * @since 1.2.0
	 *
	 * @param string $source XML string.
	 * @return DOMDocument|null
	 */
	public static function create_dom_from_xml( $source ) {
		if ( ! Validator::is_non_empty_string( $source ) ) {
			return null;
		}

		$dom = self::create_dom();

		if ( ! self::is_dom_document( $dom ) ) {
			return null;
		}

		libxml_use_internal_errors( true );

		if ( ! $dom->loadXML( mb_convert_encoding( $source, 'UTF-8', 'auto' ) ) ) {
			libxml_clear_errors();

			return null;
		}

		return $dom;
	}

	/**
	 * Determines whether $document is instance of DOMDocument.
	 *
	 * @since 1.2.0
	 *
	 * @param DOMDocument $document DOMDocument object.
	 * @return bool
	 */
	public static function is_dom_document( $document ) {
		return $document instanceof DOMDocument;
	}

	/**
	 * Determines whether $element is instance of DOMElement.
	 *
	 * @since 1.2.0
	 *
	 * @param DOMElement $element DOMElement object.
	 * @return bool
	 */
	public static function is_dom_element( $element ) {
		return $element instanceof DOMElement;
	}
}
