ldc-wenn-dann-mit-respekt/app/Models/StoreGroup.php
Noah Lancien 222347d890 phpstan
2024-01-29 16:20:14 +01:00

104 lines
2.4 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* @property string $name
* @property string $picture
* @property integer $order
* @property string $created_at
* @property string $updated_at
*/
class StoreGroup extends Model
{
use HasFactory;
/**
* @var array<string>
*/
protected $fillable = [
'name',
'picture',
'order',
'created_at',
'updated_at'
];
// * 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);
self::manageFields($model);
self::setOrder($model);
});
static::updating(function (self $model) {
self::manageFields($model);
});
static::updated(function (self $model) {
FileStorageHelper::removeOldFile($model, 'picture');
});
static::deleted(function (self $model) {
FileStorageHelper::removeFile($model, 'picture');
});
}
// * METHODS
/**
* Undocumented function
*
* @param self $model
* @return void
*/
private static function manageFields(self $model)
{
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
}
/**
* Set order after the last element of the list.
*
* @param self $model
* @return void
*/
private static function setOrder(self $model): void
{
$model->order = \intval(self::query()->max('order')) + 1;
}
/**
* 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);
}
// * RELATIONSHIPS
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function storeRegions()
{
return $this->hasMany(StoreRegion::class, 'group_id');
}
}