PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 28.2
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v28.2
28.5 28.4 28.3 28.2 28.1 28.0 27.9 27.8 27.7 27.6 27.5 trunk 18.0 18.1 18.2 18.3 18.4 18.4.1 18.5 18.5.1 18.6 18.7 18.8 18.9 19.0 All 129 releases
wordpress-seo / src / ai-http-request / application / response-parser.php

response-parser.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 28.2, at src/ai-http-request/application/response-parser.php

61 lines 1.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Yoast\WP\SEO\AI_HTTP_Request\Application;
4
5 use Yoast\WP\SEO\AI_HTTP_Request\Domain\Response;
6
7 /**
8 * Class Response_Parser
9 * Parses the response from the AI API and creates a Response object.
10 */
11 class Response_Parser implements Response_Parser_Interface {
12
13 /**
14 * Parses the response from the API.
15 *
16 * @param array<int|string|array<string>> $response The response from the API.
17 *
18 * @return Response The parsed response.
19 */
20 public function parse( $response ): Response {
21 $response_code = ( \wp_remote_retrieve_response_code( $response ) !== '' ) ? \wp_remote_retrieve_response_code( $response ) : 0;
22 $response_message = \esc_html( \wp_remote_retrieve_response_message( $response ) );
23 $error_code = '';
24 $missing_licenses = [];
25
26 if ( $response_code !== 200 && $response_code !== 0 ) {
27 $json_body = \json_decode( \wp_remote_retrieve_body( $response ) );
28 if ( $json_body !== null ) {
29 $response_message = ( $json_body->message ?? $response_message );
30 $error_code = ( $json_body->error_code ?? $this->map_message_to_code( $response_message ) );
31 if ( $response_code === 402 || $response_code === 429 ) {
32 $missing_licenses = isset( $json_body->missing_licenses ) ? (array) $json_body->missing_licenses : [];
33 }
34 }
35 }
36
37 return new Response( $response['body'], $response_code, $response_message, $error_code, $missing_licenses );
38 }
39
40 /**
41 * Maps the error message to a code.
42 *
43 * @param string $message The error message.
44 *
45 * @return string The mapped code.
46 */
47 private function map_message_to_code( string $message ): string {
48 if ( \strpos( $message, 'must NOT have fewer than 1 characters' ) !== false ) {
49 return 'NOT_ENOUGH_CONTENT';
50 }
51 if ( \strpos( $message, 'Client timeout' ) !== false ) {
52 return 'CLIENT_TIMEOUT';
53 }
54 if ( \strpos( $message, 'Server timeout' ) !== false ) {
55 return 'SERVER_TIMEOUT';
56 }
57
58 return 'UNKNOWN';
59 }
60 }
61