1. <?php
  2. /**
  3. * Deserializes DOM elements from input, with defensive checks.
  4. *
  5. * @param string $input The input string containing DOM element data.
  6. * @return DOMDocument|null A DOMDocument object if deserialization is successful, or null on failure.
  7. */
  8. function deserializeDomElement(string $input): ?DOMDocument
  9. {
  10. // Defensive check: Ensure input is not empty.
  11. if (empty($input)) {
  12. error_log("deserializeDomElement: Input is empty.");
  13. return null;
  14. }
  15. // Validate input format (basic check for XML-like structure)
  16. if (!preg_match('/^<[^>]+>$', $input)) {
  17. error_log("deserializeDomElement: Invalid input format.");
  18. return null;
  19. }
  20. try {
  21. // Attempt to create a DOMDocument object.
  22. $dom = new DOMDocument();
  23. $dom->loadXML($input);
  24. // Defensive check: Check if the DOMDocument was successfully loaded.
  25. if ($dom->hasErrors()) {
  26. error_log("deserializeDomElement: DOMDocument loading failed: " . $dom->formatErrors(XML_FORMAT_DEBUG_XML));
  27. return null;
  28. }
  29. return $dom;
  30. } catch (Exception $e) {
  31. error_log("deserializeDomElement: Exception during deserialization: " . $e->getMessage());
  32. return null;
  33. }
  34. }
  35. // Example Usage (for testing)
  36. /*
  37. $input = '<root><element attribute="value">Content</element></root>';
  38. $dom = deserializeDomElement($input);
  39. if ($dom) {
  40. echo "Deserialization successful.\n";
  41. print_r($dom->documentElement);
  42. } else {
  43. echo "Deserialization failed.\n";
  44. }
  45. */
  46. ?>

Add your comment