phpvms/app/Models/Traits/HashIdTrait.php

36 lines
742 B
PHP
Raw Normal View History

2017-06-25 02:20:24 +08:00
<?php
2017-08-13 01:24:00 +08:00
namespace App\Models\Traits;
2017-06-25 02:20:24 +08:00
use App\Contracts\Model;
2017-08-24 23:51:47 +08:00
use Hashids\Hashids;
trait HashIdTrait
2017-06-25 02:20:24 +08:00
{
/**
* @throws \Hashids\HashidsException
2018-08-27 00:40:04 +08:00
*
* @return string
*/
final protected static function createNewHashId(): string
{
$hashids = new Hashids('', Model::ID_MAX_LENGTH);
$mt = str_replace('.', '', microtime(true));
return $hashids->encode($mt);
}
/**
* Register callbacks
2018-08-27 00:40:04 +08:00
*
2018-03-09 22:52:55 +08:00
* @throws \Hashids\HashidsException
*/
final protected static function bootHashIdTrait(): void
2017-06-25 02:20:24 +08:00
{
static::creating(function ($model) {
if (empty($model->id)) {
$model->id = static::createNewHashId();
2017-06-25 02:20:24 +08:00
}
});
}
}