ldc-wenn-dann-mit-respekt/app/Models/StoreGroup.php

107 lines
2.5 KiB
PHP
Raw Normal View History

2023-03-15 13:51:01 +01:00
<?php
namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
2023-03-16 09:47:16 +01:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
2023-03-15 13:51:01 +01:00
use Illuminate\Database\Eloquent\Model;
/**
* @property string $name
* @property string $picture
2023-03-29 10:04:16 +00:00
* @property integer $order
2023-03-15 13:51:01 +01:00
* @property string $created_at
* @property string $updated_at
*/
class StoreGroup extends Model
{
2023-03-16 09:47:16 +01:00
use HasFactory;
2023-03-15 13:51:01 +01:00
/**
2024-07-16 18:21:29 +02:00
* The attributes that are mass assignable.
*
* @var array<int, string>
2023-03-15 13:51:01 +01:00
*/
protected $fillable = [
'name',
'picture',
2023-03-29 10:04:16 +00:00
'order',
2023-03-15 13:51:01 +01:00
'created_at',
'updated_at'
];
// * EVENTS
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::creating(function (self $model) {
2023-03-29 10:04:16 +00:00
self::assertFieldIsUnique('name', $model->name);
2023-03-15 13:51:01 +01:00
self::manageFields($model);
2023-03-29 10:04:16 +00:00
self::setOrder($model);
2023-03-15 13:51:01 +01:00
});
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
*
2024-01-29 16:02:03 +01:00
* @param self $model
2023-03-15 13:51:01 +01:00
* @return void
*/
2024-01-29 16:02:03 +01:00
private static function manageFields(self $model)
2023-03-15 13:51:01 +01:00
{
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
}
2023-03-29 10:04:16 +00:00
/**
* Set order after the last element of the list.
*
2024-01-29 16:02:03 +01:00
* @param self $model
2023-03-29 10:04:16 +00:00
* @return void
*/
2024-01-29 16:02:03 +01:00
private static function setOrder(self $model): void
2023-03-29 10:04:16 +00:00
{
$model->order = \intval(self::query()->max('order')) + 1;
}
2023-03-15 13:51:01 +01:00
/**
* Asserts using validation that the field is unique.
*
* @param string $nameField
2023-05-05 10:07:01 +02:00
* @param string $valueField
2023-03-15 13:51:01 +01:00
* @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()
{
2023-05-05 10:07:01 +02:00
return $this->hasMany(StoreRegion::class, 'group_id');
2023-03-15 13:51:01 +01:00
}
}