+ * For the given DOMNode, traverse its children recursively and update IDs
+ * where required (Top-level, headers & elements with IDs).
+ * Will update the provided $changeMap array with changes made, where keys are the old
+ * ids and the corresponding values are the new ids.
+ */
+ protected function updateIdsRecursively(DOMNode $element, int $depth, array &$idMap, array &$changeMap): void
+ {
+ /* @var DOMNode $child */
+ foreach ($element->childNodes as $child) {
+ if ($child instanceof DOMElement && ($depth === 0 || in_array($child->nodeName, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) || $child->getAttribute('id'))) {
+ [$oldId, $newId] = $this->setUniqueId($child, $idMap);
+ if ($newId && $newId !== $oldId && !isset($idMap[$oldId])) {
+ $changeMap[$oldId] = $newId;
+ }
+ }
+
+ if ($child->hasChildNodes()) {
+ $this->updateIdsRecursively($child, $depth + 1, $idMap, $changeMap);
+ }
+ }
+ }
+
+ /**
+ * Update the all links in the given xpath to apply requires changes within the
+ * given $changeMap array.