Passed
Push — master ( bb924a...090072 )
by Vasyl
01:56
created

UrlAlias::boot()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 9
rs 10
1
<?php
2
3
namespace Fomvasss\UrlAliases\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
class UrlAlias extends Model
8
{
9
    public $timestamps = false;
10
11
    protected $guarded = ['id'];
12
13
    protected static function boot()
14
    {
15
        static::creating(function (Model $model) {
16
            if (! $model->locale) {
17
                $model->locale = app()->app['config']->get('app.locale');
0 ignored issues
show
Bug introduced by
The function app was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

17
                $model->locale = /** @scrutinizer ignore-call */ app()->app['config']->get('app.locale');
Loading history...
18
            }
19
        });
20
21
        parent::boot(); // TODO: Change the autogenerated stub
22
    }
23
24
    /**
25
     * @return string
26
     */
27
    public function getLocaleAliasAttribute()
28
    {
29
        if (is_url($this->attributes['alias']) || $this->attributes['locale'] == $this->attributes['alias']) {
30
            return $this->attributes['alias'];
31
        }
32
33
        return $this->attributes['locale'] . '/' . $this->attributes['alias'];
34
    }
35
36
    /**
37
     * @return string
38
     */
39
    public function getLocaleSourceAttribute()
40
    {
41
        if (is_url($this->attributes['source']) || $this->attributes['locale'] == $this->attributes['alias']) {
42
            return $this->attributes['source'];
43
        }
44
        return $this->attributes['locale'] . '/' . $this->attributes['source'];
45
    }
46
47
    /**
48
     * @param $query
49
     * @param $path
50
     * @return mixed
51
     */
52
    public function scopeByPath($query, $path)
53
    {
54
        return $query->where(function($q) use ($path) {
55
                $q->where('source', $path)->orWhere('alias', $path);
56
            });
57
    }
58
59
    /**
60
     * @param $value
61
     */
62
    public function setAliasAttribute($value)
63
    {
64
        $this->attributes['alias'] = trim($value, '/');
65
    }
66
67
    /**
68
     * @param $value
69
     */
70
    public function setSourceAttribute($value)
71
    {
72
        $this->attributes['source'] = trim($value, '/');
73
    }
74
75
    /**
76
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
77
     */
78
    public function aliasable()
79
    {
80
        return $this->morphTo('aliasable', 'model_type', 'model_id');
81
    }
82
}
83