diff --git a/readme.md b/readme.md index 297c8dd..be1b09e 100644 --- a/readme.md +++ b/readme.md @@ -51,29 +51,33 @@ To create a new migration, use the artisan command `make:nanoid-migration`. All ```php generateId($this->getNanoidLength(), Client::MODE_DYNAMIC); + $client = new Client; + + if ($alphabet = $this->getNanoIdAlphabet()) { + return $client->formattedId($alphabet, $this->getNanoidLength()); + } + + return $client->generateId($this->getNanoidLength(), Client::MODE_DYNAMIC); } protected function getNanoIdPrefix(): string @@ -61,6 +67,19 @@ protected function getNanoidLength(): ?int return $nanoIdLength; } + protected function getNanoIdAlphabet(): ?string + { + if (property_exists($this, 'nanoidAlphabet')) { + return $this->nanoidAlphabet; + } + + if (method_exists($this, 'nanoidAlphabet')) { + return $this->nanoidAlphabet(); + } + + return null; + } + /** * Get the auto-incrementing key type. * diff --git a/tests/HasNanoidsTest.php b/tests/HasNanoidsTest.php index 8337f59..b519cab 100644 --- a/tests/HasNanoidsTest.php +++ b/tests/HasNanoidsTest.php @@ -56,6 +56,19 @@ expect(Str::length($model->getKey()))->toBe(3); }); +it('creates nanoid with alphabet before saving', function () { + $model = BasicModelWithAlphabet::create(); + + expect((int) $model->getKey())->toBeInt(); +}); + +it('creates nanoid with alphabet and length before saving', function () { + $model = BasicModelWithAlphabetAndLength::create(); + + expect((int) $model->getKey())->toBeInt(); + expect(Str::length($model->getKey()))->toBe(3); +}); + abstract class ModelTest extends Model { use HasNanoids; @@ -111,3 +124,15 @@ public function nanoidLength(): int return 3; } } + +class BasicModelWithAlphabet extends ModelTest +{ + protected $nanoidAlphabet = '1234567890'; +} + +class BasicModelWithAlphabetAndLength extends ModelTest +{ + protected $nanoidAlphabet = '1234567890'; + + protected $nanoidLength = 3; +}