ldc-doux/app/Models/Post.php
2022-08-29 17:23:10 +02:00

103 lines
2.7 KiB
PHP

<?php
namespace App\Models;
use App\Lib\Utils;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\File;
use Spatie\Translatable\HasTranslations;
class Post extends Model
{
use HasFactory;
use HasTranslations;
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'date_start' => 'datetime',
'date_end' => 'datetime',
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title',
'text',
'picture_home',
'alt_text_picture_home',
'picture_news',
'alt_text_picture_news',
'date_start',
'date_end',
'on_top'
];
/**
* The attributes that are translatable.
*
* @var array
*/
protected $translatable = [
'title',
'text',
'picture_home',
'alt_text_picture_home',
'picture_news',
'alt_text_picture_news'
];
/**
* Perform any actions required after the model boots.
*
* @return void
* @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
*/
protected static function boot()
{
static::creating(function (Post $post) {
if (is_a($post->picture_home, "SplFileInfo")) {
$post->picture_home = Utils::storeImage($post->picture_home, $post->getTable());
}
if (is_a($post->picture_news, "SplFileInfo")) {
$post->picture_news = Utils::storeImage($post->picture_news, $post->getTable());
}
});
static::updating(function (Post $post) {
if (is_a($post->picture_home, "SplFileInfo")) {
$post->picture_home = Utils::storeImage($post->picture_home, $post->getTable());
}
if (is_a($post->picture_news, "SplFileInfo")) {
$post->picture_news = Utils::storeImage($post->picture_news, $post->getTable());
}
});
static::deleted(function (Post $post) {
if ($post->picture_home) {
$urlPicture = public_path() . $post->picture_home;
if ($urlPicture) {
if (File::exists($urlPicture)) {
File::delete($urlPicture);
}
}
}
if ($post->picture_news) {
$urlPicture = public_path() . $post->picture_news;
if ($urlPicture) {
if (File::exists($urlPicture)) {
File::delete($urlPicture);
}
}
}
});
parent::boot();
}
}