56 lines
1.7 KiB
PHP
56 lines
1.7 KiB
PHP
<?php
|
|||
|
|
|
||
|
|
namespace App\Support\Publishing;
|
||
|
|
|
||
|
|
use App\Models\Post;
|
||
|
|
use Illuminate\Http\Client\ConnectionException;
|
||
|
|
use Illuminate\Support\Facades\Http;
|
||
|
|
|
||
|
|
class WordPressPublisher implements Publisher
|
||
|
|
{
|
||
|
|
public function supports(Post $post): bool
|
||
|
|
{
|
||
|
|
return $post->type === 'blog';
|
||
|
|
}
|
||
|
|
|
||
|
|
public function publish(Post $post): PublishResult
|
||
|
|
{
|
||
|
|
if (! $post->title) {
|
||
|
|
return PublishResult::rejected("Post {$post->id} has no title, required to publish to WordPress.");
|
||
|
|
}
|
||
|
|
|
||
|
|
$site = $post->site;
|
||
|
|
|
||
|
|
if ($site->cms_type !== 'wordpress') {
|
||
|
|
return PublishResult::rejected("Site '{$site->name}' is not configured as WordPress (cms_type={$site->cms_type}).");
|
||
|
|
}
|
||
|
|
|
||
|
|
if (! $site->wp_username || ! $site->wp_app_password) {
|
||
|
|
return PublishResult::rejected("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 PublishResult::failed("could not connect to site: {$e->getMessage()}");
|
||
|
|
}
|
||
|
|
|
||
|
|
if ($response->failed()) {
|
||
|
|
return PublishResult::failed($response->json('message') ?? 'unexpected response from WordPress');
|
||
|
|
}
|
||
|
|
|
||
|
|
$link = $response->json('link');
|
||
|
|
|
||
|
|
if (! $link) {
|
||
|
|
return PublishResult::failed('unexpected response from WordPress: missing post link');
|
||
|
|
}
|
||
|
|
|
||
|
|
return PublishResult::success($link);
|
||
|
|
}
|
||
|
|
}
|