*/ #[\Override] protected $fillable = [ 'code_exported', 'date_creation', ]; /** * The attributes that should be cast. * * @var array */ #[\Override] protected $casts = [ 'code_exported' => 'bool', 'date_creation' => 'date', ]; /** * Indicates if the model should be timestamped. * * @var bool */ #[\Override] public $timestamps = false; // * EVENTS /** * Perform any actions required after the model boots. */ protected static function booted(): void { static::created(fn () => Cache::forget('codes.count')); static::updated(fn () => Cache::forget('codes.count')); static::deleted(fn () => Cache::forget('codes.count')); } // * RELATIONS /** * Has many Participation relation * * @return HasMany */ public function participations(): HasMany { return $this->hasMany(Participation::class, 'code_unique_id'); } /** * Activities logs One-to-many relationship. * * @return HasMany */ public function activityLogs(): HasMany { return $this->hasMany(ActivityLog::class); } // * METHODS /** * Generate code_unique attribute */ protected function codeUnique(): Attribute { return Attribute::make( get: function (): ?string { if (! $this->id || $this->id < 1) { return null; } return self::intToSerial($this->id); } ); } /** * Get the key used for serial int caster */ public static function serialKeyHash(): int { return \abs(\crc32(config('app.key'))); } /** * Generate a serial from an int. * * @return string The serial * * @throws SerialCasterException If an error happens du to config. */ public static function intToSerial(int $int): string { return SerialCaster::encode( $int, self::serialKeyHash(), config('codes.codeLength'), config('codes.codeCharList') ); } /** * Get an int from a serial. * * @return int The ID represented * * @throws SerialCasterException If an error happens due to config or * wrong serial is given. */ public static function serialToInt(string $serial): int { return SerialCaster::decode( $serial, self::serialKeyHash(), config('codes.codeCharList') ); } // * GETTERS /** * Get has_been_used_too_namy_times attribute */ protected function hasBeenUsedTooManyTimes(): Attribute { /** @var Settings */ $settings = resolve(Settings::class); return Attribute::make( get: fn (): bool => $settings->nb_unique_code_use && Code::query()->where('id', $this->id)->whereHas( 'participations', operator: '>=', count: $settings->nb_unique_code_use )->exists() ); } }