Skip to content

Commit f51422a

Browse files
committed
add variable indexing for block cloning
Use the same functionality from cloneRow to index variables inside cloned block sections
1 parent c6fff31 commit f51422a

File tree

3 files changed

+22
-8
lines changed

3 files changed

+22
-8
lines changed

src/PhpWord/TemplateProcessor.php

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -274,9 +274,7 @@ public function cloneRow($search, $numberOfClones)
274274
}
275275

276276
$result = $this->getSlice(0, $rowStart);
277-
for ($i = 1; $i <= $numberOfClones; $i++) {
278-
$result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow);
279-
}
277+
$result .= implode($this->indexClonedVariables($numberOfClones, $xmlRow));
280278
$result .= $this->getSlice($rowEnd);
281279

282280
$this->tempDocumentMainPart = $result;
@@ -302,10 +300,7 @@ public function cloneBlock($blockname, $clones = 1, $replace = true)
302300

303301
if (isset($matches[3])) {
304302
$xmlBlock = $matches[3];
305-
$cloned = array();
306-
for ($i = 1; $i <= $clones; $i++) {
307-
$cloned[] = $xmlBlock;
308-
}
303+
$cloned = $this->indexClonedVariables($clones, $xmlBlock);
309304

310305
if ($replace) {
311306
$this->tempDocumentMainPart = str_replace(
@@ -545,4 +540,22 @@ protected function getSlice($startPosition, $endPosition = 0)
545540

546541
return substr($this->tempDocumentMainPart, $startPosition, ($endPosition - $startPosition));
547542
}
543+
544+
/**
545+
* Replaces variable names in cloned
546+
* rows/blocks with indexed names
547+
*
548+
* @param integer $count
549+
* @param string $xmlBlock
550+
*
551+
* @return string
552+
*/
553+
protected function indexClonedVariables($count, $xmlBlock)
554+
{
555+
$results = [];
556+
for ($i = 1; $i <= $count; $i++) {
557+
$results[] = preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlBlock);
558+
}
559+
return $results;
560+
}
548561
}

tests/PhpWord/TemplateProcessorTest.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,13 +199,14 @@ public function testCloneDeleteBlock()
199199
$templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-delete-block.docx');
200200

201201
$this->assertEquals(
202-
array('DELETEME', '/DELETEME', 'CLONEME', '/CLONEME'),
202+
array('DELETEME', '/DELETEME', 'CLONEME', 'blockVariable', '/CLONEME'),
203203
$templateProcessor->getVariables()
204204
);
205205

206206
$docName = 'clone-delete-block-result.docx';
207207
$templateProcessor->cloneBlock('CLONEME', 3);
208208
$templateProcessor->deleteBlock('DELETEME');
209+
$templateProcessor->setValue('blockVariable#3', 'Test');
209210
$templateProcessor->saveAs($docName);
210211
$docFound = file_exists($docName);
211212
unlink($docName);
Binary file not shown.

0 commit comments

Comments
 (0)