Skip to content

Commit

Permalink
Change of heart: offload schema validation to a trait+interface combo…
Browse files Browse the repository at this point in the history
… for easy re-use
  • Loading branch information
tvdijen committed Dec 16, 2024
1 parent 419687c commit 221b312
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/SchemaValidatableElementInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace SimpleSAML\XML;

use DOMDocument;

/**
* interface class to be implemented by all the classes that can be validated against a schema
*
* @package simplesamlphp/xml-common
*/
interface SchemaValidatableElementInterface extends ElementInterface
{
/**
* Validate the given DOMDocument against the schema set for this element
*
* @return void
* @throws \SimpleSAML\XML\Exception\SchemaViolationException
*/
public static function schemaValidate(DOMDocument $document): DOMDocument;
}
68 changes: 68 additions & 0 deletions src/SchemaValidatableElementTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

declare(strict_types=1);

namespace SimpleSAML\XML;

use DOMDocument;
use SimpleSAML\Assert\Assert;
use SimpleSAML\Exception\IOException;
use SimpleSAML\Exception\SchemaViolationException;

use function array_unique;
use function defined;
use function file_exists;
use function implode;
use function sprintf;
use function trim;
use function libxml_get_errors;

/**
* trait class to be used by all the classes that implement the SchemaValidatableElementInterface
*
* @package simplesamlphp/xml-common
*/
trait SchemaValidatableElementTrait
{
/**
* Validate the given DOMDocument against the schema set for this element
*
* @return void
* @throws \SimpleSAML\XML\Exception\SchemaViolationException
*/
public static function schemaValidate(DOMDocument $document): DOMDocument
{
$schemaFile = self::getSchemaFile();
$result = $document->schemaValidate($schemaFile);

if ($result === false) {
$msgs = [];
foreach (libxml_get_errors() as $err) {
$msgs[] = trim($err->message) . ' on line ' . $err->line;
}

throw new SchemaViolationException(sprintf(
"XML schema validation errors:\n - %s",
implode("\n - ", array_unique($msgs)),
));
}

return $document;
}


/**
* Get the schema file that can validate this element.
*
* @return string
*/
public static function getSchemaFile(): string
{
if (defined('static::SCHEMA')) {
$schemaFile = static::SCHEMA;
}

Assert::true(file_exists($schemaFile), IOException::class);
return $schemaFile;
}
}

0 comments on commit 221b312

Please sign in to comment.