Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
28 changes: 22 additions & 6 deletions src/PhpWord/TemplateProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -233,23 +233,39 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_
}

/**
* Returns array of all variables in template.
* Returns count of all variables in template.
*
* @return string[]
* @return array
*/
public function getVariables()
public function getVariableCount()
{
$variables = $this->getVariablesForPart($this->tempDocumentMainPart);

foreach ($this->tempDocumentHeaders as $headerXML) {
$variables = array_merge($variables, $this->getVariablesForPart($headerXML));
$variables = array_merge(
$variables,
$this->getVariablesForPart($headerXML)
);
}

foreach ($this->tempDocumentFooters as $footerXML) {
$variables = array_merge($variables, $this->getVariablesForPart($footerXML));
$variables = array_merge(
$variables,
$this->getVariablesForPart($footerXML)
);
}

return array_unique($variables);
return array_count_values($variables);
}

/**
* Returns array of all variables in template.
*
* @return string[]
*/
public function getVariables()
{
return array_keys($this->getVariableCount());
}

/**
Expand Down
38 changes: 38 additions & 0 deletions tests/PhpWord/TemplateProcessorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -223,4 +223,42 @@ public function testCloneDeleteBlock()
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);

$templateProcessor = new TemplateProcessor($templatePath);
$variableCount = $templateProcessor->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
);
}
}