Skip to content

Commit

Permalink
[BUGFIX] Ensure nested w:sdt -> w:sdtContent node paresing for Docu…
Browse files Browse the repository at this point in the history
…ment

Nodes can be nested or directly provided for the document structure.
Until now, the `sdt->sdtContent` wrapping have not been respected.

This change moves the node parsing for a document to a dedicated
method and make it recursivly callable to unnest the wrapped node.
  • Loading branch information
sbuerk committed Apr 2, 2024
1 parent 8b891bb commit 9f83162
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions src/PhpWord/Reader/Word2007/Document.php
Expand Up @@ -18,6 +18,7 @@
namespace PhpOffice\PhpWord\Reader\Word2007;

use DOMElement;
use DOMNode;
use PhpOffice\PhpWord\Element\Section;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
Expand Down Expand Up @@ -46,15 +47,33 @@ public function read(PhpWord $phpWord): void
$this->phpWord = $phpWord;
$xmlReader = new XMLReader();
$xmlReader->getDomFromZip($this->docFile, $this->xmlFile);
$readMethods = ['w:p' => 'readWPNode', 'w:tbl' => 'readTable', 'w:sectPr' => 'readWSectPrNode'];

$nodes = $xmlReader->getElements('w:body/*');
if ($nodes->length > 0) {
$section = $this->phpWord->addSection();
foreach ($nodes as $node) {
if (isset($readMethods[$node->nodeName])) {
$readMethod = $readMethods[$node->nodeName];
$this->$readMethod($xmlReader, $node, $section);
$this->readNode($phpWord, $xmlReader, $node, $section);
}
}
}

private function readNode(PhpWord $phpWord, XMLReader $xmlReader, DOMNode $node, Section $section): void
{
$readMethods = ['w:p' => 'readWPNode', 'w:tbl' => 'readTable', 'w:sectPr' => 'readWSectPrNode'];
if (isset($readMethods[$node->nodeName])) {
$readMethod = $readMethods[$node->nodeName];
$this->$readMethod($xmlReader, $node, $section);
} elseif ($node->nodeName === 'w:sdt') {
$nodes = $xmlReader->getElements('w:sdtContent/*', $node);

Check failure on line 66 in src/PhpWord/Reader/Word2007/Document.php

View workflow job for this annotation

GitHub Actions / phpstan

Parameter #2 $contextNode of method PhpOffice\PhpWord\Shared\XMLReader::getElements() expects DOMElement|null, DOMNode given.
if ($nodes->length > 0) {
foreach ($nodes as $subNode) {
$this->readNode($phpWord, $xmlReader, $subNode, $section);
}
}
} elseif ($node->nodeName === 'w:sdtContent') {
$nodes = $xmlReader->getElements('*', $node);

Check failure on line 73 in src/PhpWord/Reader/Word2007/Document.php

View workflow job for this annotation

GitHub Actions / phpstan

Parameter #2 $contextNode of method PhpOffice\PhpWord\Shared\XMLReader::getElements() expects DOMElement|null, DOMNode given.
if ($nodes->length > 0) {
foreach ($nodes as $subNode) {
$this->readNode($phpWord, $xmlReader, $subNode, $section);
}
}
}
Expand Down

0 comments on commit 9f83162

Please sign in to comment.