BookStack/app/Entities/Tools/SlugGenerator.php

60 lines
1.4 KiB
PHP
Raw Normal View History

2021-06-26 17:23:15 +02:00
<?php
namespace BookStack\Entities\Tools;
2023-05-17 18:56:55 +02:00
use BookStack\App\Model;
use BookStack\App\Sluggable;
use BookStack\Entities\Models\BookChild;
use Illuminate\Support\Str;
class SlugGenerator
{
/**
* Generate a fresh slug for the given entity.
2021-11-06 01:32:01 +01:00
* The slug will be generated so that it doesn't conflict within the same parent item.
*/
public function generate(Sluggable $model): string
{
$slug = $this->formatNameAsSlug($model->name);
while ($this->slugInUse($slug, $model)) {
$slug .= '-' . Str::random(3);
}
2021-06-26 17:23:15 +02:00
return $slug;
}
/**
* Format a name as a url slug.
*/
protected function formatNameAsSlug(string $name): string
{
$slug = Str::slug($name);
2021-06-26 17:23:15 +02:00
if ($slug === '') {
$slug = substr(md5(rand(1, 500)), 0, 5);
}
2021-06-26 17:23:15 +02:00
return $slug;
}
/**
* Check if a slug is already in-use for this
* type of model within the same parent.
2021-11-06 23:00:33 +01:00
*
2021-11-06 01:32:01 +01:00
* @param Sluggable&Model $model
*/
protected function slugInUse(string $slug, Sluggable $model): bool
{
$query = $model->newQuery()->where('slug', '=', $slug);
if ($model instanceof BookChild) {
$query->where('book_id', '=', $model->book_id);
}
if ($model->id) {
$query->where('id', '!=', $model->id);
}
return $query->count() > 0;
}
}