@@ -82,7 +82,7 @@ public function encode(mixed $data, string $format, array $context = []): string
82
82
$ encoderIgnoredNodeTypes = $ context [self ::ENCODER_IGNORED_NODE_TYPES ] ?? $ this ->defaultContext [self ::ENCODER_IGNORED_NODE_TYPES ];
83
83
$ ignorePiNode = \in_array (\XML_PI_NODE , $ encoderIgnoredNodeTypes , true );
84
84
if ($ data instanceof \DOMDocument) {
85
- return $ data -> saveXML ( $ ignorePiNode ? $ data ->documentElement : null );
85
+ return $ this -> saveXml ( $ data , $ ignorePiNode ? $ data ->documentElement : null );
86
86
}
87
87
88
88
$ xmlRootNodeName = $ context [self ::ROOT_NODE_NAME ] ?? $ this ->defaultContext [self ::ROOT_NODE_NAME ];
@@ -97,7 +97,7 @@ public function encode(mixed $data, string $format, array $context = []): string
97
97
$ this ->appendNode ($ dom , $ data , $ format , $ context , $ xmlRootNodeName );
98
98
}
99
99
100
- return $ dom -> saveXML ( $ ignorePiNode ? $ dom ->documentElement : null , $ context [self ::SAVE_OPTIONS ] ?? $ this ->defaultContext [self ::SAVE_OPTIONS ]);
100
+ return $ this -> saveXml ( $ dom , $ ignorePiNode ? $ dom ->documentElement : null , $ context [self ::SAVE_OPTIONS ] ?? $ this ->defaultContext [self ::SAVE_OPTIONS ]);
101
101
}
102
102
103
103
public function decode (string $ data , string $ format , array $ context = []): mixed
@@ -498,4 +498,23 @@ private function createDomDocument(array $context): \DOMDocument
498
498
499
499
return $ document ;
500
500
}
501
+
502
+ /**
503
+ * @throws NotEncodableValueException
504
+ */
505
+ private function saveXml (\DOMDocument $ document , ?\DOMNode $ node = null , ?int $ options = null ): string
506
+ {
507
+ $ prevErrorHandler = set_error_handler (static function ($ type , $ message , $ file , $ line , $ context = []) use (&$ prevErrorHandler ) {
508
+ if (\E_ERROR === $ type || \E_WARNING === $ type ) {
509
+ throw new NotEncodableValueException ($ message );
510
+ }
511
+
512
+ return $ prevErrorHandler ? $ prevErrorHandler ($ type , $ message , $ file , $ line , $ context ) : false ;
513
+ });
514
+ try {
515
+ return $ document ->saveXML ($ node , $ options );
516
+ } finally {
517
+ restore_error_handler ();
518
+ }
519
+ }
501
520
}
0 commit comments