reason = $reason; $this->status = $status; } public function reason(): string { return $this->reason; } public function status(): int { return $this->status; } /** Whether retrying the same request later may succeed. */ public function is_retryable(): bool { return in_array( $this->reason, array( self::RATE_LIMITED, self::UNAVAILABLE, self::NETWORK ), true ); } public static function no_key(): self { return new self( self::NO_KEY, esc_html__( 'Connect your TranslatePlus account to start translating.', 'translateplus' ) ); } public static function malformed( int $status ): self { return new self( self::UNKNOWN, esc_html__( 'Malformed response from TranslatePlus.', 'translateplus' ), $status ); } public static function from_status( int $status, string $body ): self { $detail = ''; $json = json_decode( $body, true ); if ( is_array( $json ) && isset( $json['detail'] ) ) { $detail = is_string( $json['detail'] ) ? $json['detail'] : wp_json_encode( $json['detail'] ); } switch ( $status ) { case 402: return new self( self::NO_CREDITS, __( 'Your TranslatePlus account is out of credits.', 'translateplus' ), $status ); case 401: case 403: return new self( self::INVALID_KEY, __( 'The TranslatePlus API key is invalid or has been revoked.', 'translateplus' ), $status ); case 429: return new self( self::RATE_LIMITED, __( 'Rate limit reached. Retrying shortly.', 'translateplus' ), $status ); case 500: case 502: case 503: case 504: return new self( self::UNAVAILABLE, __( 'TranslatePlus is temporarily unavailable.', 'translateplus' ), $status ); case 400: case 422: /* translators: %s: API error detail. */ return new self( self::INVALID_INPUT, sprintf( __( 'The request was rejected: %s', 'translateplus' ), $detail ?: __( 'invalid input', 'translateplus' ) ), $status ); } /* translators: %d: HTTP status code. */ return new self( self::UNKNOWN, sprintf( __( 'Unexpected API response (HTTP %d).', 'translateplus' ), $status ), $status ); } }