WooCommerce\Admin
Experimental_Abtest::fetch_variation
Fetch and cache the test variation for a provided A/B test from WP.com.
ExPlat returns a null value when the assigned variation is control or an assignment has not been set. In these instances, this method returns a value of "control".
Method of the class: Experimental_Abtest{}
Hooks from the method
Returns
Array|\WP_Error. A/B test variation, or error on failure.
Usage
// protected - for code of main (parent) or child class $result = $this->fetch_variation( $test_name );
- $test_name(string) (required)
- Name of the A/B test.
Experimental_Abtest::fetch_variation() Experimental Abtest::fetch variation code WC 10.3.6
protected function fetch_variation( $test_name ) {
// Make sure test name exists.
if ( ! $test_name ) {
return new \WP_Error( 'test_name_not_provided', 'A/B test name has not been provided.' );
}
// Make sure test name is a valid one.
if ( ! preg_match( '/^[a-z0-9_]+$/', $test_name ) ) {
return new \WP_Error( 'invalid_test_name', 'Invalid A/B test name.' );
}
// Return internal-cached test variations.
if ( isset( $this->tests[ $test_name ] ) ) {
return $this->tests[ $test_name ];
}
// Return external-cached test variations.
if ( ! empty( get_transient( 'abtest_variation_' . $test_name ) ) ) {
return get_transient( 'abtest_variation_' . $test_name );
}
// Make the request to the WP.com API.
$args = array(
'experiment_name' => $test_name,
'anon_id' => rawurlencode( $this->anon_id ),
'woo_country_code' => rawurlencode( get_option( 'woocommerce_default_country', 'US:CA' ) ),
'woo_wcadmin_install_timestamp' => rawurlencode( get_option( WCAdminHelper::WC_ADMIN_TIMESTAMP_OPTION ) ),
);
/**
* Get additional request args.
*
* @since 6.5.0
*/
$args = apply_filters( 'woocommerce_explat_request_args', $args );
$response = $this->request_assignment( $args );
// Bail if there was an error or malformed response.
if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
return new \WP_Error( 'failed_to_fetch_data', 'Unable to fetch the requested data.' );
}
// Decode the results.
$results = json_decode( $response['body'], true );
// Bail if there were no resultsreturned.
if ( ! is_array( $results ) ) {
return new \WP_Error( 'unexpected_data_format', 'Data was not returned in the expected format.' );
}
// Store the variation in our internal cache.
$this->tests[ $test_name ] = $results['variations'][ $test_name ] ?? null;
$variation = $results['variations'][ $test_name ] ?? 'control';
// Store the variation in our external cache.
if ( ! empty( $results['ttl'] ) ) {
set_transient( 'abtest_variation_' . $test_name, $variation, $results['ttl'] );
}
return $variation;
}