Skip to content

Instantly share code, notes, and snippets.

@bhubbard
Created January 12, 2020 23:18
Show Gist options
  • Save bhubbard/b74514de39252ac91e64c8f34aaf4e85 to your computer and use it in GitHub Desktop.
Save bhubbard/b74514de39252ac91e64c8f34aaf4e85 to your computer and use it in GitHub Desktop.
A simple class to trigger Google Cloud Functions.
<?php
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
if ( ! class_exists( 'Google_Cloud_Functions' ) ) {
/**
* Google Cloud Functions
*/
class Google_Cloud_Functions {
/**
* __construct function.
*
* @access public
* @return void
*/
public function __construct() {
}
/**
* Trigger Google Cloud Function.
* @param string $region Region.
* @param string $project Project.
* @param string $function_name Function Name.
* @param array $body Body.
* @return mixed Results or error.
*/
public function trigger( string $region = '', string $project = '', string $function_name = '', $body = '', bool $cache = false, bool $debug = false ) {
// Missing Valid Region.
if( empty( $region ) ) {
return new WP_Error( 'missing-region', __( "Please provide a valid Google Cloud Region (https://cloud.google.com/compute/docs/regions-zones/).", "google-cloud-functions" ) );
}
// Missing Valid Project.
if( empty( $project ) ) {
return new WP_Error( 'missing-project', __( 'Please provide a valid project name.', 'google-cloud-functions' ) );
}
// Missing Valid Function Name.
if( empty( $function_name ) ) {
return new WP_Error( 'missing-function-name', __( 'Please provide a valid function name.', 'google-cloud-functions' ) );
}
// Define Function URL.
$function_url = esc_url( 'https://' . $region .'-' . $project . '.cloudfunctions.net/' . $function_name );
// Use a Cached Response.
if( true === $cache ) {
$cache_name = 'gcf_cache_' . md5( $function_url );
$response = get_transient( $cache_name );
if( false === $response ) {
$response = wp_remote_post( $function_url, array( 'body' => $body ) );
set_transient( $cache_name, $response );
}
} else {
$response = wp_remote_post( $function_url, array( 'body' => $body ) );
}
// Debug Response.
if ( true === $debug ) {
error_log( print_r( $response ) );
}
// Display Error.
if( is_wp_error( $response ) ) {
return $response->get_error_message();
}
// Return Response.
return wp_remote_retrieve_body( $response );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment