ldc-legaulois/app/Models/OpBrCharcut/Code.php

91 lines
2.2 KiB
PHP
Raw Normal View History

2022-03-10 13:31:10 +00:00
<?php
namespace App\Models\OpBrCharcut;
use Illuminate\Database\Eloquent\Model;
use Kwaadpepper\Serial\SerialCaster;
use App\Models\Customers;
2022-03-30 08:31:41 +00:00
use Illuminate\Support\Facades\Log;
use Kwaadpepper\Serial\Exceptions\SerialCasterException;
2022-03-10 13:31:10 +00:00
class Code extends Model
{
protected $table = 'opbrcharcut_codes';
2023-06-26 15:57:38 +02:00
2022-03-10 13:31:10 +00:00
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'code_used', 'code_exported',
'date_creation'
];
/**
* Indicates if the model should be timestamped.
*
* @var boolean
*/
public $timestamps = false;
// * RELATIONS
public function customer()
{
return $this->belongsTo(Customers::class);
}
// * 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('opbrcharcut.codeLength'),
config('opbrcharcut.codeCharList')
);
}
/**
* Generate a serial from an int.
*
* @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
{
2022-03-30 08:31:41 +00:00
try {
return SerialCaster::decode(
$serial,
\abs(\crc32(config('app.key'))),
config('opbrcharcut.codeCharList')
);
} catch (SerialCasterException $e) {
2022-03-30 08:41:29 +00:00
Log::error($e->getMessage() . " code utilisé : " . $serial);
2023-06-26 15:57:38 +02:00
// return 0 invalid value for code
2022-03-30 08:31:41 +00:00
return 0;
}
2022-03-10 13:31:10 +00:00
}
}