Make WordPress Core

Ticket #41217: log-community-events-requests.2.php

File log-community-events-requests.2.php, 2.0 KB (added by iandunn, 5 years ago)

Implode the URL for easier copy/paste, keep event titles in response body, add error mock

Line 
1<?php
2
3/**
4 * Log requests to the WordPress.org Events API and their responses.
5 *
6 * @param array|WP_Error $response     HTTP response or WP_Error object.
7 * @param string         $context      Context under which the hook is fired.
8 * @param string         $transport    HTTP transport used.
9 * @param array          $request_args HTTP request arguments.
10 * @param string         $request_url  The request URL.
11 */
12function debug_community_events_response( $response, $context, $transport, $request_args, $request_url_base ) {
13        if ( false === strpos( $request_url_base, 'api.wordpress.org/events' ) ) {
14                return;
15        }
16
17        $response_code  = wp_remote_retrieve_response_code( $response );
18        $response_body  = json_decode( wp_remote_retrieve_body( $response ), true );
19        $response_error = null;
20
21        // Avoid bloating the log with all the event data, but keep the count.
22        if ( isset( $response_body['events'] ) ) {
23                $response_body['events'] = wp_list_pluck( $response_body['events'], 'title' );
24        }
25
26        $message      = is_wp_error( $response ) ? $response->get_error_message() : 'Valid response received';
27        $request_args = $request_args['body'];
28        $request_url  = add_query_arg( $request_args, $request_url_base );
29        $details      = compact( 'request_url', 'response_code', 'response_body' );
30
31        error_log( sprintf(
32                '%s: %s. Details: %s',
33                __METHOD__,
34                trim( $message, '.' ),
35                wp_json_encode( $details )
36        ) );
37}
38add_action( 'http_api_debug', 'debug_community_events_response', 10, 5 );
39
40
41// type "error" into the city name field to simulate an HTTP request error
42// fyi, you can type `narnia` or any other non-existent location into the field in order to clear the location. refresh and it'll use your IP address as the location.
43add_filter( 'pre_http_request', function( $request, $request_args ) {
44        if ( isset( $request_args['body']['location'] ) && 'error' === $request_args['body']['location'] ) {
45                $request = new WP_Error( 'test', 'testing error condition', array( 'status' => 418 ) );
46        }
47
48        return $request;
49}, 10, 2 );