Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions src/PhpWord/TemplateProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -274,9 +274,7 @@ public function cloneRow($search, $numberOfClones)
}

$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;
Expand All @@ -302,10 +300,7 @@ public function cloneBlock($blockname, $clones = 1, $replace = true)

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(
Expand Down Expand Up @@ -545,4 +540,22 @@ protected function getSlice($startPosition, $endPosition = 0)

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;
}
}
3 changes: 2 additions & 1 deletion tests/PhpWord/TemplateProcessorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -199,13 +199,14 @@ public function testCloneDeleteBlock()
$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);
Expand Down
Binary file modified tests/PhpWord/_files/templates/clone-delete-block.docx
Binary file not shown.