Magic method to proxy snake_case method calls to their PHP AI Client camelCase counterparts.
Description
This allows WordPress developers to use snake_case naming conventions. It catches any exceptions thrown, stores them, and returns a WP_Error when a terminate method is called.
Parameters
$namestringrequired- The method name in snake_case.
- mixed> $arguments The method arguments.
Source
public function __call( string $name, array $arguments ) {
/*
* If an error occurred in a previous method call, either return the error for terminate methods,
* or return the same instance for other methods to maintain the fluent interface.
*/
if ( null !== $this->error ) {
if ( self::is_generating_method( $name ) ) {
return $this->error;
}
if ( self::is_support_check_method( $name ) ) {
return false;
}
return $this;
}
// Check if the prompt should be prevented for is_supported* and generate_*/convert_text_to_speech* methods.
if ( self::is_support_check_method( $name ) || self::is_generating_method( $name ) ) {
// If AI is not supported, then there's no need to apply the filter as the prompt will be prevented anyway.
$is_ai_disabled = ! wp_supports_ai();
$prevent = $is_ai_disabled;
if ( ! $prevent ) {
/**
* Filters whether to prevent the prompt from being executed.
*
* @since 7.0.0
*
* @param bool $prevent Whether to prevent the prompt. Default false.
* @param WP_AI_Client_Prompt_Builder $builder A clone of the prompt builder instance (read-only).
*/
$prevent = (bool) apply_filters( 'wp_ai_client_prevent_prompt', false, clone $this );
}
if ( $prevent ) {
// For is_supported* methods, return false.
if ( self::is_support_check_method( $name ) ) {
return false;
}
$error_message = $is_ai_disabled
? __( 'AI features are not supported in this environment.' )
: __( 'Prompt execution was prevented by a filter.' );
// For generate_* and convert_text_to_speech* methods, create a WP_Error.
$this->error = new WP_Error(
'prompt_prevented',
$error_message,
array(
'status' => 503,
)
);
if ( self::is_generating_method( $name ) ) {
return $this->error;
}
return $this;
}
}
try {
$callable = $this->get_builder_callable( $name );
$result = $callable( ...$arguments );
// If the result is a PromptBuilder, return the current instance to allow method chaining.
if ( $result instanceof PromptBuilder ) {
return $this;
}
return $result;
} catch ( Exception $e ) {
$this->error = $this->exception_to_wp_error( $e );
if ( self::is_generating_method( $name ) ) {
return $this->error;
}
return $this;
}
}
Hooks
- apply_filters( ‘wp_ai_client_prevent_prompt’,
bool $prevent ,WP_AI_Client_Prompt_Builder $builder ) Filters whether to prevent the prompt from being executed.
Changelog
| Version | Description |
|---|---|
| 7.0.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.