Changeset View
Changeset View
Standalone View
Standalone View
src/app/Observers/SignupCodeObserver.php
<?php | <?php | ||||
namespace App\Observers; | namespace App\Observers; | ||||
use App\SignupCode; | use App\SignupCode; | ||||
use Carbon\Carbon; | use Carbon\Carbon; | ||||
use Illuminate\Support\Str; | |||||
class SignupCodeObserver | class SignupCodeObserver | ||||
{ | { | ||||
/** | /** | ||||
* Handle the "creating" event. | * Handle the "creating" event. | ||||
* | * | ||||
* Ensure that the code entry is created with a random code/short_code. | * Ensure that the code entry is created with a random code/short_code. | ||||
* | * | ||||
* @param \App\SignupCode $code The code being created. | * @param \App\SignupCode $code The code being created. | ||||
* | * | ||||
* @return void | * @return void | ||||
*/ | */ | ||||
public function creating(SignupCode $code): void | public function creating(SignupCode $code): void | ||||
{ | { | ||||
$code_length = SignupCode::CODE_LENGTH; | $code_length = SignupCode::CODE_LENGTH; | ||||
$exp_hours = env('SIGNUP_CODE_EXPIRY', SignupCode::CODE_EXP_HOURS); | $exp_hours = env('SIGNUP_CODE_EXPIRY', SignupCode::CODE_EXP_HOURS); | ||||
if (empty($code->code)) { | if (empty($code->code)) { | ||||
$code->short_code = SignupCode::generateShortCode(); | $code->short_code = SignupCode::generateShortCode(); | ||||
// FIXME: Replace this with something race-condition free | // FIXME: Replace this with something race-condition free | ||||
while (true) { | while (true) { | ||||
$code->code = str_random($code_length); | $code->code = Str::random($code_length); | ||||
if (!SignupCode::find($code->code)) { | if (!SignupCode::find($code->code)) { | ||||
break; | break; | ||||
} | } | ||||
} | } | ||||
} | } | ||||
$code->expires_at = Carbon::now()->addHours($exp_hours); | $code->expires_at = Carbon::now()->addHours($exp_hours); | ||||
} | } | ||||
} | } |