short test of machine translation.', 'Start a project' ); public function __construct( private readonly SettingsRepository $settings, private readonly ProviderFactory $providers, private readonly Translator $translator ) {} public function routes(): void { register_rest_route( self::NS, '/models', array( // POST: the key typed in the form travels in the body, never in the URL. 'methods' => WP_REST_Server::READABLE . ', ' . WP_REST_Server::CREATABLE, 'callback' => $this->safely( array( $this, 'models' ) ), 'permission_callback' => array( $this, 'can_manage' ), 'args' => array( 'provider' => array( 'type' => 'string', 'required' => true, ), 'key' => array( 'type' => 'string' ), ), ) ); register_rest_route( self::NS, '/test-provider', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => $this->safely( array( $this, 'test' ) ), 'permission_callback' => array( $this, 'can_manage' ), 'args' => array( 'key' => array( 'type' => 'string' ), 'model' => array( 'type' => 'string' ), ), ) ); } /** @param WP_REST_Request> $request */ public function models( WP_REST_Request $request ): WP_REST_Response|WP_Error { $provider = $this->providers->make( sanitize_key( (string) $request['provider'] ), self::typed( $request, 'key' ) ); if ( $provider instanceof WP_Error ) { return self::fail( $provider, 400 ); } $list = $provider->models(); if ( $list instanceof WP_Error ) { return self::fail( $list, 502 ); } return new WP_REST_Response( array( 'models' => array_values( $list ) ) ); } /** * A value typed in the settings form and not saved yet ('' = use the saved one). * * @param WP_REST_Request> $request */ private static function typed( WP_REST_Request $request, string $field ): string { return trim( sanitize_text_field( (string) $request[ $field ] ) ); } /** Translate a fixed sample into the first other language. */ public function test( WP_REST_Request $request ): WP_REST_Response|WP_Error { $id = sanitize_key( (string) $request['provider'] ); $provider = $this->providers->make( '' !== $id ? $id : null, self::typed( $request, 'key' ), self::typed( $request, 'model' ) ); if ( $provider instanceof WP_Error ) { return self::fail( $provider, 400 ); } $settings = $this->settings->get(); $from = $settings->default_code(); $to = (string) array_key_first( $settings->other_languages() ); if ( '' === $to ) { return new WP_Error( 'blocklingo_one_lang', __( 'Add a second language first.', 'blocklingo' ), array( 'status' => 400 ) ); } $result = $this->translator->translate_strings( self::SAMPLE, array( 'html', 'text' ), $from, $to, $provider ); if ( $result instanceof WP_Error ) { return self::fail( $result, 502 ); } return new WP_REST_Response( array( 'from' => $from, 'to' => $to, 'input' => self::SAMPLE, 'output' => array_values( $result ), ) ); } }