ldc-le-gaulois-pro/app/Models/News.php
2025-07-09 12:00:00 +02:00

329 lines
11 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Support\Str;
use Spatie\Sitemap\Tags\Url;
use Spatie\CalendarLinks\Link;
use App\Lib\Helpers\ToolboxHelper;
use Uwil\Seo\Laravel\Objects\SeoItem;
use Uwil\Seo\Laravel\Traits\SeoTrait;
use App\Lib\Helpers\FileStorageHelper;
use Spatie\Sitemap\Contracts\Sitemapable;
use Uwil\SitemapGenerator\Lib\SitemapHelper;
use Uwil\Seo\Laravel\Interfaces\SeoInterface;
use Illuminate\Validation\ValidationException;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Uwil\Laravel\Redirections\Traits\IsRedirectable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Uwil\Laravel\Redirections\Interfaces\RedirectableInterface;
/**
*/
/**
* @property integer $id Id.
* @property string $title Title.
* @property string $subtitle Type of the advice.
* @property string $slug Slug of the title.
* @property string $seo_title SEO Title.
* @property string $seo_description SEO description.
* @property string $picture Path of a picture.
* @property string $picture_alt Picture's attribute alt.
* @property string $picture_title Picture's attribute title.
* @property string|null $picture2 Path of a second picture.
* @property string|null $picture2_alt Second picture's attribute alt.
* @property string|null $picture2_title Second picture's attribute title.
* @property string $content First WYSWYG content.
* @property string|null $content2 Second WYSWYG content.
* @property \Illuminate\Support\Carbon|null $event_start Start of the event.
* @property \Illuminate\Support\Carbon|null $event_end End of the event.
* @property string|null $event_text Text of the event.
* @property boolean $published Status.
* @property-read string $reading_time Time reading of a news' page
* @property-read \Illuminate\Support\Carbon $created_at Created date.
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
*
* @property-read \Spatie\CalendarLinks\Link|null $cal_link
*
* @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\News> $news
* News Belongs-To-Many relationship.
* @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\Product> $products
* Products Belongs-To-Many relationship.
* @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\Tags> $categories
* Categories Morph-To-Many relationship.
*/
class News extends Authenticatable implements SeoInterface, Sitemapable, RedirectableInterface
{
use HasFactory;
use SeoTrait;
use IsRedirectable;
/**
* The attributes that are mass assignable.
*
* @var array<int,string>
*/
protected $fillable = [
'title',
'slug',
'subtitle',
'seo_title',
'seo_description',
'picture',
'picture_alt',
'picture_title',
'picture2',
'picture2_alt',
'picture2_title',
'content',
'content2',
'event_start',
'event_end',
'event_text',
'published',
];
/**
* The attributes that should be cast.
*
* @var array<string,string>
*/
protected $casts = [
'event_start' => 'datetime',
'event_end' => 'datetime',
'published' => 'bool',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
self::manageFields($model);
});
static::updating(function (self $model) {
self::manageFields($model);
self::assertLimitNewsCategory($model->categories()->count());
self::assertLimitProducts($model->products()->count());
self::assertLimitNews($model->news()->count());
});
static::updated(function (self $model) {
FileStorageHelper::removeOldFile($model, 'picture');
FileStorageHelper::removeOldFile($model, 'picture2');
});
static::deleted(function (self $model) {
FileStorageHelper::removeFile($model, 'picture');
FileStorageHelper::removeFile($model, 'picture2');
});
}
// * ATTRIBUTES
/**
* Get cal_link attribute
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
public function calLink(): Attribute
{
return Attribute::make(
get: fn() => (
$this->exists() and
($this->event_start && $this->event_end && $this->event_text)
) ? Link::create(
$this->title,
$this->event_start,
$this->event_end
)->description($this->event_text)->ics() : null
);
}
// * METHODS
/**
* Common methods function.
*
* @param self $model
* @return void
*/
private static function manageFields(self $model): void
{
self::assertTitleIsUnique($model->title, $model->id);
$model->slug = Str::slug($model->title);
ToolboxHelper::assertNoInternalBoUrls('content', $model->content);
$model->content = clean($model->content);
if ($model->content2) {
ToolboxHelper::assertNoInternalBoUrls('content2', $model->content2);
$model->content2 = clean($model->content2);
}
$model->picture = FileStorageHelper::storeFile($model, $model->picture);
$model->picture2 = FileStorageHelper::storeFile($model, $model->picture2);
}
/**
* Limit products associated.
*
* @param integer $nbProductsInBdd
* @return void
* @throws \Illuminate\Validation\ValidationException Error exception.
*/
private static function assertLimitProducts(int $nbProductsInBdd): void
{
if ($nbProductsInBdd > 3) {
throw ValidationException::withMessages([
'Vous devez associer au maximum 3 produits.'
]);
}
}
/**
* Limit news associated.
*
* @param integer $nbNewsInBdd
* @return void
* @throws \Illuminate\Validation\ValidationException Error exception.
*/
private static function assertLimitNews(int $nbNewsInBdd): void
{
if ($nbNewsInBdd > 3) {
throw ValidationException::withMessages([
'Vous devez associer au maximum 3 actualités.'
]);
}
}
/**
* Limit news categories associated.
*
* @param integer $nbNewsCategoriesInBdd
* @return void
* @throws \Illuminate\Validation\ValidationException Error exception.
*/
private static function assertLimitNewsCategory(int $nbNewsCategoriesInBdd): void
{
if ($nbNewsCategoriesInBdd < 1 or $nbNewsCategoriesInBdd > 2) {
throw ValidationException::withMessages([
trans('Vous devez associer une actualité à 1 ou 2 catégories.')
]);
}
}
/**
* Asserts using validation that the title is unique.
*
* @param string $title
* @param integer|null $id
* @return void
*/
private static function assertTitleIsUnique(string $title, ?int $id = null): void
{
$table = (new self())->getTable();
ToolboxHelper::assertFieldIsUnique($table, 'title', $title, $id);
ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($title), $id);
}
/**
* Getter reading_time.
*
* @return string
*/
public function getReadingTime(): string
{
$allWords = count(explode(
" ",
($this->title . " " .
$this->subtitle . " " .
$this->content . " " .
$this->content2 . " " .
\Carbon\Carbon::parse($this->event_start)->locale('fr_FR')->isoFormat('D MMM Y')
)
));
$time = round($allWords / 140, 0);
return ($time < 1) ? round(($allWords / 140) * 60, 0) . " seconde(s)" : $time . " minute(s)";
}
// * REDIRECTIONS.
/**
* Get the front url of this model.
* Should return the model.show route, with all binded elements if needed.
*
* @param string $modelKey
* @return string
*/
public function getFrontUrl(string $modelKey): string
{
return route('fo.news.show', $modelKey);
}
// * RELATIONSHIPS
/**
* News Morph-To-Many relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
* @phpcs:disable Generic.NamingConventions.ConstructorName.OldStyle
*/
public function news(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
// phpcs:enable
return $this->belongsToMany(News::class, 'news_news', 'news_id', 'news_related_id');
}
/**
* Products Morph-To-Many relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function products(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(Product::class);
}
/**
* Categories Morph-To-Many relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function categories(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(NewsCategory::class);
}
/**
* toSitemapTag method
*
* @return Url|string|array
*/
public function toSitemapTag(): Url | string | array
{
$model = $this;
$route = 'fo.news.show';
$params = ['actu' => $model];
return SitemapHelper::generateUrl($route, $params, $model);
}
/**
* Transform to seoModel
*
* @return \Uwil\Seo\Laravel\Objects\SeoItem
*/
public function toSeoItem(): SeoItem
{
return new SeoItem(
\trans($this->getTable()),
$this->seo_title,
$this->seo_description,
$this->published ?? false,
\route(\config('seo.bo_route_prefix') . $this->getTable() . '.edit', $this),
route('fo.news.show', $this)
);
}
}