Cancelled
Push — 0.5 ( d49ebd...32819b )
by Philippe
36s queued 36s
created

ModuleTemplateApplicator::handle()   B

Complexity

Conditions 8
Paths 16

Size

Total Lines 30
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 30
rs 8.4444
cc 8
nc 16
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Thinktomorrow\Chief\Templates;
6
7
use Thinktomorrow\Chief\DynamicAttributes\DynamicAttributes;
8
use Thinktomorrow\Chief\Modules\Module;
9
use Webmozart\Assert\Assert;
10
11
class ModuleTemplateApplicator implements TemplateApplicator
12
{
13
    public function __construct()
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
            foreach ($sourceModel->fragments()->get() as $fragmentModel) {
35
                $targetModel->fragments()->create([
36
                    'key'    => $fragmentModel->key,
37
                    'values' => $fragmentModel->values,
38
                ]);
39
            }
40
        }
41
42
        $targetModel->save();
43
44
        // Assets
45
        foreach ($sourceModel->assets() as $asset) {
46
            $targetModel->assetRelation()->attach($asset, ['type' => $asset->pivot->type, 'locale' => $asset->pivot->locale, 'order' => $asset->pivot->order]);
47
        }
48
    }
49
50
    public function shouldApply($sourceModel, $targetModel): bool
51
    {
52
        return ($sourceModel instanceof Module && $targetModel instanceof Module);
53
    }
54
}
55