Skip to content

Commit

Permalink
Merge pull request #2 from AesirCloud/1.0.3
Browse files Browse the repository at this point in the history
1.0.3
  • Loading branch information
gregupton authored Jul 8, 2024
2 parents c932b92 + ee03496 commit 6c75709
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 17 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# Change Log
All notable changes to `sluggable` will be documented in this file.

## 1.0.3 - 2024-07-08
- Fixed issue where slug was not always booting correctly.

## 1.0.2 - 2024-06-28
- Add tests

Expand Down
91 changes: 74 additions & 17 deletions src/SluggableServiceProvider.php
Original file line number Diff line number Diff line change
@@ -1,34 +1,91 @@
<?php

namespace AesirCloud\Sluggable;
namespace AesirCloud\Sluggable\Traits;

use Illuminate\Support\ServiceProvider;
class SluggableServiceProvider extends ServiceProvider
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

trait Sluggable
{
/**
* Bootstrap any package services.
* Boot the sluggable trait for a model.
*
* @return void
*/
public function boot()
public static function bootSluggable(): void
{
static::saving(function ($model) {
$model->generateSlug();
});
}

/**
* Find a model by its slug.
*
* @param string $slug
* @return Model|null
*/
public static function findBySlug($slug)
{
// Publish the configuration file
$this->publishes([
__DIR__.'/../config/sluggable.php' => config_path('sluggable.php'),
], 'config');
return static::where('slug', $slug)->first();
}

/**
* Register any package services.
* Generate a unique slug for the model.
*
* @return void
*/
public function register()
protected function generateSlug(): void
{
$slug = Str::slug($this->getSlugSource());

// Ensure the slug is unique
$slug = $this->makeSlugUnique($slug);

$this->slug = $slug;
}

/**
* Get the source string for the slug.
*
* @return string
*/
protected function getSlugSource()
{
if (property_exists($this, 'slugSource')) {
return $this->{$this->slugSource};
}

return $this->title ?? $this->name ?? 'default';
}

/**
* Make the slug unique.
*
* @param string $slug
* @return string
*/
protected function makeSlugUnique($slug): string
{
$originalSlug = $slug;
$count = 1;

while ($this->slugExists($slug)) {
$slug = "{$originalSlug}-{$count}";
$count++;
}

return $slug;
}

/**
* Check if the slug already exists.
*
* @param string $slug
* @return bool
*/
protected function slugExists($slug): bool
{
// Merge the configuration file
$this->mergeConfigFrom(
__DIR__.'/../config/sluggable.php',
'sluggable'
);
return static::where('slug', $slug)->exists();
}
}
}

0 comments on commit 6c75709

Please sign in to comment.