feat: content-create and content-update with schema validation
All-or-nothing writes: validation (fields, terms, featured image, parent, template) before any write; failed extras delete the new draft (create) or restore revision, old columns, fields, terms and featured image (update). content-update requires rev; Rev::ofPost covers content, title, excerpt, status and post_modified_gmt. MetaFieldSource::write() now throws on failure. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01At3V6SjwbMe6eMzVGW3Hs7
This commit is contained in:
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\WordPress\Content;
|
||||
|
||||
use LIT\MCP\Abilities\Ability;
|
||||
use LIT\MCP\Abilities\Errors;
|
||||
use LIT\MCP\Abilities\Rev;
|
||||
use LIT\MCP\Abilities\ToolResult;
|
||||
use LIT\MCP\ChangeLog\ChangeLog;
|
||||
use LIT\MCP\Integrations\WordPress\PostGuard;
|
||||
use LIT\MCP\Integrations\WordPress\Schema\ContentSchema;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
use WP_Error;
|
||||
use WP_Post;
|
||||
|
||||
/**
|
||||
* lit/content-create: new entry, always a draft. All or nothing (spec §8.2): input is
|
||||
* validated before the insert; if fields, terms or the featured image cannot be written
|
||||
* afterwards, the brand-new draft is deleted again and the error is rethrown (the
|
||||
* AbilityRegistrar logs it and reports lit_internal_error).
|
||||
*/
|
||||
final class ContentCreateAbility implements Ability
|
||||
{
|
||||
public function __construct(
|
||||
private ContentSchema $schema,
|
||||
private PostWriter $writer,
|
||||
private ChangeLog $log
|
||||
) {
|
||||
}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'lit/content-create';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Inhalt anlegen';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Legt einen neuen Eintrag an – immer als Entwurf (veröffentlichen nur über lit-post-publish). '
|
||||
. 'Kerndaten, Begriffe, Felder (gegen das Schema aus lit-content-types geprüft) und Beitragsbild '
|
||||
. 'in einem Schritt; bei einem Fehler wird nichts angelegt.';
|
||||
}
|
||||
|
||||
public function inputSchema(): array
|
||||
{
|
||||
return [
|
||||
'type' => 'object',
|
||||
'properties' => array_merge([
|
||||
'post_type' => ['type' => 'string'],
|
||||
'title' => ['type' => 'string', 'minLength' => 1],
|
||||
], PostWriter::inputProperties()),
|
||||
'required' => ['post_type', 'title'],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public function outputSchema(): ?array
|
||||
{
|
||||
return ToolResult::schema();
|
||||
}
|
||||
|
||||
public function annotations(): array
|
||||
{
|
||||
return ['readonly' => false, 'destructive' => false, 'idempotent' => false];
|
||||
}
|
||||
|
||||
public function isDirect(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function permission(array $input): bool|WP_Error
|
||||
{
|
||||
$type = PostGuard::postType($input['post_type'] ?? null, $this->schema, 'create_posts');
|
||||
|
||||
return $type instanceof WP_Error ? $type : true;
|
||||
}
|
||||
|
||||
public function execute(array $input): mixed
|
||||
{
|
||||
$type = PostGuard::postType($input['post_type'] ?? null, $this->schema, 'create_posts');
|
||||
if ($type instanceof WP_Error) {
|
||||
return $type;
|
||||
}
|
||||
|
||||
$postType = (string) $input['post_type'];
|
||||
$prepared = $this->writer->prepare($postType, $input, true);
|
||||
if ($prepared instanceof WP_Error) {
|
||||
return $prepared;
|
||||
}
|
||||
|
||||
$data = array_merge($this->writer->postData($input), [
|
||||
'post_type' => $postType,
|
||||
'post_status' => 'draft',
|
||||
'post_author' => get_current_user_id(),
|
||||
]);
|
||||
$postId = wp_insert_post(wp_slash($data), true);
|
||||
if ($postId instanceof WP_Error) {
|
||||
return Errors::invalidInput('WordPress hat den Eintrag abgelehnt: ' . $postId->get_error_message());
|
||||
}
|
||||
|
||||
$postId = (int) $postId;
|
||||
try {
|
||||
$this->writer->writeExtras($postId, $postType, $prepared, $input);
|
||||
} catch (Throwable $e) {
|
||||
$this->discard($postId, $e);
|
||||
}
|
||||
do_action('lit_mcp_after_save', $postId, $this->name(), $input);
|
||||
|
||||
$post = get_post($postId);
|
||||
$title = $post instanceof WP_Post ? (string) $post->post_title : (string) $input['title'];
|
||||
$summary = sprintf('Entwurf "%s" angelegt', $title);
|
||||
$logId = $this->log->record($this->name(), $postType, (string) $postId, $summary);
|
||||
|
||||
return ToolResult::ok(sprintf('"%s" als Entwurf angelegt (ID %d).', $title, $postId))
|
||||
->changed((string) $postId, $postType, 'created', $title)
|
||||
->rev($post instanceof WP_Post ? Rev::ofPost($post) : null)
|
||||
->logId($logId)
|
||||
->urls((string) get_preview_post_link($postId), (string) get_edit_post_link($postId, 'raw'))
|
||||
->warnings($prepared['warnings'])
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the draft this call just created (it cannot have been used anywhere yet).
|
||||
*
|
||||
* @throws RuntimeException Always – the original failure, noting whether the draft is gone.
|
||||
*/
|
||||
private function discard(int $postId, Throwable $cause): never
|
||||
{
|
||||
$deleted = wp_delete_post($postId, true);
|
||||
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Extras of new post %d could not be written (%s); draft %s.',
|
||||
$postId,
|
||||
$cause->getMessage(),
|
||||
$deleted ? 'deleted again' : 'could NOT be deleted'
|
||||
),
|
||||
0,
|
||||
$cause
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\WordPress\Content;
|
||||
|
||||
use LIT\MCP\Abilities\Ability;
|
||||
use LIT\MCP\Abilities\Errors;
|
||||
use LIT\MCP\Abilities\Rev;
|
||||
use LIT\MCP\Abilities\ToolResult;
|
||||
use LIT\MCP\ChangeLog\ChangeLog;
|
||||
use LIT\MCP\Integrations\WordPress\PostGuard;
|
||||
use LIT\MCP\Integrations\WordPress\RevisionPoint;
|
||||
use LIT\MCP\Integrations\WordPress\Schema\ContentSchema;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
use WP_Error;
|
||||
use WP_Post;
|
||||
|
||||
/**
|
||||
* lit/content-update: changes an entry without touching its status. rev (from
|
||||
* lit/content-get) is required so parallel edits are never overwritten (spec §2
|
||||
* principle 7). All or nothing (spec §8.2): input is validated first; if fields,
|
||||
* terms or the featured image fail after the post row was updated, the row is
|
||||
* restored from the restore-point revision (plus old values for columns revisions
|
||||
* do not cover), the extras get their old values back, and the error is rethrown
|
||||
* (the AbilityRegistrar logs it and reports lit_internal_error).
|
||||
*/
|
||||
final class ContentUpdateAbility implements Ability
|
||||
{
|
||||
private const CHANGE_KEYS = [
|
||||
'title', 'content', 'excerpt', 'slug', 'parent', 'menu_order', 'template', 'terms', 'fields', 'featured_image',
|
||||
];
|
||||
|
||||
/** Post columns a revision stores (and wp_restore_post_revision() restores). */
|
||||
private const REVISIONED = ['post_title', 'post_content', 'post_excerpt'];
|
||||
|
||||
public function __construct(
|
||||
private ContentSchema $schema,
|
||||
private PostWriter $writer,
|
||||
private ChangeLog $log
|
||||
) {
|
||||
}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'lit/content-update';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Inhalt ändern';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Ändert Kerndaten, Begriffe, Felder oder Beitragsbild eines Eintrags; der Status bleibt '
|
||||
. 'unverändert (veröffentlichte Inhalte werden live geändert, vorher entsteht eine Revision). '
|
||||
. 'rev aus lit-content-get ist Pflicht, damit parallele Änderungen nicht überschrieben werden; '
|
||||
. 'die Antwort enthält die neue rev für weitere Änderungen. '
|
||||
. 'content von Divi-Seiten ist hier nicht änderbar.';
|
||||
}
|
||||
|
||||
public function inputSchema(): array
|
||||
{
|
||||
return [
|
||||
'type' => 'object',
|
||||
'properties' => array_merge([
|
||||
'post_id' => ['type' => 'integer', 'minimum' => 1],
|
||||
'rev' => ['type' => 'string', 'description' => 'rev aus lit-content-get (optimistische Sperre).'],
|
||||
'title' => ['type' => 'string', 'minLength' => 1],
|
||||
], PostWriter::inputProperties()),
|
||||
'required' => ['post_id', 'rev'],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public function outputSchema(): ?array
|
||||
{
|
||||
return ToolResult::schema();
|
||||
}
|
||||
|
||||
public function annotations(): array
|
||||
{
|
||||
return ['readonly' => false, 'destructive' => false, 'idempotent' => true];
|
||||
}
|
||||
|
||||
public function isDirect(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function permission(array $input): bool|WP_Error
|
||||
{
|
||||
$post = PostGuard::editable($input['post_id'] ?? null, $this->schema);
|
||||
|
||||
return $post instanceof WP_Error ? $post : true;
|
||||
}
|
||||
|
||||
public function execute(array $input): mixed
|
||||
{
|
||||
$post = PostGuard::editable($input['post_id'] ?? null, $this->schema);
|
||||
if ($post instanceof WP_Error) {
|
||||
return $post;
|
||||
}
|
||||
|
||||
if (! isset($input['rev']) || $input['rev'] !== Rev::ofPost($post)) {
|
||||
return Errors::revMismatch();
|
||||
}
|
||||
|
||||
if (array_key_exists('content', $input) && PostPresenter::usesDivi($post)) {
|
||||
return Errors::unsupported(
|
||||
'Divi-Inhalte können nicht als Rohtext überschrieben werden; nichts wurde gespeichert.',
|
||||
'Divi-Struktur über lit-divi-outline und die lit-divi-*-Tools bearbeiten; Titel, Auszug, '
|
||||
. 'Felder und Begriffe hier ohne content ändern.'
|
||||
);
|
||||
}
|
||||
|
||||
$data = $this->writer->postData($input);
|
||||
if ($data === [] && ! $this->writer->hasExtras($input)) {
|
||||
return Errors::invalidInput(
|
||||
'Nichts zu ändern.',
|
||||
[],
|
||||
'Mindestens eines angeben: ' . implode(', ', self::CHANGE_KEYS) . '.'
|
||||
);
|
||||
}
|
||||
|
||||
$postType = (string) $post->post_type;
|
||||
$prepared = $this->writer->prepare($postType, $input, false);
|
||||
if ($prepared instanceof WP_Error) {
|
||||
return $prepared;
|
||||
}
|
||||
|
||||
$postId = (int) $post->ID;
|
||||
$snapshot = $this->writer->snapshot($postId, $postType, $prepared, $input);
|
||||
$revisionId = RevisionPoint::capture($postId);
|
||||
|
||||
$rowUpdated = false;
|
||||
try {
|
||||
if ($data !== []) {
|
||||
$result = wp_update_post(wp_slash(array_merge($data, ['ID' => $postId])), true);
|
||||
if ($result instanceof WP_Error) {
|
||||
return Errors::invalidInput(
|
||||
'WordPress hat die Änderung abgelehnt: ' . $result->get_error_message()
|
||||
);
|
||||
}
|
||||
$rowUpdated = true;
|
||||
}
|
||||
|
||||
$this->writer->writeExtras($postId, $postType, $prepared, $input);
|
||||
} catch (Throwable $e) {
|
||||
$this->rollBack($post, $rowUpdated ? $data : [], $revisionId, $snapshot, $e);
|
||||
}
|
||||
do_action('lit_mcp_after_save', $postId, $this->name(), $input);
|
||||
|
||||
$updated = get_post($postId);
|
||||
$updated = $updated instanceof WP_Post ? $updated : $post;
|
||||
$changedKeys = array_keys(array_intersect_key($input, array_flip(self::CHANGE_KEYS)));
|
||||
$summary = sprintf('"%s" geändert: %s', $updated->post_title, implode(', ', $changedKeys));
|
||||
$logId = $this->log->record($this->name(), $postType, (string) $postId, $summary, $revisionId);
|
||||
|
||||
return ToolResult::ok(sprintf('%s (Status unverändert: %s).', $summary, $updated->post_status))
|
||||
->changed((string) $postId, $postType, 'updated', (string) $updated->post_title)
|
||||
->rev(Rev::ofPost($updated))
|
||||
->revisionId($revisionId)
|
||||
->logId($logId)
|
||||
->urls((string) get_preview_post_link($updated), (string) get_edit_post_link($postId, 'raw'))
|
||||
->warnings($prepared['warnings'])
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data Columns that were written to the post row.
|
||||
* @param array<string, mixed> $snapshot Output of PostWriter::snapshot().
|
||||
* @throws RuntimeException Always – the original failure plus the rollback outcome.
|
||||
*/
|
||||
private function rollBack(WP_Post $post, array $data, ?int $revisionId, array $snapshot, Throwable $cause): never
|
||||
{
|
||||
$failures = [];
|
||||
try {
|
||||
$this->writer->restore((int) $post->ID, (string) $post->post_type, $snapshot);
|
||||
} catch (Throwable $e) {
|
||||
$failures[] = $e->getMessage();
|
||||
}
|
||||
|
||||
try {
|
||||
$this->restoreRow($post, $data, $revisionId);
|
||||
} catch (Throwable $e) {
|
||||
$failures[] = $e->getMessage();
|
||||
}
|
||||
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Update of post %d failed (%s); %s.',
|
||||
(int) $post->ID,
|
||||
$cause->getMessage(),
|
||||
$failures === [] ? 'changes rolled back' : 'rollback incomplete: ' . implode('; ', $failures)
|
||||
),
|
||||
0,
|
||||
$cause
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Title, content and excerpt come back from the restore-point revision when that
|
||||
* revision reflects the pre-update state (revisions enabled: RevisionPoint then
|
||||
* saved or confirmed it). Everything else – and everything when revisions are off,
|
||||
* where the newest revision may be stale – gets the value read before the update.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
private function restoreRow(WP_Post $post, array $data, ?int $revisionId): void
|
||||
{
|
||||
if ($data === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$old = [];
|
||||
foreach (array_keys($data) as $column) {
|
||||
$old[$column] = $column === 'page_template'
|
||||
? ((string) get_page_template_slug($post) ?: PostWriter::DEFAULT_TEMPLATE)
|
||||
: $post->{$column};
|
||||
}
|
||||
|
||||
$fromRevision = array_values(array_intersect(array_keys($old), self::REVISIONED));
|
||||
if ($revisionId !== null && $fromRevision !== [] && wp_revisions_enabled($post)) {
|
||||
$restored = wp_restore_post_revision($revisionId, $fromRevision);
|
||||
if ($restored && ! is_wp_error($restored)) {
|
||||
$old = array_diff_key($old, array_flip($fromRevision));
|
||||
}
|
||||
}
|
||||
|
||||
if ($old === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$result = wp_update_post(wp_slash(array_merge($old, ['ID' => (int) $post->ID])), true);
|
||||
if ($result instanceof WP_Error || ! $result) {
|
||||
$message = $result instanceof WP_Error ? $result->get_error_message() : 'unknown error';
|
||||
throw new RuntimeException('Post row could not be restored: ' . $message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ class PostPresenter
|
||||
'terms' => JsonMap::of($this->terms($post)),
|
||||
'fields' => JsonMap::of($this->fields($post)),
|
||||
'featured_image' => $this->featuredImage($post),
|
||||
'rev' => Rev::of((string) $post->post_content),
|
||||
'rev' => Rev::ofPost($post),
|
||||
'hints' => $divi ? [self::DIVI_HINT] : [],
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\WordPress\Content;
|
||||
|
||||
use LIT\MCP\Abilities\Errors;
|
||||
use LIT\MCP\Integrations\WordPress\Schema\ContentSchema;
|
||||
use LIT\MCP\Integrations\WordPress\Schema\FieldValidator;
|
||||
use LIT\MCP\Integrations\WordPress\Schema\TermAssigner;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
use WP_Error;
|
||||
use WP_Post;
|
||||
|
||||
/**
|
||||
* Shared validation and write logic of lit/content-create and lit/content-update.
|
||||
* prepare() validates everything before the first write (all or nothing, spec §8.2);
|
||||
* snapshot()/restore() let lit/content-update undo the extras when a later write fails.
|
||||
* Not final so the abilities can be unit-tested with a mock.
|
||||
*/
|
||||
class PostWriter
|
||||
{
|
||||
private const POST_FIELDS = [
|
||||
'title' => 'post_title',
|
||||
'content' => 'post_content',
|
||||
'excerpt' => 'post_excerpt',
|
||||
'slug' => 'post_name',
|
||||
'parent' => 'post_parent',
|
||||
'menu_order' => 'menu_order',
|
||||
'template' => 'page_template',
|
||||
];
|
||||
|
||||
/** wp_insert_post() ignores an empty page_template; this value selects the default template. */
|
||||
public const DEFAULT_TEMPLATE = 'default';
|
||||
|
||||
public function __construct(
|
||||
private ContentSchema $schema,
|
||||
private FieldValidator $validator,
|
||||
private TermAssigner $terms
|
||||
) {
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
public static function inputProperties(): array
|
||||
{
|
||||
return [
|
||||
'content' => ['type' => 'string', 'description' => 'HTML bzw. Block-Markup (nicht für Divi-Inhalte).'],
|
||||
'excerpt' => ['type' => 'string'],
|
||||
'slug' => ['type' => 'string'],
|
||||
'parent' => ['type' => 'integer', 'minimum' => 0],
|
||||
'menu_order' => ['type' => 'integer'],
|
||||
'template' => ['type' => 'string', 'description' => 'Seiten-Template (Dateiname), leer = Standard.'],
|
||||
'terms' => [
|
||||
'type' => 'object',
|
||||
'additionalProperties' => ['type' => 'array', 'items' => ['type' => ['integer', 'string']]],
|
||||
'description' => 'Je Taxonomie die vollständige Liste der Begriffe (IDs oder Namen); '
|
||||
. 'ersetzt die bisherige Zuordnung dieser Taxonomie.',
|
||||
],
|
||||
'fields' => [
|
||||
'type' => 'object',
|
||||
'description' => 'Feldwerte nach Schlüssel (siehe lit-content-types); null leert ein Feld.',
|
||||
],
|
||||
'featured_image' => [
|
||||
'type' => ['integer', 'null'],
|
||||
'minimum' => 0,
|
||||
'description' => 'Anhang-ID des Beitragsbilds; 0 oder null entfernt es.',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $input
|
||||
* @return array<string, mixed>|WP_Error Keys fields, terms (taxonomy => list<int|string>), warnings.
|
||||
*/
|
||||
public function prepare(string $postType, array $input, bool $isCreate): array|WP_Error
|
||||
{
|
||||
$errors = [];
|
||||
|
||||
$fields = $this->validator->validate(
|
||||
$this->schema->fields($postType),
|
||||
is_array($input['fields'] ?? null) ? $input['fields'] : [],
|
||||
$isCreate
|
||||
);
|
||||
foreach ($fields['errors'] as $key => $message) {
|
||||
$errors['fields.' . $key] = $message;
|
||||
}
|
||||
|
||||
$terms = $this->terms->resolve($postType, is_array($input['terms'] ?? null) ? $input['terms'] : []);
|
||||
foreach ($terms['errors'] as $taxonomy => $message) {
|
||||
$errors['terms.' . $taxonomy] = $message;
|
||||
}
|
||||
|
||||
$checks = [
|
||||
'featured_image' => $this->checkFeaturedImage($postType, $input),
|
||||
'parent' => $this->checkParent($postType, $input),
|
||||
'template' => $this->checkTemplate($postType, $input),
|
||||
];
|
||||
$errors = array_merge($errors, array_filter($checks, static fn (?string $error): bool => $error !== null));
|
||||
|
||||
if ($errors !== []) {
|
||||
return Errors::invalidInput('Eingaben sind ungültig; nichts wurde gespeichert.', $errors);
|
||||
}
|
||||
|
||||
return ['fields' => $fields['values'], 'terms' => $terms['terms'], 'warnings' => $fields['warnings']];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $input
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function postData(array $input): array
|
||||
{
|
||||
$data = [];
|
||||
foreach (self::POST_FIELDS as $key => $column) {
|
||||
if (array_key_exists($key, $input)) {
|
||||
$data[$column] = $input[$key];
|
||||
}
|
||||
}
|
||||
|
||||
if (($data['page_template'] ?? null) === '') {
|
||||
$data['page_template'] = self::DEFAULT_TEMPLATE;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $input */
|
||||
public function hasExtras(array $input): bool
|
||||
{
|
||||
return ! empty($input['fields']) || ! empty($input['terms']) || array_key_exists('featured_image', $input);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{fields: array<string, mixed>, terms: array<string, list<int|string>>} $prepared
|
||||
* @param array<string, mixed> $input
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
public function writeExtras(int $postId, string $postType, array $prepared, array $input): void
|
||||
{
|
||||
$this->terms->assign($postId, $prepared['terms']);
|
||||
$this->writeFields($postId, $postType, $prepared['fields']);
|
||||
|
||||
if (array_key_exists('featured_image', $input)) {
|
||||
$this->setFeaturedImage($postId, (int) ($input['featured_image'] ?? 0));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Current values of everything writeExtras() would change – call before the first write.
|
||||
*
|
||||
* @param array{fields: array<string, mixed>, terms: array<string, list<int|string>>} $prepared
|
||||
* @param array<string, mixed> $input
|
||||
* @return array{fields: array<string, mixed>, terms: array<string, list<int>>, featured_image?: int}
|
||||
*/
|
||||
public function snapshot(int $postId, string $postType, array $prepared, array $input): array
|
||||
{
|
||||
$definitions = $this->schema->fields($postType);
|
||||
$fields = [];
|
||||
foreach (array_keys($prepared['fields']) as $key) {
|
||||
$definition = $definitions[$key];
|
||||
$old = $this->schema->sourceOf($definition)->read($postId, $definition);
|
||||
$fields[$key] = in_array($old, ['', [], null, false], true) ? null : $old;
|
||||
}
|
||||
|
||||
$terms = [];
|
||||
foreach (array_keys($prepared['terms']) as $taxonomy) {
|
||||
$ids = wp_get_object_terms($postId, $taxonomy, ['fields' => 'ids']);
|
||||
if (is_wp_error($ids)) {
|
||||
throw new RuntimeException('Terms could not be read: ' . $ids->get_error_message());
|
||||
}
|
||||
$terms[$taxonomy] = array_map('intval', (array) $ids);
|
||||
}
|
||||
|
||||
$snapshot = ['fields' => $fields, 'terms' => $terms];
|
||||
if (array_key_exists('featured_image', $input)) {
|
||||
$snapshot['featured_image'] = (int) get_post_thumbnail_id($postId);
|
||||
}
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a snapshot back. Tries every part even if one fails.
|
||||
*
|
||||
* @param array{fields: array<string, mixed>, terms: array<string, list<int>>, featured_image?: int} $snapshot
|
||||
* @throws RuntimeException Listing every part that could not be restored.
|
||||
*/
|
||||
public function restore(int $postId, string $postType, array $snapshot): void
|
||||
{
|
||||
$failures = [];
|
||||
$steps = [
|
||||
fn () => $this->terms->assign($postId, $snapshot['terms']),
|
||||
fn () => $this->writeFields($postId, $postType, $snapshot['fields']),
|
||||
];
|
||||
if (array_key_exists('featured_image', $snapshot)) {
|
||||
$steps[] = fn () => $this->setFeaturedImage($postId, (int) $snapshot['featured_image']);
|
||||
}
|
||||
|
||||
foreach ($steps as $step) {
|
||||
try {
|
||||
$step();
|
||||
} catch (Throwable $e) {
|
||||
$failures[] = $e->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
if ($failures !== []) {
|
||||
throw new RuntimeException('Restore incomplete: ' . implode('; ', $failures));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $values
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
private function writeFields(int $postId, string $postType, array $values): void
|
||||
{
|
||||
$definitions = $this->schema->fields($postType);
|
||||
$bySource = [];
|
||||
foreach ($values as $key => $value) {
|
||||
$bySource[$definitions[$key]->source][$key] = $value;
|
||||
}
|
||||
|
||||
foreach ($bySource as $sourceValues) {
|
||||
$first = $definitions[(string) array_key_first($sourceValues)];
|
||||
$this->schema->sourceOf($first)->write($postId, $postType, $sourceValues, $definitions);
|
||||
}
|
||||
}
|
||||
|
||||
/** @throws RuntimeException */
|
||||
private function setFeaturedImage(int $postId, int $imageId): void
|
||||
{
|
||||
$result = $imageId > 0 ? set_post_thumbnail($postId, $imageId) : delete_post_thumbnail($postId);
|
||||
|
||||
// Both return false as well when nothing had to change.
|
||||
if ($result === false && (int) get_post_thumbnail_id($postId) !== max($imageId, 0)) {
|
||||
throw new RuntimeException(sprintf('Featured image of post %d could not be set.', $postId));
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $input */
|
||||
private function checkFeaturedImage(string $postType, array $input): ?string
|
||||
{
|
||||
$imageId = (int) ($input['featured_image'] ?? 0);
|
||||
if ($imageId === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! post_type_supports($postType, 'thumbnail')) {
|
||||
return 'Inhaltstyp unterstützt kein Beitragsbild.';
|
||||
}
|
||||
|
||||
return wp_attachment_is_image($imageId) ? null : 'Kein Bild aus der Mediathek.';
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $input */
|
||||
private function checkParent(string $postType, array $input): ?string
|
||||
{
|
||||
$parentId = (int) ($input['parent'] ?? 0);
|
||||
if ($parentId === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parent = get_post($parentId);
|
||||
|
||||
return $parent instanceof WP_Post && $parent->post_type === $postType
|
||||
? null
|
||||
: 'Übergeordneter Eintrag muss existieren und denselben Inhaltstyp haben.';
|
||||
}
|
||||
|
||||
/**
|
||||
* wp_insert_post() rejects an unknown template only after the row was written,
|
||||
* so it is checked here, before anything is saved.
|
||||
*
|
||||
* @param array<string, mixed> $input
|
||||
*/
|
||||
private function checkTemplate(string $postType, array $input): ?string
|
||||
{
|
||||
$template = $input['template'] ?? '';
|
||||
if (! is_string($template) || $template === '' || $template === self::DEFAULT_TEMPLATE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$templates = (array) wp_get_theme()->get_page_templates(null, $postType);
|
||||
if (isset($templates[$template])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $templates === []
|
||||
? 'Für diesen Inhaltstyp gibt es keine Seiten-Templates; leer lassen für den Standard.'
|
||||
: sprintf('Unbekanntes Template. Erlaubt: %s (leer = Standard).', implode(', ', array_keys($templates)));
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\WordPress\Schema;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Shared read/write via the post meta API.
|
||||
* Shared read/write via the post meta API. write() throws when WordPress did not
|
||||
* store a value, so callers can roll back (all or nothing, spec §8.2).
|
||||
*/
|
||||
abstract class MetaFieldSource implements FieldSource
|
||||
{
|
||||
@@ -19,20 +22,50 @@ abstract class MetaFieldSource implements FieldSource
|
||||
foreach ($values as $key => $value) {
|
||||
$key = (string) $key;
|
||||
if ($value === null) {
|
||||
delete_post_meta($postId, $key);
|
||||
$this->delete($postId, $key);
|
||||
continue;
|
||||
}
|
||||
|
||||
$field = $definitions[$key] ?? null;
|
||||
if ($field !== null && $field->multiple && is_array($value) && array_is_list($value)) {
|
||||
delete_post_meta($postId, $key);
|
||||
$this->delete($postId, $key);
|
||||
foreach ($value as $item) {
|
||||
add_post_meta($postId, $key, wp_slash($item));
|
||||
if (add_post_meta($postId, $key, wp_slash($item)) === false) {
|
||||
throw new RuntimeException(sprintf('Meta "%s" of post %d could not be added.', $key, $postId));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
update_post_meta($postId, $key, wp_slash($value));
|
||||
// update_post_meta() also returns false when the value is unchanged – only a
|
||||
// stored value that still differs is a failure.
|
||||
if (update_post_meta($postId, $key, wp_slash($value)) === false && ! $this->holds($postId, $key, $value)) {
|
||||
throw new RuntimeException(sprintf('Meta "%s" of post %d could not be saved.', $key, $postId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function delete(int $postId, string $key): void
|
||||
{
|
||||
// delete_post_meta() returns false as well when there was nothing to delete.
|
||||
if (delete_post_meta($postId, $key) === false && metadata_exists('post', $postId, $key)) {
|
||||
throw new RuntimeException(sprintf('Meta "%s" of post %d could not be deleted.', $key, $postId));
|
||||
}
|
||||
}
|
||||
|
||||
private function holds(int $postId, string $key, mixed $value): bool
|
||||
{
|
||||
$stored = get_post_meta($postId, $key, false);
|
||||
if (! is_array($stored) || count($stored) !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$current = $stored[0];
|
||||
if (is_scalar($current) && is_scalar($value)) {
|
||||
// Meta is stored as text: 3 and "3", true and "1" are the same stored value.
|
||||
return (string) $current === (string) $value;
|
||||
}
|
||||
|
||||
return $current == $value; // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,16 @@ namespace LIT\MCP\Integrations\WordPress;
|
||||
|
||||
use LIT\MCP\ChangeLog\ChangeLog;
|
||||
use LIT\MCP\Integrations\Integration;
|
||||
use LIT\MCP\Integrations\WordPress\Content\ContentCreateAbility;
|
||||
use LIT\MCP\Integrations\WordPress\Content\ContentGetAbility;
|
||||
use LIT\MCP\Integrations\WordPress\Content\ContentQueryAbility;
|
||||
use LIT\MCP\Integrations\WordPress\Content\ContentTypesAbility;
|
||||
use LIT\MCP\Integrations\WordPress\Content\ContentUpdateAbility;
|
||||
use LIT\MCP\Integrations\WordPress\Content\PostPresenter;
|
||||
use LIT\MCP\Integrations\WordPress\Content\PostWriter;
|
||||
use LIT\MCP\Integrations\WordPress\Schema\ContentSchema;
|
||||
use LIT\MCP\Integrations\WordPress\Schema\FieldValidator;
|
||||
use LIT\MCP\Integrations\WordPress\Schema\TermAssigner;
|
||||
|
||||
/**
|
||||
* WordPress basics (spec §6): content, status, copies, revisions, menus, settings.
|
||||
@@ -35,11 +40,14 @@ final class WordPressIntegration implements Integration
|
||||
public function abilities(): array
|
||||
{
|
||||
$presenter = new PostPresenter($this->schema);
|
||||
$writer = new PostWriter($this->schema, new FieldValidator(), new TermAssigner());
|
||||
|
||||
return [
|
||||
new ContentTypesAbility($this->schema),
|
||||
new ContentQueryAbility($this->schema, $presenter),
|
||||
new ContentGetAbility($this->schema, $presenter),
|
||||
new ContentCreateAbility($this->schema, $writer, $this->log),
|
||||
new ContentUpdateAbility($this->schema, $writer, $this->log),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user