From 6d3fa6ca6b6898f7d1d38498110bdcaebc8cd230 Mon Sep 17 00:00:00 2001 From: RVxLab <46111684+RVxLab@users.noreply.github.com> Date: Sun, 19 Feb 2023 17:22:47 +1000 Subject: [PATCH] Add the ability to specify how slugs are generated --- src/Tab.php | 13 +++++++++++++ tests/Feature/TabTest.php | 18 ++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/Tab.php b/src/Tab.php index 5a801c0..2e475dd 100644 --- a/src/Tab.php +++ b/src/Tab.php @@ -37,6 +37,9 @@ class Tab implements TabContract, JsonSerializable, Arrayable protected $position; + /** @var null|callable(\Eminiarts\Tabs\Contracts\TabContract $tab): string */ + protected static $createSlugUsing = null; + public function __construct($title, array $fields, $position = 0) { $this->title = $title; @@ -49,6 +52,12 @@ public static function make($title, array $fields): self return new static($title, $fields); } + /** @param callable(\Eminiarts\Tabs\Contracts\TabContract $tab): string $createSlugUsingFunction */ + public static function createSlugUsing(callable $createSlugUsingFunction): void + { + self::$createSlugUsing = $createSlugUsingFunction; + } + public function position(int $position): self { $this->position = $position; @@ -157,6 +166,10 @@ public function getName(): string public function getSlug(): string { + if (null !== $makeSlug = static::$createSlugUsing) { + return $makeSlug($this); + } + return Str::slug($this->getName()); } diff --git a/tests/Feature/TabTest.php b/tests/Feature/TabTest.php index 0428bcd..c3df7dd 100644 --- a/tests/Feature/TabTest.php +++ b/tests/Feature/TabTest.php @@ -6,6 +6,7 @@ use Eminiarts\Tabs\Tab; use PHPUnit\Framework\TestCase; +use Illuminate\Support\Str; class TabTest extends TestCase { @@ -126,16 +127,29 @@ public function testBodyClass(): void ], $tab->toArray()['bodyClass']); } + public function testCanSetCustomSlugGenerationFunction(): void + { + Tab::createSlugUsing(fn (Tab $tab) => strrev(Str::slug($tab->getTitle()))); + + $tab = Tab::make('Test tab', []); + + self::assertSame('bat-tset', $tab->getSlug()); + } + /** * @link https://github.com/eminiarts/nova-tabs/issues/145 + * @link https://github.com/eminiarts/nova-tabs/issues/167 + * @link https://github.com/eminiarts/nova-tabs/issues/275 * * @dataProvider multibyteTitleProvider */ - public function testDoesNotCrashWithMultibyteCharactersAsTitle(string $title): void + public function testCanHandleSlugsInNonAsciiCharacters(string $title): void { + Tab::createSlugUsing(fn (Tab $tab) => $tab->getTitle()); + $tab = Tab::make($title, []); - self::assertEmpty($tab->getSlug()); + self::assertSame($title, $tab->getSlug()); } /**