add `getVariableCount` method to `TemplateProcessor`

returns how many times each placeholder is present in the document

almost the same code as `getVariables`

useful when cloning a block a number of times and want to replace
placeholders that are present more than once in the block
(using the `$limit` parameter of `setValue`)
This commit is contained in:
Nicolas Dermine 2018-02-05 17:45:24 +01:00
parent cf6319d7d4
commit 07e97c38cd
2 changed files with 63 additions and 0 deletions

View File

@ -232,6 +232,32 @@ class TemplateProcessor
$this->tempDocumentFooters = $this->setValueForPart($search, $replace, $this->tempDocumentFooters, $limit);
}
/**
* Returns count of all variables in template.
*
* @return array
*/
public function getVariableCount()
{
$variables = $this->getVariablesForPart($this->tempDocumentMainPart);
foreach ($this->tempDocumentHeaders as $headerXML) {
$variables = array_merge(
$variables,
$this->getVariablesForPart($headerXML)
);
}
foreach ($this->tempDocumentFooters as $footerXML) {
$variables = array_merge(
$variables,
$this->getVariablesForPart($footerXML)
);
}
return array_count_values($variables);
}
/**
* Returns array of all variables in template.
*

View File

@ -223,4 +223,41 @@ final class TemplateProcessorTest extends \PHPUnit\Framework\TestCase
unlink($docName);
$this->assertTrue($docFound);
}
/**
* @covers ::getVariableCount
* @test
*/
public function getVariableCountCountsHowManyTimesEachPlaceholderIsPresent()
{
// create template with placeholders
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$header = $section->addHeader();
$header->addText('${a_field_that_is_present_three_times}');
$footer = $section->addFooter();
$footer->addText('${a_field_that_is_present_twice}');
$section2 = $phpWord->addSection();
$section2->addText('
${a_field_that_is_present_one_time}
${a_field_that_is_present_three_times}
${a_field_that_is_present_twice}
${a_field_that_is_present_three_times}
');
$objWriter = IOFactory::createWriter($phpWord);
$templatePath = 'test.docx';
$objWriter->save($templatePath);
$variableCount = (new TemplateProcessor($templatePath))->getVariableCount();
unlink($templatePath);
$this->assertEquals(
array(
'a_field_that_is_present_three_times' => 3,
'a_field_that_is_present_twice' => 2,
'a_field_that_is_present_one_time' => 1,
),
$variableCount
);
}
}