38 lines
1009 B
PHP
38 lines
1009 B
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Helpers;
|
||
|
|
|
||
|
|
use Cocur\Slugify\Slugify;
|
||
|
|
use Illuminate\Support\Str;
|
||
|
|
|
||
|
|
class SlugHelper
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* Generate a slug from a title, supporting Japanese and other non-ASCII characters
|
||
|
|
*
|
||
|
|
* @param string $title
|
||
|
|
* @param string|null $fallback Optional fallback if slug is empty
|
||
|
|
* @return string
|
||
|
|
*/
|
||
|
|
public static function generate(string $title, ?string $fallback = null): string
|
||
|
|
{
|
||
|
|
$slugify = new Slugify(['lowercase' => true]);
|
||
|
|
|
||
|
|
// Try to generate slug with cocur/slugify
|
||
|
|
$slug = $slugify->slugify($title);
|
||
|
|
|
||
|
|
// If slug is empty (happens with pure Japanese/Chinese characters),
|
||
|
|
// use fallback or generate a unique identifier
|
||
|
|
if (empty($slug)) {
|
||
|
|
if ($fallback) {
|
||
|
|
$slug = $fallback;
|
||
|
|
} else {
|
||
|
|
// Use timestamp + random string for unique slug
|
||
|
|
$slug = date('YmdHis') . '-' . Str::random(8);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return $slug;
|
||
|
|
}
|
||
|
|
}
|