Completed
Push — master ( d289a1...5c6899 )
by
unknown
07:56
created

LocaleObserver   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A created() 0 17 4
A deleted() 0 18 3
A translatableModels() 0 4 1
1
<?php
2
3
namespace BBS\Nova\Translation\Models\Observers;
4
5
use BBS\Nova\Translation\Models\Locale;
6
use BBS\Nova\Translation\Models\Scopes\TranslatableScope;
7
use BBS\Nova\Translation\Models\Translation;
8
use BBS\Nova\Translation\ServiceProvider;
9
10
class LocaleObserver
11
{
12
    /**
13
     * Handle the Locale "created" event.
14
     *
15
     * @param  \BBS\Nova\Translation\Models\Locale  $locale
16
     * @return void
17
     */
18
    public function created(Locale $locale)
19
    {
20
        foreach ($this->translatableModels() as $modelClassName) {
21
            /** @var \Illuminate\Database\Eloquent\Model $model */
22
            $model = (new $modelClassName);
23
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 \BBS\Nova\Translation\Models\Translation $translation */
50
            $instance = (new $translation->translatable_type)
51
                ->newQueryWithoutScope(TranslatableScope::class)
52
                ->find($translation->translatable_id);
53
54
            if (! empty($instance)) {
55
                // Related translation is deleted by the Translatable "deleted" observer
56
                $instance->delete();
57
            }
58
        }
59
    }
60
61
    /**
62
     * Return list of translated models.
63
     *
64
     * @return array
65
     */
66
    protected function translatableModels()
67
    {
68
        return config(ServiceProvider::PACKAGE_ID.'.auto_synced_models');
69
    }
70
}
71