You are here

public static function Utility::normalizeXml in Search API Solr 8.3

Same name and namespace in other branches
  1. 4.x src/Utility/Utility.php \Drupal\search_api_solr\Utility\Utility::normalizeXml()

Normalize a XML file.

Removes comments from an xml file and removes the 'name' attribute of the root node.

Parameters

string $xml: The XML file to normalize.

Return value

array An array with the version number and the normalized XML.

1 call to Utility::normalizeXml()
search_api_solr_requirements in ./search_api_solr.install
Implements hook_requirements().

File

src/Utility/Utility.php, line 1058

Class

Utility
Provides various helper functions for Solr backends.

Namespace

Drupal\search_api_solr\Utility

Code

public static function normalizeXml($xml) : array {
  $document = new \DOMDocument();
  if (@$document
    ->loadXML($xml) === FALSE) {
    $document
      ->loadXML("<root>{$xml}</root>");
  }
  $version_number = '';
  $root = $document->documentElement;
  if (isset($root) && $root
    ->hasAttribute('name')) {
    $version_number = $root
      ->getAttribute('name');
    $root
      ->removeAttribute('name');
  }
  $xpath = new \DOMXPath($document);

  // Remove all comments.
  foreach ($xpath
    ->query("//comment()") as $comment) {
    $comment->parentNode
      ->removeChild($comment);
  }

  // Trim all whitespaces.
  foreach ($xpath
    ->query('//text()') as $whitespace) {
    $whitespace->data = trim($whitespace->nodeValue);
  }
  return [
    $version_number,
    $document
      ->saveXML(),
  ];
}