feat: add posts:publish command for WordPress REST API publishing
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Post;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class PublishPost extends Command
|
||||
{
|
||||
protected $signature = 'posts:publish {post}';
|
||||
|
||||
protected $description = 'Publish an existing blog post to its site\'s WordPress REST API';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$post = Post::with('site')->find($this->argument('post'));
|
||||
|
||||
if (! $post) {
|
||||
return $this->failWith("Post {$this->argument('post')} not found.");
|
||||
}
|
||||
|
||||
if ($post->type !== 'blog') {
|
||||
return $this->failWith("Post {$post->id} has type '{$post->type}', expected 'blog' to publish to a CMS.");
|
||||
}
|
||||
|
||||
if (! $post->title) {
|
||||
return $this->failWith("Post {$post->id} has no title, required to publish to WordPress.");
|
||||
}
|
||||
|
||||
$site = $post->site;
|
||||
|
||||
if ($site->cms_type !== 'wordpress') {
|
||||
return $this->failWith("Site '{$site->name}' is not configured as WordPress (cms_type={$site->cms_type}).");
|
||||
}
|
||||
|
||||
if (! $site->wp_username || ! $site->wp_app_password) {
|
||||
return $this->failWith("Site '{$site->name}' is missing WordPress credentials.");
|
||||
}
|
||||
|
||||
try {
|
||||
$response = Http::withBasicAuth($site->wp_username, $site->wp_app_password)
|
||||
->post(rtrim($site->url, '/') . '/wp-json/wp/v2/posts', [
|
||||
'title' => $post->title,
|
||||
'content' => $post->body,
|
||||
'status' => 'publish',
|
||||
]);
|
||||
} catch (ConnectionException $e) {
|
||||
return $this->publishFailed($post, "could not connect to site: {$e->getMessage()}");
|
||||
}
|
||||
|
||||
if ($response->failed()) {
|
||||
$message = $response->json('message') ?? 'unexpected response from WordPress';
|
||||
|
||||
return $this->publishFailed($post, $message);
|
||||
}
|
||||
|
||||
$link = $response->json('link');
|
||||
|
||||
if (! $link) {
|
||||
return $this->publishFailed($post, 'unexpected response from WordPress: missing post link');
|
||||
}
|
||||
|
||||
$post->update(['status' => 'published', 'published_url' => $link]);
|
||||
|
||||
$this->line(json_encode(['success' => true, 'url' => $link]));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function failWith(string $message): int
|
||||
{
|
||||
$this->line(json_encode(['success' => false, 'error' => $message]));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
private function publishFailed(Post $post, string $message): int
|
||||
{
|
||||
$post->update(['status' => 'failed']);
|
||||
|
||||
return $this->failWith($message);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user