You are here

public static function Utility::normalizeXml in Search API Solr 4.x

Same name and namespace in other branches
  1. 8.3 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 1131

Class

Utility
Provides various helper functions for Solr backends.

Namespace

Drupal\search_api_solr\Utility

Code

public static function normalizeXml($xml) : array {
  if ($xml = trim($xml)) {
    $document = new \DOMDocument();
    if (@$document
      ->loadXML($xml) === FALSE) {
      $document
        ->loadXML("<root>{$xml}</root>");
    }
    $version_number = '';
    $root = $document->documentElement;
    if (isset($root) && $root
      ->hasAttribute('name')) {
      $parts = explode('-', $root
        ->getAttribute('name'));
      if (isset($parts[4])) {

        // Remove jump-start config-set flag.
        unset($parts[4]);
      }
      $version_number = implode('-', $parts);
      $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(),
    ];
  }
  return [
    '',
    '',
  ];
}