From 5a68ef600be7423ee5f16579ddce19b7d2b89332 Mon Sep 17 00:00:00 2001 From: Michel Bardelmeijer Date: Mon, 9 Sep 2019 13:49:16 +0200 Subject: [PATCH] Allow a closure to be passed with image replacement tags --- src/PhpWord/TemplateProcessor.php | 7 +++++++ tests/PhpWord/TemplateProcessorTest.php | 8 +++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 7efc0f1a..3af8738c 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -447,6 +447,13 @@ class TemplateProcessor $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'])) { diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 4caca77a..21203234 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -392,9 +392,11 @@ final class TemplateProcessorTest extends \PHPUnit\Framework\TestCase $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);