|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Cachet\Filament\Widgets; |
| 4 | + |
| 5 | +use Filament\Widgets\Concerns\CanPoll; |
| 6 | +use Filament\Widgets\Widget; |
| 7 | +use Illuminate\Support\Carbon; |
| 8 | +use Illuminate\Support\Facades\Blade; |
| 9 | +use Illuminate\Support\Facades\Cache; |
| 10 | +use Illuminate\Support\Str; |
| 11 | +use Illuminate\Support\Uri; |
| 12 | +use Throwable; |
| 13 | + |
| 14 | +class Feed extends Widget |
| 15 | +{ |
| 16 | + use CanPoll; |
| 17 | + |
| 18 | + protected int|string|array $columnSpan = 'full'; |
| 19 | + |
| 20 | + protected static string $view = 'cachet::filament.widgets.feed'; |
| 21 | + |
| 22 | + protected static ?int $sort = 10; |
| 23 | + |
| 24 | + protected function getViewData(): array |
| 25 | + { |
| 26 | + return [ |
| 27 | + 'items' => $this->getFeed(), |
| 28 | + 'noItems' => Blade::render($this->getEmptyBlock()), |
| 29 | + ]; |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Get the generated empty block text. |
| 34 | + */ |
| 35 | + public function getEmptyBlock(): string |
| 36 | + { |
| 37 | + return preg_replace( |
| 38 | + '/\*(.*?)\*/', |
| 39 | + '<x-filament::link href="'.config('cachet.feed.uri').'" target="_blank" rel="nofollow noopener">$1</x-filament::link>', |
| 40 | + __('cachet::cachet.feed.empty') |
| 41 | + ); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Get the feed from the cache or fetch it fresh. |
| 46 | + */ |
| 47 | + protected function getFeed(): array |
| 48 | + { |
| 49 | + return Cache::flexible('cachet-feed', [ |
| 50 | + 60 * 15, |
| 51 | + 60 * 60, |
| 52 | + ], fn () => $this->fetchFeed( |
| 53 | + config('cachet.feed.uri') |
| 54 | + )); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Fetch the data from the given RSS feed. |
| 59 | + */ |
| 60 | + protected function fetchFeed(string $uri, int $maxPosts = 5): array |
| 61 | + { |
| 62 | + try { |
| 63 | + $xml = simplexml_load_string(file_get_contents($uri)); |
| 64 | + |
| 65 | + $posts = []; |
| 66 | + |
| 67 | + $feedItems = $xml->channel->item ?? $xml->entry ?? []; |
| 68 | + $feedIndex = 0; |
| 69 | + |
| 70 | + foreach ($feedItems as $item) { |
| 71 | + if ($feedIndex >= $maxPosts) { |
| 72 | + break; |
| 73 | + } |
| 74 | + |
| 75 | + $posts[] = [ |
| 76 | + 'title' => (string)($item->title ?? ''), |
| 77 | + 'link' => Uri::of((string)($item->link ?? ''))->withQuery([ |
| 78 | + 'ref' => 'cachet-dashboard', |
| 79 | + ]), |
| 80 | + 'description' => Str::of($item->description ?? $item->summary ?? '')->limit(preserveWords: true), |
| 81 | + 'date' => Carbon::parse((string)($item->pubDate ?? $item->updated ?? '')), |
| 82 | + ]; |
| 83 | + |
| 84 | + $feedIndex++; |
| 85 | + } |
| 86 | + |
| 87 | + return $posts; |
| 88 | + } catch (Throwable $e) { |
| 89 | + return []; |
| 90 | + } |
| 91 | + } |
| 92 | +} |
0 commit comments