*/ protected $fillable = [ 'title', 'content', 'url', 'picture', 'picture_alt', 'picture_title', 'published', 'publish_at', 'unpublish_at', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'published' => 'boolean', 'publish_at' => 'datetime', 'unpublish_at' => 'datetime', ]; /** * Perform any actions required after the model boots. */ protected static function booted(): void { static::creating(function (self $newsCorporate) { self::makeStatusSense($newsCorporate); $newsCorporate->picture = FileStorageHelper::storeFile($newsCorporate, $newsCorporate->picture, true); }); static::created(function () { self::resetCache(); }); static::updating(function (self $newsCorporate) { self::makeStatusSense($newsCorporate); $newsCorporate->picture = FileStorageHelper::storeFile($newsCorporate, $newsCorporate->picture, true); }); static::updated(function (self $newsCorporate) { FileStorageHelper::removeOldFile($newsCorporate, 'picture'); self::resetCache(); }); static::deleted(function (self $newsCorporate) { FileStorageHelper::removeFile($newsCorporate, 'picture'); self::resetCache(); }); } // * METHODS /** * Adjusts newsCorporate status using current status and publish dates. */ private static function makeStatusSense(self $newsCorporate): void { /** @var \Carbon\Carbon|null */ $publish_at = $newsCorporate->publish_at; /** @var \Carbon\Carbon|null */ $unpublish_at = $newsCorporate->unpublish_at; $wantedStatus = $newsCorporate->published; if ($publish_at or $unpublish_at) { $newsCorporate->published = $newsCorporate->planificated_status; } if ($wantedStatus !== $newsCorporate->published) { session()->flash('bo.info', \trans( 'La publication est modifiée en concordance avec les dates enregistrées. Pour modifier l\'état de publication, veuillez modifier ou enlever les dates correspondantes.' )); } } /** * Getter the current status following planification dates planificated_status. */ public function getPlanificatedStatusAttribute(): bool { /** @var \Carbon\Carbon|null */ $publish_at = $this->publish_at; /** @var \Carbon\Carbon|null */ $unpublish_at = $this->unpublish_at; if ($publish_at and $unpublish_at) { return $unpublish_at->greaterThanOrEqualTo(now()) and $publish_at->lessThan(now()); } if ($publish_at) { return $publish_at->lessThan(now()); } if ($unpublish_at) { return $unpublish_at->greaterThanOrEqualTo(now()); } return false; } /** * Reset all cache elements related to this model. */ private static function resetCache(): void { Cache::forget('9publishedNewsCorporateOrderedByUpdatedAt'); self::get9PublishedOrderedByUpdatedAt(); } /** * Get 9 published news corporate ordered by updated_at. */ public static function get9PublishedOrderedByUpdatedAt(): Collection { return Cache::remember('9publishedNewsCorporateOrderedByUpdatedAt', 86400, function () { return self::query()->where('published', true)->orderByDesc('updated_at')->limit(9)->get(); }); } }