diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 599ca0cf..6d3a1348 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -619,9 +619,7 @@ class TemplateProcessor } $result = $this->getSlice(0, $rowStart); - for ($i = 1; $i <= $numberOfClones; $i++) { - $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow); - } + $result .= implode($this->indexClonedVariables($numberOfClones, $xmlRow)); $result .= $this->getSlice($rowEnd); $this->tempDocumentMainPart = $result; @@ -647,10 +645,7 @@ class TemplateProcessor if (isset($matches[3])) { $xmlBlock = $matches[3]; - $cloned = array(); - for ($i = 1; $i <= $clones; $i++) { - $cloned[] = $xmlBlock; - } + $cloned = $this->indexClonedVariables($clones, $xmlBlock); if ($replace) { $this->tempDocumentMainPart = str_replace( @@ -938,4 +933,22 @@ class TemplateProcessor return substr($this->tempDocumentMainPart, $startPosition, ($endPosition - $startPosition)); } + + /** + * Replaces variable names in cloned + * rows/blocks with indexed names + * + * @param integer $count + * @param string $xmlBlock + * + * @return string + */ + protected function indexClonedVariables($count, $xmlBlock) + { + $results = array(); + for ($i = 1; $i <= $count; $i++) { + $results[] = preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlBlock); + } + return $results; + } } diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 73b4910c..36432dc5 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -288,13 +288,14 @@ final class TemplateProcessorTest extends \PHPUnit\Framework\TestCase $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-delete-block.docx'); $this->assertEquals( - array('DELETEME', '/DELETEME', 'CLONEME', '/CLONEME'), + array('DELETEME', '/DELETEME', 'CLONEME', 'blockVariable', '/CLONEME'), $templateProcessor->getVariables() ); $docName = 'clone-delete-block-result.docx'; $templateProcessor->cloneBlock('CLONEME', 3); $templateProcessor->deleteBlock('DELETEME'); + $templateProcessor->setValue('blockVariable#3', 'Test'); $templateProcessor->saveAs($docName); $docFound = file_exists($docName); unlink($docName); diff --git a/tests/PhpWord/_files/templates/clone-delete-block.docx b/tests/PhpWord/_files/templates/clone-delete-block.docx index 049d5ca4..986742e3 100644 Binary files a/tests/PhpWord/_files/templates/clone-delete-block.docx and b/tests/PhpWord/_files/templates/clone-delete-block.docx differ