<?php

namespace Fifa\ConnectId\Sdk\Util\XsdSchemaValidator;

use DOMDocument;
use Fifa\ConnectId\Sdk\Model\ValidationResult;
use Fifa\ConnectId\Sdk\Model\XmlValidationError;
use LibXMLError;

/**
 * Class XsdSchemaValidator
 * @package Fifa\ConnectId\Sdk\Util\XsdSchemaValidator
 */
class XsdSchemaValidator implements XsdSchemaValidatorInterface
{
    /**
     * @var string
     */
    private static $xsdSchemaPath;

    /**
     * XsdSchemaValidator constructor.
     */
    public function __construct()
    {
        self::$xsdSchemaPath = XsdSchemasDirectoryResolver::getDirectory() . DIRECTORY_SEPARATOR . 'scenarios.xsd';
    }

    /**
     * @param string $xmlContent
     * @return ValidationResult
     */
    public function validate(string $xmlContent): ValidationResult
    {
        $domDocument = new DOMDocument();
        $domDocument->loadXML($xmlContent);
        $validationErrors = [];

        libxml_use_internal_errors(true);
        $isValid = $domDocument->schemaValidate(self::$xsdSchemaPath);

        if (!$isValid) {
            $libErrors = libxml_get_errors();
            $validationErrors = array_map(function (LibXMLError $libXmlError) {
                return new XmlValidationError($libXmlError);
            }, $libErrors);
        }

        libxml_use_internal_errors(false);
        return new ValidationResult($validationErrors);
    }
}