Skip to content

Commit

Permalink
Validate XML mapping against XSD file
Browse files Browse the repository at this point in the history
  • Loading branch information
greg0ire committed Sep 25, 2017
1 parent 1d5c87e commit e71713a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -837,6 +837,7 @@ private function _getCascadeMappings(SimpleXMLElement $cascadeElement)
*/
protected function loadMappingFile($file)
{
$this->assertValid($file);
$result = [];
// Note: we do not use `simplexml_load_file()` because of https://bugs.php.net/bug.php?id=62577
$xmlElement = simplexml_load_string(file_get_contents($file));
Expand All @@ -861,6 +862,21 @@ protected function loadMappingFile($file)
return $result;
}

private function assertValid(string $file): void
{
$backedUpErrorSetting = libxml_use_internal_errors(true);
$document = new \DOMDocument();
$document->load($file);
if (!$document->schemaValidate(__DIR__ . '/../../../../../doctrine-mapping.xsd')) {
$errors = libxml_get_errors();
libxml_clear_errors();
libxml_use_internal_errors(false);
throw MappingException::fromLibXmlErrors($errors);
}
libxml_clear_errors();
libxml_use_internal_errors(false);
}

/**
* @param mixed $element
*
Expand Down
17 changes: 17 additions & 0 deletions lib/Doctrine/ORM/Mapping/MappingException.php
Original file line number Diff line number Diff line change
Expand Up @@ -820,4 +820,21 @@ public static function infiniteEmbeddableNesting($className, $propertyName)
)
);
}

/**
* @param LibXMLError[] $errors
*/
public static function fromLibXmlErrors(array $errors) : self
{
return new self(array_reduce(array_map(function (\LibXMLError $error) : string {
return sprintf(
'libxml error: %s%s:%d',
$error->message,
$error->file,
$error->line
);
}, $errors), function ($previousMessage, $currentMessage) : string {
return $previousMessage . PHP_EOL . $currentMessage;
}, ''));
}
}

0 comments on commit e71713a

Please sign in to comment.