Completed
Push — master ( edb9ee...b465c5 )
by
unknown
10:14
created

LocaleObserver   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 4
dl 0
loc 60
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A created() 0 18 4
A deleted() 0 16 3
A translatableModels() 0 4 1
1
<?php
2
3
namespace BBSLab\NovaTranslation\Models\Observers;
4
5
use BBSLab\NovaTranslation\Models\Locale;
6
use BBSLab\NovaTranslation\Models\Translation;
7
use BBSLab\NovaTranslation\NovaTranslationServiceProvider;
8
9
class LocaleObserver
10
{
11
    /**
12
     * Handle the Locale "created" event.
13
     *
14
     * @param  \BBS\Nova\Translation\Models\Locale  $locale
15
     * @return void
16
     */
17
    public function created(Locale $locale)
18
    {
19
        foreach ($this->translatableModels() as $modelClassName) {
20
            /** @var \Illuminate\Database\Eloquent\Model $model */
21
            $model = (new $modelClassName);
22
23
            // @TODO... Handle translation_id in Translation
24
            foreach ($model->query()->cursor() as $instance) {
25
                $data = [];
26
                foreach ($instance->getNonTranslatable() as $field) {
27
                    $data[$field] = $instance->$field;
28
                }
29
30
                $created = $model->query()->create($data);
31
                $created->createTranslationEntry($locale->id);
32
            }
33
        }
34
    }
35
36
    /**
37
     * Handle the Locale "deleted" event.
38
     *
39
     * @param  \BBS\Nova\Translation\Models\Locale  $locale
40
     * @return void
41
     */
42
    public function deleted(Locale $locale)
43
    {
44
        $query = Translation::query()
45
            ->where('locale_id', '=', $locale->id)
46
            ->whereIn('translatable_type', $this->translatableModels());
47
48
        foreach ($query->cursor() as $translation) {
49
            /** @var \BBSLab\NovaTranslation\Models\Translation $translation */
50
            $instance = (new $translation->translatable_type)->find($translation->translatable_id);
51
52
            if (! empty($instance)) {
53
                // Related translation is deleted by the Translatable "deleted" observer
54
                $instance->delete();
55
            }
56
        }
57
    }
58
59
    /**
60
     * Return list of translated models.
61
     *
62
     * @return array
63
     */
64
    protected function translatableModels()
65
    {
66
        return config(NovaTranslationServiceProvider::PACKAGE_ID.'.auto_synced_models');
67
    }
68
}
69