Skip to content

Instantly share code, notes, and snippets.

@Jakhongir91
Created December 2, 2019 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jakhongir91/178cfbbed9b1934d6c1d8cd10781cf72 to your computer and use it in GitHub Desktop.
Save Jakhongir91/178cfbbed9b1934d6c1d8cd10781cf72 to your computer and use it in GitHub Desktop.
<?php
namespace Spatie\Tags;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection as DbCollection;
use Illuminate\Database\Eloquent\Model;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;
use Spatie\Translatable\HasTranslations;
class Tag extends Model implements Sortable
{
use SortableTrait, HasTranslations, HasSlug;
public $translatable = ['name', 'slug'];
public $guarded = [];
public function scopeWithType(Builder $query, string $type = null): Builder
{
if (is_null($type)) {
return $query;
}
return $query->where('type', $type)->ordered();
}
public function scopeContaining(Builder $query, string $name, $locale = null): Builder
{
$locale = $locale ?? app()->getLocale();
return $query->whereRaw('lower('.$this->getQuery()->getGrammar()->wrap('name->'.$locale).') like ?', ['%'.mb_strtolower($name).'%']);
}
/**
* @param string|array|\ArrayAccess $values
* @param string|null $type
* @param string|null $locale
*
* @return \Spatie\Tags\Tag|static
*/
public static function findOrCreate($values, string $type = null, string $locale = null)
{
$tags = collect($values)->map(function ($value) use ($type, $locale) {
if ($value instanceof self) {
return $value;
}
return static::findOrCreateFromString($value, $type, $locale);
});
return is_string($values) ? $tags->first() : $tags;
}
public static function getWithType(string $type): DbCollection
{
return static::withType($type)->ordered()->get();
}
public static function findFromString(string $name, string $type = null, string $locale = null)
{
$locale = $locale ?? app()->getLocale();
return static::query()
->where("name->{$locale}", $name)
->where('type', $type)
->first();
}
public static function findFromStringOfAnyType(string $name, string $locale = null)
{
$locale = $locale ?? app()->getLocale();
return static::query()
->where("name->{$locale}", $name)
->first();
}
protected static function findOrCreateFromString(string $name, string $type = null, string $locale = null)
{
$locale = $locale ?? app()->getLocale();
$tag = static::findFromString($name, $type, $locale);
if (! $tag) {
$tag = static::create([
'name' => [$locale => $name],
'type' => $type,
]);
}
return $tag;
}
public function setAttribute($key, $value)
{
if ($key === 'name' && ! is_array($value)) {
return $this->setTranslation($key, app()->getLocale(), $value);
}
return parent::setAttribute($key, $value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment