*/ private $body; /** * @param array $body */ private function __construct( int $status, array $body ) { $this->status = $status; $this->body = $body; } public static function job( JobState $job ): self { return new self( 200, array( 'ok' => true, 'job' => $job->toArray(), 'next' => $job->nextHint(), ) ); } /** * Success envelope for endpoints that are not about a job. * * @param array $data */ public static function data( array $data ): self { return new self( 200, array( 'ok' => true, 'data' => $data, 'next' => array( 'action' => 'stop', 'delay_ms' => 0, ), ) ); } public static function error( string $code, string $message, int $status = 400 ): self { // Server-side faults and throttling are worth retrying; client mistakes and // "disk full" (507) are not. $retry = ( $status >= 500 && 507 !== $status ) || 429 === $status; return new self( $status, array( 'ok' => false, 'error' => array( 'code' => $code, 'message' => $message, ), 'next' => array( 'action' => $retry ? 'retry' : 'stop', 'delay_ms' => $retry ? 2000 : 0, ), ) ); } /** * A failure the page can show as it is, sent as HTTP 200 on purpose. * * A 5xx from the origin is often replaced by the CDN or proxy in front of the site with its own * error page, and the visitor then never sees the message. The body carries the failure * ("ok" and "success" are both false), and it also reads as an ordinary error to OM.api. * $data carries whatever the page needs to offer a way out (the feedback form's fallback links). * * @param array $data */ public static function failure( string $code, string $message, array $data = array() ): self { return new self( 200, array( 'ok' => false, 'success' => false, 'message' => $message, 'data' => $data, 'error' => array( 'code' => $code, 'message' => $message, ), 'next' => array( 'action' => 'stop', 'delay_ms' => 0, ), ) ); } public static function fromWpError( \WP_Error $error ): self { $data = $error->get_error_data(); $status = is_array( $data ) && isset( $data['status'] ) ? (int) $data['status'] : 400; return self::error( (string) $error->get_error_code(), $error->get_error_message(), $status ); } public function toRest(): \WP_REST_Response { $response = new \WP_REST_Response( $this->body, $this->status ); $response->header( 'Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0' ); return $response; } /** * Emits the envelope and terminates the request (admin-ajax transport). */ public function sendAjax(): void { nocache_headers(); // A stray notice printed earlier would corrupt the JSON body. if ( ob_get_length() ) { ob_clean(); } wp_send_json( $this->body, $this->status ); } }