Files
laralog/app/Support/SlugGenerator.php
T
gouki d483577c90
Build and Deploy / verify (push) Successful in 11s
Build and Deploy / deploy (push) Successful in 17s
fix(tags): use crc32-fallback slugger for Chinese tag names (HasSlug was blanking slugs)
2026-10-12 22:52:21 +00:00

43 lines
1.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Support;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class SlugGenerator
{
/**
* spatie/tags 的 tags.slugger 回调:拉丁字符用 Str::slug,纯中文名回退 crc32 形式。
*/
public static function slug(string $string): string
{
$slug = Str::slug($string, '-', 'en');
return $slug === '' ? 'tag-'.crc32($string) : $slug;
}
/**
* 生成唯一 slug。中文标题自动回退为 $fallback 或 crc32 形式。
*/
public static function make(string $string, string $table, string $column = 'slug', ?int $ignoreId = null, ?string $fallback = null): string
{
$slug = Str::slug($string, '-', 'en');
if ($slug === '' || $slug === null) {
$slug = $fallback ?? $table.'-'.crc32($string);
}
$base = $slug;
$i = 2;
while (DB::table($table)->where($column, $slug)->where('id', '!=', $ignoreId ?? 0)->exists()) {
$slug = $base.'-'.$i++;
}
return $slug;
}
}