WC_REST_Authentication::update_last_accessprivateWC 1.0

Updates the last_access field for the API key associated with the current request.

This method tries to disambiguate 'primary' API requests from any programmatic REST API requests made internally.

Method of the class: WC_REST_Authentication{}

Returns

null. Nothing (null).

Usage

// private - for code of main (parent) class only
$result = $this->update_last_access( $request );
$request(WP_REST_Request) (required)
The request currently being processed.

WC_REST_Authentication::update_last_access() code WC 10.7.0

private function update_last_access( $request ) {
	global $wp;
	global $wpdb;

	// Lots of (programmatically) created REST API requests may be handled within the same process.
	// In most cases, however, we do not want to record the last access time for each of these.
	$do_not_record = true;

	// Try to detect if the REST API request actively being processed matches the current WP request.
	if ( is_a( $wp, WP::class ) && is_a( $request, WP_REST_Request::class ) ) {
		$actual_http_request     = trim( $wp->request, '/' );
		$api_request_in_progress = trim( $request->get_route(), '/' );

		// Remove the REST API route prefix (normally 'wp-json') for easier comparison.
		$rest_prefix = trailingslashit( rest_get_url_prefix() );

		if ( str_starts_with( $actual_http_request, $rest_prefix ) ) {
			$actual_http_request = substr( $actual_http_request, strlen( $rest_prefix ) );
		}

		// Recommend recording the last access time only if the actual WP request and the current
		// API request being processed are a match.
		$do_not_record = $actual_http_request !== $api_request_in_progress;
	}
	/**
	 * This filter enables the exclusion of the most recent access time from being logged for REST API calls.
	 *
	 * @param bool $result  Default value.
	 * @param int  $key_id  Key ID associated with REST API request.
	 * @param int  $user_id User ID associated with REST API request.
	 *
	 * @since 7.7.0
	 */
	if ( apply_filters( 'woocommerce_disable_rest_api_access_log', $do_not_record, $this->user->key_id, $this->user->user_id ) ) {
		return;
	}

	$wpdb->update(
		$wpdb->prefix . 'woocommerce_api_keys',
		array( 'last_access' => current_time( 'mysql' ) ),
		array( 'key_id' => $this->user->key_id ),
		array( '%s' ),
		array( '%d' )
	);
}