Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Helpers;
- use DOMDocument;
- use InvalidArgumentException;
- use UnexpectedValueException;
- class XmlXsdValidator
- {
- /**
- * XmlXsdValidator constructor.
- */
- public function __construct()
- {
- // Enable user error handling
- libxml_use_internal_errors(true);
- }
- /**
- * Method to validate raw xml data against specified xsd schema.
- *
- * @param $xmlString
- * @param $xsdSchemaPath
- * @return bool
- * @throws Exception
- */
- public function validate($xmlString, $xsdSchemaPath)
- {
- // Validate xml string
- if (empty($xmlString)) {
- throw new InvalidArgumentException('Empty xml string.');
- }
- // Validate xsd schema path
- if (!file_exists($xsdSchemaPath)) {
- throw new InvalidArgumentException('XSD schema file '. (!empty($xsdSchemaPath) ? $xsdSchemaPath : 'N/A') .' does not exist.');
- }
- // Load xml string
- $xml = new DOMDocument();
- $xml->loadXML($xmlString);
- // Validate xml string against xsd schema
- if (!$xml->schemaValidate($xsdSchemaPath))
- {
- // Init validation errors
- $validation_errors = [];
- // Load validation errors
- $errors = libxml_get_errors();
- // Parse validation error messages
- foreach ($errors as $error)
- {
- // Parse error type
- $error_type = '';
- switch ($error->level) {
- case LIBXML_ERR_WARNING:
- $error_type = "Warning $error->code: ";
- break;
- case LIBXML_ERR_ERROR:
- $error_type = "Error $error->code: ";
- break;
- case LIBXML_ERR_FATAL:
- $error_type = "Fatal Error $error->code: ";
- break;
- }
- // Build validation error
- $validation_error = $error_type . $error->message;
- if ($error->file) {
- $validation_error .= ' on file ' . basename($error->file);
- }
- $validation_error .= ' on line #' . $error->line;
- // Append validation error
- $validation_errors[] = $validation_error;
- }
- // Clean-up
- libxml_clear_errors();
- // Error
- throw new UnexpectedValueException('XML validation failed: ' . implode(' | ', $validation_errors));
- }
- // Clean-up
- $xml = null;
- // Success
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement