96 lines
2.2 KiB
PHP
96 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Lib\Helpers\ToolboxHelper;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Facades\Crypt;
|
|
use Illuminate\Support\Str;
|
|
|
|
class Service extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
/**
|
|
* The attributes that are mass assignable.
|
|
*
|
|
* @var array<int, string>
|
|
*/
|
|
protected $fillable = [
|
|
'name',
|
|
'bearer_token',
|
|
'bearer_pwd',
|
|
'brand_id'
|
|
];
|
|
|
|
// * EVENTS
|
|
|
|
/**
|
|
* Perform any actions required after the model boots.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function booted()
|
|
{
|
|
static::creating(function (self $model) {
|
|
self::assertFieldIsUnique('name', $model->name);
|
|
$model->generateBearerToken();
|
|
$model->generateBearerPassword();
|
|
});
|
|
}
|
|
|
|
// * METHODS
|
|
|
|
/**
|
|
* Asserts using validation that the field is unique.
|
|
*
|
|
* @param string $nameField
|
|
* @param string $valueField
|
|
* @param integer|null $id
|
|
* @return void
|
|
*/
|
|
private static function assertFieldIsUnique(string $nameField, string $valueField, ?int $id = null)
|
|
{
|
|
$table = (new self())->getTable();
|
|
ToolboxHelper::assertFieldIsUnique($table, $nameField, $valueField, $id);
|
|
}
|
|
|
|
/**
|
|
* Generates new bearer token
|
|
*
|
|
* @return string
|
|
*/
|
|
public function generateBearerToken(): string
|
|
{
|
|
$this->bearer_token = hash('ripemd160', Str::uuid());
|
|
$this->bearer_token_date = now();
|
|
return $this->bearer_token;
|
|
}
|
|
|
|
/**
|
|
* Generates new bearer password
|
|
* It store the crypted password in model
|
|
* and returns the plain password
|
|
*
|
|
* @return string
|
|
*/
|
|
public function generateBearerPassword(): string
|
|
{
|
|
$pwd = hash('sha256', Str::uuid());
|
|
$this->bearer_pwd = Crypt::encryptString($pwd);
|
|
return $pwd;
|
|
}
|
|
|
|
// * RELATIONSHIPS
|
|
|
|
/**
|
|
* Get the brand that owns the service.
|
|
*
|
|
* @return BelongsTo
|
|
*/
|
|
public function brand()
|
|
{
|
|
return $this->belongsTo(Brand::class);
|
|
}
|
|
}
|