diff --git a/src/Parser/MjmlParser.php b/src/Parser/MjmlParser.php
index ef99eb0..935e3a1 100644
--- a/src/Parser/MjmlParser.php
+++ b/src/Parser/MjmlParser.php
@@ -82,6 +82,7 @@ public function parse(string $mjml, ?string $filePath = null): Node
$doc->loadXML($mjml, \LIBXML_NONET | \LIBXML_NOWARNING);
$collector->collect(restorePrevious: true);
+ $this->assertReadable($filePath);
$root = $doc->documentElement;
@@ -335,6 +336,7 @@ private function parseIncludeContent(string $mjml, string $filePath): Node
$doc->loadXML($mjml, \LIBXML_NONET | \LIBXML_NOWARNING);
$collector->collect();
+ $this->assertReadable($filePath);
$root = $doc->documentElement;
@@ -345,6 +347,24 @@ private function parseIncludeContent(string $mjml, string $filePath): Node
return $this->domToNode($root, $filePath);
}
+ /**
+ * A fatal libxml error leaves no usable tree, so rendering on would produce an empty email.
+ *
+ * @throws ParseException
+ */
+ private function assertReadable(?string $filePath): void
+ {
+ if (!$this->libxmlErrors->hasFatalErrors()) {
+ return;
+ }
+
+ $source = $filePath !== null ? " in {$filePath}" : '';
+
+ throw new ParseException(
+ "Malformed MJML{$source}: " . implode('; ', $this->libxmlErrors->getErrorMessages()),
+ );
+ }
+
/**
* Merge accumulated CSS includes into the mj-head node.
*
diff --git a/tests/Unit/Parser/MjmlParserTest.php b/tests/Unit/Parser/MjmlParserTest.php
index 2664ac0..9dd0d3f 100644
--- a/tests/Unit/Parser/MjmlParserTest.php
+++ b/tests/Unit/Parser/MjmlParserTest.php
@@ -6,8 +6,10 @@
use PHPUnit\Framework\TestCase;
use MjmlPHP\Component\ComponentRegistry;
+use MjmlPHP\Mjml;
use MjmlPHP\MjmlOptions;
use MjmlPHP\Parser\MjmlParser;
+use MjmlPHP\Parser\ParseException;
use MjmlPHP\Validation\ValidationLevel;
final class MjmlParserTest extends TestCase
@@ -769,6 +771,34 @@ public function testWhitespaceOnlyInputProducesEmptyMjmlNode(): void
self::assertSame([], $node->children);
}
+ public function testMissingClosingTagThrows(): void
+ {
+ $this->expectException(ParseException::class);
+ $this->expectExceptionMessageMatches('/^Malformed MJML: \[FATAL\] line 1: Opening and ending tag mismatch/');
+
+ $this->parser->parse('Hi');
+ }
+
+ public function testBareAmpersandInAttributeThrows(): void
+ {
+ $this->expectException(ParseException::class);
+ $this->expectExceptionMessageMatches('/EntityRef/');
+
+ $this->parser->parse('Go');
+ }
+
+ public function testRenderThrowsForMalformedMarkupInEveryValidationLevel(): void
+ {
+ foreach (ValidationLevel::cases() as $level) {
+ try {
+ Mjml::render('', new MjmlOptions(validationLevel: $level));
+ self::fail("Expected a ParseException with validation level {$level->value}.");
+ } catch (ParseException $exception) {
+ self::assertStringStartsWith('Malformed MJML: ', $exception->getMessage());
+ }
+ }
+ }
+
public function testDeeplyNestedSectionsDoNotCrash(): void
{
// 50 nested wrappers — well below libxml limits but still non-trivial