62 lines
1.4 KiB
PHP
62 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Models\Traits;
|
|
|
|
use Illuminate\Contracts\Database\Eloquent\Builder;
|
|
|
|
trait HashableId
|
|
{
|
|
private const string HASHID_COLUMN_NAME = 'hash_id';
|
|
|
|
public static function idToHash(int $key): string
|
|
{
|
|
return _h($key);
|
|
}
|
|
|
|
public static function hashToId(string $hash): int
|
|
{
|
|
return unhash_it($hash);
|
|
}
|
|
|
|
public static function byHashOrFail($hash): self
|
|
{
|
|
return self::query()->byHash($hash)->firstOrFail();
|
|
}
|
|
|
|
public static function byHash($hash): ?self
|
|
{
|
|
return self::query()->byHash($hash)->first();
|
|
}
|
|
|
|
/**
|
|
* Get HashId column name.
|
|
*/
|
|
public function getHashColumnName(): string
|
|
{
|
|
return property_exists($this, 'hashColumnName')
|
|
? $this->hashColumnName
|
|
: self::HASHID_COLUMN_NAME;
|
|
}
|
|
|
|
public function getHashAttribute(): ?string
|
|
{
|
|
return $this->exists
|
|
? $this->idToHash($this->getKey())
|
|
: null;
|
|
}
|
|
|
|
public function scopeByHash(Builder $query, string $hash): Builder
|
|
{
|
|
return $query->where($this->getQualifiedKeyName(), unhash_it($hash));
|
|
}
|
|
|
|
public function resolveRouteBinding($value, $field = null)
|
|
{
|
|
if ($field || is_numeric($value)) {
|
|
return parent::resolveRouteBinding($value, $field);
|
|
}
|
|
|
|
return $this->byHash($value);
|
|
}
|
|
}
|