Files
muninn/app/Jobs/PublishPostJob.php
T

61 lines
1.7 KiB
PHP
Raw Normal View History

<?php
namespace App\Jobs;
use App\Models\Post;
use App\Support\Publishing\PublisherManager;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class PublishPostJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $timeout = 150;
public function __construct(public readonly int $postId) {}
public function handle(PublisherManager $publishers): void
{
$post = Post::with(['site', 'socialAccount'])->find($this->postId);
if (! $post) {
return;
}
// A duplicate/stale job for a post already resolved by an earlier
// run of this same job (e.g. a double-dispatch while no worker was
// running) — skip it rather than risk publishing twice.
if ($post->status !== 'publishing') {
return;
}
$publisher = $publishers->resolve($post);
if (! $publisher) {
$post->update(['status' => 'draft', 'publish_error' => "No publisher available for post type '{$post->type}'."]);
return;
}
$result = $publisher->publish($post);
if ($result->success) {
$post->update(['status' => 'published', 'published_url' => $result->url, 'publish_error' => null]);
return;
}
$post->update([
'status' => $result->attempted ? 'failed' : 'draft',
'publish_error' => $result->error,
]);
Log::error('post publish failed', ['post_id' => $post->id, 'error' => $result->error]);
}
}