53 lines
1.4 KiB
PHP
53 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Models;
|
|
|
|
use Illuminate\Database\UniqueConstraintViolationException;
|
|
use Illuminate\Support\Str;
|
|
|
|
/**
|
|
* The random key that goes into today's visitor codes. A new one every day, and
|
|
* the old ones are deleted: without its key a code can no longer be linked to an
|
|
* IP address, not even by this site.
|
|
*
|
|
* @property string $day
|
|
* @property string $salt
|
|
*/
|
|
class VisitorSalt extends Model
|
|
{
|
|
public $timestamps = false;
|
|
|
|
protected $primaryKey = 'day';
|
|
|
|
public $incrementing = false;
|
|
|
|
protected $keyType = 'string';
|
|
|
|
public static function forToday(): string
|
|
{
|
|
$today = now()->toDateString();
|
|
$salt = static::query()->where('day', $today)->value('salt');
|
|
|
|
if (is_string($salt)) {
|
|
return $salt;
|
|
}
|
|
|
|
static::forgetOld();
|
|
|
|
try {
|
|
return static::query()->create(['day' => $today, 'salt' => Str::random(64)])->salt;
|
|
} catch (UniqueConstraintViolationException) {
|
|
// Another visitor arrived in the same instant and made today's key.
|
|
return static::query()->where('day', $today)->sole()->salt;
|
|
}
|
|
}
|
|
|
|
/** Deletes every key that is not today's. Returns how many. */
|
|
public static function forgetOld(): int
|
|
{
|
|
$deleted = static::query()->where('day', '<', now()->toDateString())->delete();
|
|
|
|
return is_int($deleted) ? $deleted : 0;
|
|
}
|
|
}
|