Last active
March 21, 2016 18:19
-
-
Save barryhughes/aa4af91b71e17c5228ab to your computer and use it in GitHub Desktop.
WP HTTP API: simulated transport for troubleshooting and testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Once setup, this WP HTTP transport does a couple of things: | |
* | |
* 1) it means calls to wp_http_get() etc don't result in anything | |
* actually being sent on the wire | |
* | |
* 2) if a save directory is specified it will save a text representation | |
* of the request in that directory | |
* | |
* Occasionally useful for debugging purposes. | |
*/ | |
class WP_Http_Simulated { | |
protected static $saved_requests_dir = ''; | |
public static function setup( $save_dir = '' ) { | |
self::$saved_requests_dir = $save_dir; | |
add_filter( 'http_api_transports', function( $transports ) { | |
array_unshift( $transports, 'simulated' ); | |
return $transports; | |
} ); | |
} | |
/** | |
* Confirm that this transport is viable, otherwise WP_Http will skip | |
* to the next available transport. | |
* | |
* @return bool | |
*/ | |
public static function test() { | |
return true; | |
} | |
/** | |
* Save a representation of the request (if a saved requests directory | |
* has been specified) and return a 200 OK response to the caller. | |
* | |
* @param string $url | |
* @param array $args | |
* | |
* @return array | |
*/ | |
public function request( $url, array $args = null ) { | |
if ( ! empty( self::$saved_requests_dir ) ) { | |
$base_filename = self::$saved_requests_dir . date_i18n( 'ymd-his-' ) . uniqid(); | |
file_put_contents( $base_filename, "$url\n" . print_r( $args, true ) ); | |
} | |
return [ | |
'headers' => [ | |
'date' => date_i18n( 'Y-m-d H:i:s' ), | |
'server' => 'Simulated response', | |
'content-type' => 'application/json' | |
], | |
'body' => json_encode( [ | |
'data' => hash( 'md5', rand( 0, PHP_INT_MAX ) ) | |
] ), | |
'response' => [ | |
'code' => '200', | |
'message' => 'OK' | |
], | |
'cookies' => [] | |
]; | |
} | |
} | |
WP_Http_Simulated::setup( '/html/someproject.com/wp-content/uploads/http-requests' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment