|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Models; |
| 4 | + |
| 5 | +use App\Models\Scopes\LatestPublishedOrderScope; |
| 6 | +use Illuminate\Database\Eloquent\Attributes\ScopedBy; |
| 7 | +use Illuminate\Database\Eloquent\Casts\Attribute; |
| 8 | +use Illuminate\Database\Eloquent\Model; |
| 9 | +use Spatie\YamlFrontMatter\YamlFrontMatter; |
| 10 | +use Sushi\Sushi; |
| 11 | +use Symfony\Component\Finder\Finder; |
| 12 | + |
| 13 | +#[ScopedBy(LatestPublishedOrderScope::class)] |
| 14 | +class Post extends Model |
| 15 | +{ |
| 16 | + use Sushi; |
| 17 | + |
| 18 | + protected function casts(): array |
| 19 | + { |
| 20 | + return [ |
| 21 | + 'published_at' => 'datetime', |
| 22 | + ]; |
| 23 | + } |
| 24 | + |
| 25 | + /** @return array<int, array<string, mixed>> */ |
| 26 | + public function getRows(): array |
| 27 | + { |
| 28 | + return collect($this->files()) |
| 29 | + ->map(fn (string $file): array => $this->parseFile($file)) |
| 30 | + ->sortByDesc('published_at') |
| 31 | + ->values() |
| 32 | + ->toArray(); |
| 33 | + } |
| 34 | + |
| 35 | + protected function files(): Finder |
| 36 | + { |
| 37 | + return Finder::create() |
| 38 | + ->files() |
| 39 | + ->in(resource_path('content/blog')) |
| 40 | + ->name('*.md'); |
| 41 | + } |
| 42 | + |
| 43 | + /** @return array<string, mixed> */ |
| 44 | + protected function parseFile(string $file): array |
| 45 | + { |
| 46 | + $document = YamlFrontMatter::parseFile($file); |
| 47 | + |
| 48 | + // Default values for all possible fields |
| 49 | + $defaults = [ |
| 50 | + 'title' => '', |
| 51 | + 'description' => '', |
| 52 | + 'published_at' => null, |
| 53 | + 'slug' => basename($file, '.md'), |
| 54 | + 'content' => '', |
| 55 | + ]; |
| 56 | + |
| 57 | + return array_merge( |
| 58 | + $defaults, |
| 59 | + $document->matter(), |
| 60 | + [ |
| 61 | + 'slug' => basename($file, '.md'), // Always override slug |
| 62 | + 'content' => $document->body(), // Store markdown content |
| 63 | + ], |
| 64 | + ); |
| 65 | + } |
| 66 | + |
| 67 | + /** @return Attribute<string, never> */ |
| 68 | + protected function formattedDate(): Attribute |
| 69 | + { |
| 70 | + return Attribute::make( |
| 71 | + get: fn (): string => $this->getAttribute('published_at')?->format('F j, Y') ?? '', |
| 72 | + ); |
| 73 | + } |
| 74 | +} |
0 commit comments