From: Louis Jeckel Date: Wed, 13 Jan 2021 18:18:42 +0000 (+0100) Subject: transform mustache template to mailgun X-Git-Url: http://git.cubedesigners.com/?a=commitdiff_plain;h=195bbdc4a91ddbc6b3ee01faedfbb3eeb031155c;p=psq.git transform mustache template to mailgun --- diff --git a/app/Jobs/ProcessEmailBatch.php b/app/Jobs/ProcessEmailBatch.php index f5ed9c8..3585676 100644 --- a/app/Jobs/ProcessEmailBatch.php +++ b/app/Jobs/ProcessEmailBatch.php @@ -17,6 +17,7 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Arr; +use Illuminate\Support\Str; class ProcessEmailBatch implements ShouldQueue @@ -167,20 +168,24 @@ class ProcessEmailBatch implements ShouldQueue $this->batch->file->publish(); } + $templateVariables = $this->processVariablesForMailgun(); + foreach($chunks as $chunk) { - $variables = json_encode($chunk->mapWithKeys(function (User $user) { + $variables = json_encode($chunk->mapWithKeys(function (User $user) use ($templateVariables){ $fileVar = $this->batch->file === null ? [] : ['file_url' => $this->batch->file->getMailableUrl($user)]; + $filledVariables = array_map(fn($template) => $user->templateAttribute($template), $templateVariables); + return [ $user->email => array_merge([ 'id' => $user->id, 'name' => $user->name ?? '', - ], $fileVar) + ], $fileVar, $filledVariables) ]; }), JSON_THROW_ON_ERROR); @@ -219,4 +224,21 @@ class ProcessEmailBatch implements ShouldQueue $this->batch->update(['sent_to' => $this->users->pluck('email')]); } + + public function processVariablesForMailgun() + { + if($this->html === null) { + return []; + } + $variables = []; + + $this->html = preg_replace_callback('/\{\{[^(% )]*\}\}/', function($matches) use(&$variables){ + + $match = Str::before(Str::after($matches[0], '{{'), '}}'); + $variables[] = $match ; + return "%recipient.$match%"; + }, $this->html); + + return array_unique($variables); + } }