Completed
Push — master ( 497186...38c187 )
by Freek
02:38
created

Tag::scopeWithType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
1
<?php
2
3
namespace Spatie\Tags;
4
5
use Illuminate\Database\Eloquent\Collection as DbCollection;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Query\Builder;
8
use Spatie\EloquentSortable\Sortable;
9
use Spatie\EloquentSortable\SortableTrait;
10
use Spatie\Translatable\HasTranslations;
11
12
class Tag extends Model implements Sortable
13
{
14
    use SortableTrait, HasTranslations, HasSlug;
15
16
    public $translatable = ['name', 'slug'];
17
18
    public $guarded = [];
19
20
    public function scopeWithType(Builder $query, string $type = null): Builder
21
    {if (is_null($type)) {
22
            return $query;
23
        }
24
25
        return $query->where('type', $type)->orderBy('order_column');
26
    }
27
28
29
    /**
30
     * @param array|\ArrayAccess $values
31
     * @param string|null $type
32
     * @param string|null $locale
33
     *
34
     * @return \Spatie\Tags\Tag|static
35
     */
36
    public static function findOrCreate($values, string $type = null, string $locale = null)
37
    {
38
39
        $tags = collect($values)->map(function (string $value) use ($type, $locale) {
40
41
            if ($value instanceof Tag) {
42
                return $value;
43
            }
44
45
            return static::findOrCreateFromString($value, $type, $locale);
46
        });
47
48
        return is_string($values) ? $tags->first() : $tags;
49
    }
50
51
    public static function getWithType(string $type): DbCollection
52
    {
53
        return static::type($type)->get();
54
    }
55
56
    public static function findFromString(string $name, string $type = null, string $locale = null)
57
    {
58
        $locale = $locale ?? app()->getLocale();
59
60
        return static::query()
61
            ->where("name->{$locale}", $name)
62
            ->where('type', $type)
63
            ->first();
64
    }
65
66
    protected static function findOrCreateFromString(string $name, string $type = null, string $locale = null): Tag
67
    {
68
69
        $locale = $locale ?? app()->getLocale();
70
71
        $tag = static::findFromString($name, $type, $locale);
72
73
        if (! $tag) {
74
            $tag = static::create([
75
                'name' => [$locale => $name],
76
                'type' => $type,
77
            ]);
78
        }
79
        return $tag;
80
    }
81
}
82