PromptBuilder::parseMessage( mixed $input, WordPressAiClientMessagesEnumsMessageRoleEnum $defaultRole ): WordPressAiClientMessagesDTOMessage

In this article

This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only by core. It is listed here for completeness.

Parses various input types into a Message with the given role.

Parameters

$inputmixedrequired
The input to parse.
$defaultRoleWordPressAiClientMessagesEnumsMessageRoleEnumrequired
The role for the message if not specified by input.

Return

WordPressAiClientMessagesDTOMessage The parsed message.

Source

private function parseMessage($input, MessageRoleEnum $defaultRole): Message
{
    // Handle Message input directly
    if ($input instanceof Message) {
        return $input;
    }
    // Handle single MessagePart
    if ($input instanceof MessagePart) {
        return new Message($defaultRole, [$input]);
    }
    // Handle string input
    if (is_string($input)) {
        if (trim($input) === '') {
            throw new InvalidArgumentException('Cannot create a message from an empty string.');
        }
        return new Message($defaultRole, [new MessagePart($input)]);
    }
    // Handle array input
    if (!is_array($input)) {
        throw new InvalidArgumentException('Input must be a string, MessagePart, MessagePartArrayShape, ' . 'a list of string|MessagePart|MessagePartArrayShape, or a Message instance.');
    }
    // Handle MessageArrayShape input
    if (Message::isArrayShape($input)) {
        return Message::fromArray($input);
    }
    // Check if it's a MessagePartArrayShape
    if (MessagePart::isArrayShape($input)) {
        return new Message($defaultRole, [MessagePart::fromArray($input)]);
    }
    // It should be a list of string|MessagePart|MessagePartArrayShape
    if (!array_is_list($input)) {
        throw new InvalidArgumentException('Array input must be a list array.');
    }
    // Empty array check
    if (empty($input)) {
        throw new InvalidArgumentException('Cannot create a message from an empty array.');
    }
    $parts = [];
    foreach ($input as $item) {
        if (is_string($item)) {
            $parts[] = new MessagePart($item);
        } elseif ($item instanceof MessagePart) {
            $parts[] = $item;
        } elseif (is_array($item) && MessagePart::isArrayShape($item)) {
            $parts[] = MessagePart::fromArray($item);
        } else {
            throw new InvalidArgumentException('Array items must be strings, MessagePart instances, or MessagePartArrayShape.');
        }
    }
    return new Message($defaultRole, $parts);
}

Changelog

VersionDescription
0.1.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.