Skip to content

Commit 221b312

Browse files
committed
Change of heart: offload schema validation to a trait+interface combo for easy re-use
1 parent 419687c commit 221b312

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace SimpleSAML\XML;
6+
7+
use DOMDocument;
8+
9+
/**
10+
* interface class to be implemented by all the classes that can be validated against a schema
11+
*
12+
* @package simplesamlphp/xml-common
13+
*/
14+
interface SchemaValidatableElementInterface extends ElementInterface
15+
{
16+
/**
17+
* Validate the given DOMDocument against the schema set for this element
18+
*
19+
* @return void
20+
* @throws \SimpleSAML\XML\Exception\SchemaViolationException
21+
*/
22+
public static function schemaValidate(DOMDocument $document): DOMDocument;
23+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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

Comments
 (0)