119 lines
2.9 KiB
PHP
119 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Kwaadpepper\Serial\SerialCaster;
|
|
|
|
/**
|
|
* Code.
|
|
*
|
|
* @property boolean $code_used Is the code used ?
|
|
* @property boolean $code_exported Is the code exported ?
|
|
* @property \Illuminate\Support\Carbon $date_creation Date of creation.
|
|
*
|
|
* @property-read string|null $code_unique The unique code
|
|
*
|
|
* @method public static function intToSerial($int) Generate a serial from an int.
|
|
* @method public static function serialToInt($serial) Get an int from a serial.
|
|
*
|
|
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Participation[] $participations
|
|
* Associated participations.
|
|
*/
|
|
class Code extends Model
|
|
{
|
|
/**
|
|
* Indicates if the IDs are auto-incrementing.
|
|
*
|
|
* @var boolean
|
|
*/
|
|
public $incrementing = false;
|
|
|
|
/**
|
|
* The attributes that are mass assignable.
|
|
*
|
|
* @var array
|
|
*/
|
|
protected $fillable = [
|
|
'code_used',
|
|
'code_exported',
|
|
'date_creation'
|
|
];
|
|
|
|
/**
|
|
* The attributes that should be cast.
|
|
*
|
|
* @var array<string, string>
|
|
*/
|
|
protected $casts = [
|
|
'code_used' => 'bool',
|
|
'code_exported' => 'bool',
|
|
'date_creation' => 'date',
|
|
];
|
|
|
|
/**
|
|
* Indicates if the model should be timestamped.
|
|
*
|
|
* @var boolean
|
|
*/
|
|
public $timestamps = false;
|
|
|
|
// * RELATIONS
|
|
|
|
/**
|
|
* Has many Participation relation
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
|
*/
|
|
public function participations()
|
|
{
|
|
return $this->hasMany(Participation::class, 'code_unique_id');
|
|
}
|
|
|
|
// * FUNCTIONS
|
|
/**
|
|
* Generate code_unique attribute
|
|
*
|
|
* @return string|null
|
|
*/
|
|
public function getCodeUniqueAttribute()
|
|
{
|
|
if (!$this->id or !\is_integer($this->id) or $this->id < 1) {
|
|
return null;
|
|
}
|
|
return self::intToSerial($this->id);
|
|
}
|
|
|
|
/**
|
|
* Generate a serial from an int.
|
|
*
|
|
* @param integer $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,
|
|
\abs(\crc32(config('app.key'))),
|
|
config('codes.codeLength'),
|
|
config('codes.codeCharList')
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Get an int from a serial.
|
|
*
|
|
* @param string $serial
|
|
* @return integer 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,
|
|
\abs(\crc32(config('app.key'))),
|
|
config('codes.codeCharList')
|
|
);
|
|
}
|
|
}
|