Merge branch 'improve-cloneBlock-regex' of https://github.com/nicoder/PHPWord into fix_clone_block

This commit is contained in:
troosan 2018-07-17 08:03:35 +02:00
commit affccc7937
2 changed files with 53 additions and 1 deletions

View File

@ -323,7 +323,7 @@ class TemplateProcessor
{ {
$xmlBlock = null; $xmlBlock = null;
preg_match( preg_match(
'/(<\?xml.*)(<w:p.*>\${' . $blockname . '}<\/w:.*?p>)(.*)(<w:p.*\${\/' . $blockname . '}<\/w:.*?p>)/is', '/(<\?xml.*)(<w:p\b.*>\${' . $blockname . '}<\/w:.*?p>)(.*)(<w:p\b.*\${\/' . $blockname . '}<\/w:.*?p>)/is',
$this->tempDocumentMainPart, $this->tempDocumentMainPart,
$matches $matches
); );

View File

@ -223,4 +223,56 @@ final class TemplateProcessorTest extends \PHPUnit\Framework\TestCase
unlink($docName); unlink($docName);
$this->assertTrue($docFound); $this->assertTrue($docFound);
} }
/**
* @covers ::cloneBlock
* @test
*/
public function cloneBlockCanCloneABlockTwice()
{
// create template with placeholders and block
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$documentElements = array(
'Title: ${title}',
'${subreport}',
'${subreport.id}: ${subreport.text}. ',
'${/subreport}',
);
foreach ($documentElements as $documentElement) {
$section->addText($documentElement);
}
$objWriter = IOFactory::createWriter($phpWord);
$templatePath = 'test.docx';
$objWriter->save($templatePath);
// replace placeholders and save the file
$templateProcessor = new TemplateProcessor($templatePath);
$templateProcessor->setValue('title', 'Some title');
$templateProcessor->cloneBlock('subreport', 2);
$templateProcessor->setValue('subreport.id', '123', 1);
$templateProcessor->setValue('subreport.text', 'Some text', 1);
$templateProcessor->setValue('subreport.id', '456', 1);
$templateProcessor->setValue('subreport.text', 'Some other text', 1);
$templateProcessor->saveAs($templatePath);
// assert the block has been cloned twice
// and the placeholders have been replaced correctly
$phpWord = IOFactory::load($templatePath);
$sections = $phpWord->getSections();
$actualElements = $sections[0]->getElements();
unlink($templatePath);
$expectedElements = array(
'Title: Some title',
'123: Some text. ',
'456: Some other text. ',
);
$this->assertCount(count($expectedElements), $actualElements);
foreach ($expectedElements as $i => $expectedElement) {
$this->assertEquals(
$expectedElement,
$actualElements[$i]->getText()
);
}
}
} }