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
|
|
|
|