Passed
Push — master ( b755a8...4573fd )
by Gabriel
02:16
created

HasSeo::bootHasSeo()   B

Complexity

Conditions 8
Paths 1

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 17
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 25
rs 8.4444
1
<?php
2
3
namespace Giuga\LaravelSeoMetaBox\Traits;
4
5
use Giuga\LaravelSeoMetaBox\Models\Seo;
6
use Illuminate\Database\Eloquent\Model;
7
8
trait HasSeo
9
{
10
    abstract public function getSeoOptions(): SeoOptions;
11
12
    protected static function bootHasSeo()
13
    {
14
        static::saved(function (Model $model) {
15
            $options = $model->getSeoOptions();
16
            $seo = Seo::firstOrNew([
17
                'type' => get_class($model),
18
                'object_id' => $model->{$model->primaryKey},
19
            ]);
20
            $seo->slug = $options->routePrefix ?? '';
21
            if ($options->hasSlug) {
22
                $seo->slug .= $model->{$options->slugField};
23
            } else {
24
                $seo->slug .= $model->{$model->primaryKey};
25
            }
26
            if ((empty($seo->title) || $options->overwriteOnUpdate) && isset($options->titleField)) {
27
                $seo->title = $model->{$options->titleField};
28
            }
29
            if ((empty($seo->description) || $options->overwriteOnUpdate) && isset($options->descriptionField)) {
30
                $seo->description = $model->{$options->descriptionField};
31
            }
32
            $seo->save();
33
        });
34
35
        static::retrieved(function (Model $model) {
36
            app()->make('laravel-seo-meta-box')->addObjectOnPage(get_class($model), $model->{$model->primaryKey});
37
        });
38
    }
39
40
    public function seo()
41
    {
42
        return $this->hasOne(Seo::class, 'object_id');
0 ignored issues
show
Bug introduced by
It seems like hasOne() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

42
        return $this->/** @scrutinizer ignore-call */ hasOne(Seo::class, 'object_id');
Loading history...
43
    }
44
}
45