ldc-com-app-bo/app/Models/Contact.php

122 lines
3.1 KiB
PHP

<?php
namespace App\Models;
use App\Casts\AsArrayOfInput;
use App\Lib\Helpers\ToolboxHelper;
use App\Lib\Inputs\InputEmail;
use App\Lib\Inputs\InputPhone;
use App\Lib\Inputs\InputText;
use App\Traits\Models\HasUuidKey;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Kwaadpepper\Enum\Traits\CastsEnums;
/**
* @property integer $app_user_id
* @property string $id
* @property string $email
* @property string|null $lastname
* @property string|null $firstname
* @property string|null $phone
* @property array<\App\Lib\Inputs\Definition\Input> $data
* @property string|null $notes
* @property array<array<string,string>> $visits
* @property \Carbon\Carbon $timestamp
*/
class Contact extends Model
{
use CastsEnums;
use HasFactory;
use HasUuidKey;
/**
* fillable
* @var string[]
*/
protected $fillable = [
'app_user_id',
'email',
'lastname',
'firstname',
'data',
'phone',
'notes',
'visits',
'timestamp',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'data' => AsArrayOfInput::class,
'timestamp' => 'immutable_datetime',
'visits' => 'array'
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function (self $model) {
$model->id = Str::uuid();
ToolboxHelper::assertContactDataIsMatchingFormulary($model);
});
static::deleting(function (self $model) {
ToolboxHelper::assertContactDataIsMatchingFormulary($model);
});
}
// * RELATIONSHIPS
/**
* MorphToMany Directories
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function appUser()
{
return $this->belongsTo(AppUser::class, 'app_user_id', 'id');
}
// * METHODS
/**
* Get all inputs
*
* @return array
* @throws \RuntimeException This should not happen since data was validated on contact insertion.
* ! It may happen if this model does not have an email.
* ! It may only happen if input validation rules are changed.
*/
public function allInputs(): array
{
return $this->mandatoryInputs() + $this->data;
}
/**
* Get mandatory inputs
*
* @return array<\App\Lib\Inputs\Definition\Input>
* @throws \RuntimeException If this model does have an email.
*/
public function mandatoryInputs(): array
{
// * firsname
$data[] = InputText::make('Prénom', $this->firstname, false);
// * lastname
$data[] = InputText::make('Nom', $this->lastname, false);
// * email
$data[] = InputEmail::make('E-mail', $this->email, true);
// * phone
$data[] = InputPhone::make('Téléphone', $this->phone, false);
return $data;
}
}