Skip to content

Commit 4e87e72

Browse files
authored
Merge pull request #1716 from enflow/allowImageClosure
Allow a closure to be passed with image replacement tags
2 parents 8922632 + 6811868 commit 4e87e72

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

docs/templates-processing.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,11 @@ Example:
6363
6464
$templateProcessor->setImageValue('CompanyLogo', 'path/to/company/logo.png');
6565
$templateProcessor->setImageValue('UserLogo', array('path' => 'path/to/logo.png', 'width' => 100, 'height' => 100, 'ratio' => false));
66+
$templateProcessor->setImageValue('FeatureImage', function () {
67+
// Closure will only be executed if the replacement tag is found in the template
68+
69+
return array('path' => SlowFeatureImageGenerator::make(), 'width' => 100, 'height' => 100, 'ratio' => false);
70+
});
6671
6772
cloneBlock
6873
""""""""""

src/PhpWord/TemplateProcessor.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,13 @@ private function prepareImageAttrs($replaceImage, $varInlineArgs)
456456
$width = null;
457457
$height = null;
458458
$ratio = null;
459+
460+
// a closure can be passed as replacement value which after resolving, can contain the replacement info for the image
461+
// use case: only when a image if found, the replacement tags can be generated
462+
if (is_callable($replaceImage)) {
463+
$replaceImage = $replaceImage();
464+
}
465+
459466
if (is_array($replaceImage) && isset($replaceImage['path'])) {
460467
$imgPath = $replaceImage['path'];
461468
if (isset($replaceImage['width'])) {

tests/PhpWord/TemplateProcessorTest.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -397,9 +397,11 @@ public function testSetImageValue()
397397
$imagePath = __DIR__ . '/_files/images/earth.jpg';
398398

399399
$variablesReplace = array(
400-
'headerValue' => $imagePath,
401-
'documentContent' => array('path' => $imagePath, 'width' => 500, 'height' => 500),
402-
'footerValue' => array('path' => $imagePath, 'width' => 100, 'height' => 50, 'ratio' => false),
400+
'headerValue' => function () use ($imagePath) {
401+
return $imagePath;
402+
},
403+
'documentContent' => array('path' => $imagePath, 'width' => 500, 'height' => 500),
404+
'footerValue' => array('path' => $imagePath, 'width' => 100, 'height' => 50, 'ratio' => false),
403405
);
404406
$templateProcessor->setImageValue(array_keys($variablesReplace), $variablesReplace);
405407

0 commit comments

Comments
 (0)