Test Setup Failed
Push — ft/duplicate-page ( 3cb9e2 )
by Ben
65:03 queued 56:56
created

ModuleTemplateApplicator   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 16
c 1
b 0
f 0
dl 0
loc 45
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
B handle() 0 32 8
A __construct() 0 2 1
A shouldApply() 0 3 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Thinktomorrow\Chief\Templates;
5
6
use Thinktomorrow\Chief\DynamicAttributes\DynamicAttributes;
7
use Thinktomorrow\Chief\Modules\Module;
8
use Webmozart\Assert\Assert;
9
10
class ModuleTemplateApplicator implements TemplateApplicator
11
{
12
    public function __construct()
13
    {
14
15
    }
16
17
    public function handle($sourceModel, $targetModel): void
18
    {
19
        Assert::isInstanceOf($sourceModel, Module::class);
20
        Assert::isInstanceOf($targetModel, Module::class);
21
22
        // Dynamic attributes
23
        if($sourceModel->values && $sourceModel->values instanceof DynamicAttributes) {
24
            $targetModel->values = $sourceModel->values;
25
        }
26
27
        // Translations
28
        foreach($sourceModel->getTranslationsArray() as $locale => $values) {
29
            $targetModel->translations()->create(array_merge(['locale' => $locale], $values));
30
        }
31
32
        // Fragments
33
        if (method_exists($sourceModel, 'fragments') && method_exists($targetModel, 'fragments'))
34
        {
35
            foreach ($sourceModel->fragments()->get() as $fragmentModel)
36
            {
37
                $targetModel->fragments()->create([
38
                    'key'    => $fragmentModel->key,
39
                    'values' => $fragmentModel->values,
40
                ]);
41
            }
42
        }
43
44
        $targetModel->save();
45
46
        // Assets
47
        foreach($sourceModel->assets() as $asset) {
48
            $targetModel->assetRelation()->attach($asset, ['type' => $asset->pivot->type, 'locale' => $asset->pivot->locale, 'order' => $asset->pivot->order]);
49
        }
50
    }
51
52
    public function shouldApply($sourceModel, $targetModel): bool
53
    {
54
        return ($sourceModel instanceof Module && $targetModel instanceof Module);
55
    }
56
}
57