85 lines
2.4 KiB
PHP
85 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Support\Str;
|
|
use IriksIT\Manager\Support\Markdown;
|
|
|
|
class Post extends Model
|
|
{
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'tags' => 'array',
|
|
'is_featured' => 'boolean',
|
|
'published_at' => 'datetime',
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Posts that are visible on the public site: published and not scheduled for later.
|
|
*
|
|
* @param Builder<Post> $query
|
|
*/
|
|
public function scopePublished(Builder $query): void
|
|
{
|
|
$query->whereNotNull('published_at')->where('published_at', '<=', now());
|
|
}
|
|
|
|
public function isPublished(): bool
|
|
{
|
|
return $this->published_at !== null && $this->published_at->lte(now());
|
|
}
|
|
|
|
/** `draft`, `scheduled` or `published`. */
|
|
public function status(): string
|
|
{
|
|
return match (true) {
|
|
$this->published_at === null => 'draft',
|
|
$this->published_at->isFuture() => 'scheduled',
|
|
default => 'published',
|
|
};
|
|
}
|
|
|
|
/** A slug for $title that no other post uses yet. */
|
|
public static function uniqueSlug(string $title, ?int $ignoreId = null): string
|
|
{
|
|
$base = Str::slug($title) ?: 'post';
|
|
$slug = $base;
|
|
$suffix = 2;
|
|
|
|
while (static::query()->where('slug', $slug)->when($ignoreId, fn (Builder $q) => $q->whereKeyNot($ignoreId))->exists()) {
|
|
$slug = $base.'-'.$suffix++;
|
|
}
|
|
|
|
return $slug;
|
|
}
|
|
|
|
public function readingMinutes(): int
|
|
{
|
|
return max(1, (int) ceil(str_word_count(strip_tags($this->body)) / 220));
|
|
}
|
|
|
|
/**
|
|
* The fields a post card or listing needs, for the host's public pages.
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function toCard(): array
|
|
{
|
|
return [
|
|
'title' => $this->title,
|
|
'slug' => $this->slug,
|
|
'excerpt' => $this->excerpt ?? Str::limit(Markdown::toPlainText($this->body), 160),
|
|
'cover_image' => $this->cover_image,
|
|
'cover_focus' => Media::focusFor($this->cover_image),
|
|
'category' => $this->category,
|
|
'tags' => $this->tags ?? [],
|
|
'is_featured' => $this->is_featured,
|
|
'published_at' => $this->published_at?->toIso8601String(),
|
|
'reading_minutes' => $this->readingMinutes(),
|
|
];
|
|
}
|
|
}
|