PersonalizeHtmlAction   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 3
dl 0
loc 38
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A replaceSubscriberAttributes() 0 20 2
A execute() 0 14 1
1
<?php
2
3
namespace Spatie\EmailCampaigns\Actions;
4
5
use Spatie\EmailCampaigns\Models\Subscriber;
6
use Spatie\EmailCampaigns\Models\CampaignSend;
7
use Spatie\SchemalessAttributes\SchemalessAttributes;
8
9
class PersonalizeHtmlAction
10
{
11
    public function execute($html, CampaignSend $pendingSend)
12
    {
13
        /** @var \Spatie\EmailCampaigns\Models\Subscription $subscription */
14
        $subscription = $pendingSend->subscription;
15
16
        $html = str_replace('::campaignSendUuid::', $pendingSend->uuid, $html);
17
        $html = str_replace('::subscriptionUuid::', $subscription->uuid, $html);
18
        $html = str_replace('::subscriber.uuid::', $subscription->subscriber->uuid, $html);
19
        $html = str_replace('::unsubscribeUrl::', $subscription->unsubscribeUrl($pendingSend), $html);
20
21
        $html = $this->replaceSubscriberAttributes($html, $subscription->subscriber);
22
23
        return $html;
24
    }
25
26
    protected function replaceSubscriberAttributes(string $html, Subscriber $subscriber): string
27
    {
28
        $html = preg_replace_callback('/::subscriber.([\w.]+)::/', function (array $match) use ($subscriber) {
29
            $parts = collect(explode('.', $match[1] ?? ''));
30
31
            $replace = $parts->reduce(function ($value, $part) {
32
                if ($value instanceof SchemalessAttributes) {
33
                    return $value->get($part);
34
                }
35
36
                return $value->$part
37
                    ?? $value[$part]
38
                    ?? null;
39
            }, $subscriber);
40
41
            return $replace ?? $match;
42
        }, $html);
43
44
        return $html;
45
    }
46
}
47