Skip to content

Commit

Permalink
feat: handle prefix length being 0
Browse files Browse the repository at this point in the history
  • Loading branch information
bensherred committed Nov 25, 2023
1 parent 186bfa4 commit 70938ba
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
2 changes: 2 additions & 0 deletions config/sqids.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@
| the prefix and the casing. By default, the prefix will be generated
| based on the model name.
|
| Setting the prefix length to "0" will remove the prefix all together.
|
| Supported Casing: "lower", "upper", "camel", "snake", "kebab",
| "title", "studly"
|
Expand Down
3 changes: 2 additions & 1 deletion src/HasSqids.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ public function resolveRouteBindingQuery($query, $value, $field = null): Builder

public static function keyFromSqid(string $sqid): ?int
{
$prefixLength = Sqids::prefixLength();
$prefix = Str::beforeLast(subject: $sqid, search: Sqids::separator());
$expectedPrefix = Sqids::prefixForModel(model: __CLASS__);

if ($prefix !== $expectedPrefix) {
if ($prefixLength && $prefix !== $expectedPrefix) {
return null;
}

Expand Down
13 changes: 11 additions & 2 deletions src/Sqids.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public static function forModel(Model $model): string
$id = $model->getKey();

$prefix = static::prefixForModel(model: $model::class);
$separator = static::separator();
$separator = $prefix ? static::separator() : null;
$sqid = static::encodeId(id: $id);

return "{$prefix}{$separator}{$sqid}";
Expand All @@ -25,7 +25,11 @@ public static function forModel(Model $model): string
public static function prefixForModel(string $model): ?string
{
$classBasename = class_basename(class: $model);
$prefixLength = Config::integer(key: 'sqids.prefix.length', default: 3);
$prefixLength = static::prefixLength();

if (!$prefixLength) {
return null;
}

$prefix = $prefixLength < 0
? $classBasename
Expand All @@ -52,6 +56,11 @@ public static function separator(): string
return Config::string(key: 'sqids.separator', default: '_');
}

public static function prefixLength(): int
{
return Config::integer(key: 'sqids.prefix.length', default: 3);
}

public static function encodeId(int $id): string
{
return static::encoder()->encode(numbers: [$id]);
Expand Down

0 comments on commit 70938ba

Please sign in to comment.