<?php

namespace WPDesk\FakturyKSEF\Xml\Validators;

use DOMDocument;
use Exception;

class XsdValidator {

	private string $schema_path;

	public function __construct( $filename = '' ) {
		if ( $filename ) {
			$this->set_schema_path( __DIR__ . '/files/' . $filename . '.xsd' );
		}
	}

	public function set_schema_path( string $schema_path ): void {
		$this->schema_path = $schema_path;
	}

	public function get_schema_path(): string {
		return $this->schema_path;
	}

	public function schema_validate( DOMDocument $xml ): array {
		if ( ! $this->get_schema_path() || ! file_exists( $this->get_schema_path() ) ) {
			throw new Exception( 'Invalid XSD path.' );
		}
		$errors = [];
		libxml_use_internal_errors( true );
		if ( ! ini_get( 'allow_url_fopen' ) ) {
			return $errors;
		}
		if ( ! $xml->schemaValidate( $this->get_schema_path() ) ) {
			$errors = libxml_get_errors();
			libxml_clear_errors();
		}

		$error_mapper = new XsdErrorMapper( $errors );

		return $error_mapper->get_errors();
	}
}
