ldc-doux/app/Models/Post.php

104 lines
2.7 KiB
PHP
Raw Normal View History

2021-12-17 17:27:25 +01:00
<?php
namespace App\Models;
use App\Lib\Utils;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\File;
2022-01-23 15:25:17 +01:00
use Spatie\Translatable\HasTranslations;
2021-12-17 17:27:25 +01:00
class Post extends Model
{
use HasFactory;
2022-01-23 15:25:17 +01:00
use HasTranslations;
2021-12-17 17:27:25 +01:00
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'date_start' => 'datetime',
'date_end' => 'datetime',
];
2022-08-29 17:23:10 +02:00
/**
* The attributes that are mass assignable.
*
* @var array
*/
2021-12-17 17:27:25 +01:00
protected $fillable = [
'title',
'text',
'picture_home',
2021-12-20 14:02:37 +01:00
'alt_text_picture_home',
2021-12-17 17:27:25 +01:00
'picture_news',
2021-12-20 14:02:37 +01:00
'alt_text_picture_news',
2021-12-17 17:27:25 +01:00
'date_start',
'date_end',
'on_top'
];
2022-08-29 17:23:10 +02:00
/**
* The attributes that are translatable.
*
* @var array
*/
2022-01-23 15:25:17 +01:00
protected $translatable = [
'title',
'text',
'picture_home',
'alt_text_picture_home',
'picture_news',
'alt_text_picture_news'
];
2022-08-29 17:23:10 +02:00
/**
* Perform any actions required after the model boots.
*
* @return void
* @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
*/
2021-12-17 17:27:25 +01:00
protected static function boot()
{
static::creating(function (Post $post) {
2022-07-27 14:33:56 +02:00
if (is_a($post->picture_home, "SplFileInfo")) {
2021-12-17 17:27:25 +01:00
$post->picture_home = Utils::storeImage($post->picture_home, $post->getTable());
}
2022-07-27 14:33:56 +02:00
if (is_a($post->picture_news, "SplFileInfo")) {
2021-12-17 17:27:25 +01:00
$post->picture_news = Utils::storeImage($post->picture_news, $post->getTable());
}
});
static::updating(function (Post $post) {
2022-07-27 14:33:56 +02:00
if (is_a($post->picture_home, "SplFileInfo")) {
2021-12-17 17:27:25 +01:00
$post->picture_home = Utils::storeImage($post->picture_home, $post->getTable());
}
2022-07-27 14:33:56 +02:00
if (is_a($post->picture_news, "SplFileInfo")) {
2021-12-17 17:27:25 +01:00
$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);
}
}
}
});
2021-12-17 17:27:25 +01:00
parent::boot();
}
}