|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace SimpleSAML\XML; |
| 6 | + |
| 7 | +use DOMDocument; |
| 8 | +use SimpleSAML\Assert\Assert; |
| 9 | +use SimpleSAML\Exception\IOException; |
| 10 | +use SimpleSAML\Exception\SchemaViolationException; |
| 11 | + |
| 12 | +use function array_unique; |
| 13 | +use function defined; |
| 14 | +use function file_exists; |
| 15 | +use function implode; |
| 16 | +use function sprintf; |
| 17 | +use function trim; |
| 18 | +use function libxml_get_errors; |
| 19 | + |
| 20 | +/** |
| 21 | + * trait class to be used by all the classes that implement the SchemaValidatableElementInterface |
| 22 | + * |
| 23 | + * @package simplesamlphp/xml-common |
| 24 | + */ |
| 25 | +trait SchemaValidatableElementTrait |
| 26 | +{ |
| 27 | + /** |
| 28 | + * Validate the given DOMDocument against the schema set for this element |
| 29 | + * |
| 30 | + * @return void |
| 31 | + * @throws \SimpleSAML\XML\Exception\SchemaViolationException |
| 32 | + */ |
| 33 | + public static function schemaValidate(DOMDocument $document): DOMDocument |
| 34 | + { |
| 35 | + $schemaFile = self::getSchemaFile(); |
| 36 | + $result = $document->schemaValidate($schemaFile); |
| 37 | + |
| 38 | + if ($result === false) { |
| 39 | + $msgs = []; |
| 40 | + foreach (libxml_get_errors() as $err) { |
| 41 | + $msgs[] = trim($err->message) . ' on line ' . $err->line; |
| 42 | + } |
| 43 | + |
| 44 | + throw new SchemaViolationException(sprintf( |
| 45 | + "XML schema validation errors:\n - %s", |
| 46 | + implode("\n - ", array_unique($msgs)), |
| 47 | + )); |
| 48 | + } |
| 49 | + |
| 50 | + return $document; |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | + /** |
| 55 | + * Get the schema file that can validate this element. |
| 56 | + * |
| 57 | + * @return string |
| 58 | + */ |
| 59 | + public static function getSchemaFile(): string |
| 60 | + { |
| 61 | + if (defined('static::SCHEMA')) { |
| 62 | + $schemaFile = static::SCHEMA; |
| 63 | + } |
| 64 | + |
| 65 | + Assert::true(file_exists($schemaFile), IOException::class); |
| 66 | + return $schemaFile; |
| 67 | + } |
| 68 | +} |
0 commit comments