Skip to content

Commit affccc7

Browse files
committed
Merge branch 'improve-cloneBlock-regex' of https://github.com/nicoder/PHPWord into fix_clone_block
2 parents 4c9e750 + 4105a9a commit affccc7

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

src/PhpWord/TemplateProcessor.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ public function cloneBlock($blockname, $clones = 1, $replace = true)
323323
{
324324
$xmlBlock = null;
325325
preg_match(
326-
'/(<\?xml.*)(<w:p.*>\${' . $blockname . '}<\/w:.*?p>)(.*)(<w:p.*\${\/' . $blockname . '}<\/w:.*?p>)/is',
326+
'/(<\?xml.*)(<w:p\b.*>\${' . $blockname . '}<\/w:.*?p>)(.*)(<w:p\b.*\${\/' . $blockname . '}<\/w:.*?p>)/is',
327327
$this->tempDocumentMainPart,
328328
$matches
329329
);

tests/PhpWord/TemplateProcessorTest.php

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,4 +223,56 @@ public function testCloneDeleteBlock()
223223
unlink($docName);
224224
$this->assertTrue($docFound);
225225
}
226+
227+
/**
228+
* @covers ::cloneBlock
229+
* @test
230+
*/
231+
public function cloneBlockCanCloneABlockTwice()
232+
{
233+
// create template with placeholders and block
234+
$phpWord = new PhpWord();
235+
$section = $phpWord->addSection();
236+
$documentElements = array(
237+
'Title: ${title}',
238+
'${subreport}',
239+
'${subreport.id}: ${subreport.text}. ',
240+
'${/subreport}',
241+
);
242+
foreach ($documentElements as $documentElement) {
243+
$section->addText($documentElement);
244+
}
245+
$objWriter = IOFactory::createWriter($phpWord);
246+
$templatePath = 'test.docx';
247+
$objWriter->save($templatePath);
248+
249+
// replace placeholders and save the file
250+
$templateProcessor = new TemplateProcessor($templatePath);
251+
$templateProcessor->setValue('title', 'Some title');
252+
$templateProcessor->cloneBlock('subreport', 2);
253+
$templateProcessor->setValue('subreport.id', '123', 1);
254+
$templateProcessor->setValue('subreport.text', 'Some text', 1);
255+
$templateProcessor->setValue('subreport.id', '456', 1);
256+
$templateProcessor->setValue('subreport.text', 'Some other text', 1);
257+
$templateProcessor->saveAs($templatePath);
258+
259+
// assert the block has been cloned twice
260+
// and the placeholders have been replaced correctly
261+
$phpWord = IOFactory::load($templatePath);
262+
$sections = $phpWord->getSections();
263+
$actualElements = $sections[0]->getElements();
264+
unlink($templatePath);
265+
$expectedElements = array(
266+
'Title: Some title',
267+
'123: Some text. ',
268+
'456: Some other text. ',
269+
);
270+
$this->assertCount(count($expectedElements), $actualElements);
271+
foreach ($expectedElements as $i => $expectedElement) {
272+
$this->assertEquals(
273+
$expectedElement,
274+
$actualElements[$i]->getText()
275+
);
276+
}
277+
}
226278
}

0 commit comments

Comments
 (0)