posts = $posts; } /** * Save manual segment translations for a post. * * @param array $edits Sanitized edits. * @return array{translated_id:int, saved:int, pending_review:bool} * @throws \RuntimeException When the post cannot be translated. */ public function save_edits( int $source_id, string $lang, array $edits ): array { $post = get_post( $source_id ); if ( ! $post ) { throw new \RuntimeException( esc_html__( 'Post not found.', 'translateplus' ) ); } $sources = $this->posts->collect( $post ); $edits = array_values( array_filter( $edits, static function ( $e ) use ( $sources ) { return isset( $sources[ $e['key'] ] ) && '' !== trim( (string) $e['translation'] ); } ) ); $reviewer = Roles::can_review( $lang ); $target = Groups::translation( 'post', $source_id, $lang ); $previous = Segments::get( 'post', $source_id, $lang ); // Published translation, no review rights: keep the edits as suggestions. if ( ! $reviewer && Roles::is_live( $target ) ) { $saved = Segments::save_manual( 'post', $source_id, $lang, $edits, Languages::source(), $previous, false ); if ( $saved ) { Groups::set_status( 'post', $target, Groups::STATUS_REVIEW ); } return array( 'translated_id' => $target, 'saved' => $saved, 'pending_review' => true, ); } // Apply earlier suggestions and these edits, then rebuild without calling the API. if ( $reviewer ) { Segments::to_memory( 'post', $source_id, $lang, Languages::source() ); } $pairs = array(); foreach ( $edits as $e ) { $pairs[ (string) $sources[ $e['key'] ] ] = $e['translation']; } Memory::save( $pairs, Languages::source(), $lang ); $target = $this->posts->translate( $source_id, $lang, array( 'force' => true, 'offline' => true, 'pending' => ! $reviewer, ) ); $saved = Segments::save_manual( 'post', $source_id, $lang, $edits, Languages::source(), $previous ); return array( 'translated_id' => $target, 'saved' => $saved, 'pending_review' => ! $reviewer, ); } /** * Approve a translation: apply suggested changes and publish it. * * @throws \RuntimeException When the post cannot be translated. */ public function approve( int $source_id, string $lang ): int { Segments::to_memory( 'post', $source_id, $lang, Languages::source() ); $target = $this->posts->translate( $source_id, $lang, array( 'force' => true, 'offline' => true, ) ); Segments::mark_reviewed( 'post', $source_id, $lang ); $source_status = get_post_status( $source_id ); PostTranslator::$writing = true; wp_update_post( array( 'ID' => $target, 'post_status' => in_array( $source_status, array( 'publish', 'future', 'private' ), true ) ? $source_status : 'publish', ) ); PostTranslator::$writing = false; Groups::set_status( 'post', $target, Groups::STATUS_TRANSLATED ); return $target; } }