Skip to content

Allow a closure to be passed with image replacement tags #1716

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 5, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions docs/templates-processing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ Example:

$templateProcessor->setImageValue('CompanyLogo', 'path/to/company/logo.png');
$templateProcessor->setImageValue('UserLogo', array('path' => 'path/to/logo.png', 'width' => 100, 'height' => 100, 'ratio' => false));
$templateProcessor->setImageValue('FeatureImage', function () {
// Closure will only be executed if the replacement tag is found in the template

return array('path' => SlowFeatureImageGenerator::make(), 'width' => 100, 'height' => 100, 'ratio' => false);
});

cloneBlock
""""""""""
Expand Down
7 changes: 7 additions & 0 deletions src/PhpWord/TemplateProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,13 @@ private function prepareImageAttrs($replaceImage, $varInlineArgs)
$width = null;
$height = null;
$ratio = null;

// a closure can be passed as replacement value which after resolving, can contain the replacement info for the image
// use case: only when a image if found, the replacement tags can be generated
if (is_callable($replaceImage)) {
$replaceImage = $replaceImage();
}

if (is_array($replaceImage) && isset($replaceImage['path'])) {
$imgPath = $replaceImage['path'];
if (isset($replaceImage['width'])) {
Expand Down
8 changes: 5 additions & 3 deletions tests/PhpWord/TemplateProcessorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -392,9 +392,11 @@ public function testSetImageValue()
$imagePath = __DIR__ . '/_files/images/earth.jpg';

$variablesReplace = array(
'headerValue' => $imagePath,
'documentContent' => array('path' => $imagePath, 'width' => 500, 'height' => 500),
'footerValue' => array('path' => $imagePath, 'width' => 100, 'height' => 50, 'ratio' => false),
'headerValue' => function () use ($imagePath) {
return $imagePath;
},
'documentContent' => array('path' => $imagePath, 'width' => 500, 'height' => 500),
'footerValue' => array('path' => $imagePath, 'width' => 100, 'height' => 50, 'ratio' => false),
);
$templateProcessor->setImageValue(array_keys($variablesReplace), $variablesReplace);

Expand Down