Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
13aaba0
chore: simplifies type
JasonTheAdams Jul 26, 2025
0b52ffd
feat: adds json serialization to DTOs
JasonTheAdams Jul 28, 2025
0c0407c
refactor: moves enum trait to traits directory
JasonTheAdams Jul 28, 2025
03f66ff
test: adds serialization tests
JasonTheAdams Jul 28, 2025
a350b57
feat: improves fromJson validation and documenting
JasonTheAdams Jul 28, 2025
f6a1605
refactor: clean up typing with generics
JasonTheAdams Jul 28, 2025
cf5b304
refactor: further cleaning up of types
JasonTheAdams Jul 28, 2025
404699a
refactor: improves Message::toJson types
JasonTheAdams Jul 28, 2025
18ffdb4
refactor: changes to array terminology over json
JasonTheAdams Jul 28, 2025
cb4406e
refactor: adds abstract DTO with json serialization
JasonTheAdams Jul 28, 2025
f17f662
refactor: simplifies File::fromArray
JasonTheAdams Jul 28, 2025
1f77a32
refactor: simplifies Message::fromArray
JasonTheAdams Jul 28, 2025
3bc7064
refactor: simplifies MessagePart::fromArray
JasonTheAdams Jul 28, 2025
a9629c4
refactor: simplifies GenerativeAiResult
JasonTheAdams Jul 28, 2025
0f8f66d
fix: corrects incorrect types
JasonTheAdams Jul 28, 2025
18afbb5
refactor: simplifies GenerativeAiResult::fromArray
JasonTheAdams Jul 28, 2025
a66a56b
fix: corrects TokenUsage types
JasonTheAdams Jul 28, 2025
5bef6fb
refactor: simplifies FunctionCall
JasonTheAdams Jul 28, 2025
eac5146
refactor: simplifies Tool::fromArray
JasonTheAdams Jul 28, 2025
2811597
refactor: simplifies WebSearch
JasonTheAdams Jul 28, 2025
3e36f0f
refactor: simplifies Fiel and MessagePart toArray
JasonTheAdams Jul 29, 2025
b6890c8
chore: corrects too specific Message return type
JasonTheAdams Jul 29, 2025
cb985cc
fix: adds missing imports
JasonTheAdams Jul 29, 2025
25f0491
feat: adds fromArray key validation
JasonTheAdams Jul 29, 2025
87d9c67
fix: corrects linting issue
JasonTheAdams Jul 29, 2025
30ee59c
refactor: adds schema constants
JasonTheAdams Jul 29, 2025
59514c3
test: adds missing import
JasonTheAdams Jul 29, 2025
59e586c
refactor: removes need for final DTOs
JasonTheAdams Jul 29, 2025
c4c6452
fix: checks for key existence, allowing null values
JasonTheAdams Jul 29, 2025
342c07a
refacor: removes non-required key validation
JasonTheAdams Jul 29, 2025
8ded94d
feat: validates that successful oepration has result
JasonTheAdams Jul 29, 2025
6b48bef
refactor: removes potentially problematic schema condition
JasonTheAdams Jul 29, 2025
3eb5279
fix: corrects either id or name to be required
JasonTheAdams Jul 29, 2025
7d53157
fix: removes unnecessary Tool type validation
JasonTheAdams Jul 29, 2025
75a8034
chore: marks mimeType required
JasonTheAdams Jul 30, 2025
19b4692
chore: fixes since tags
JasonTheAdams Jul 30, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions src/Common/AbstractDataValueObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

declare(strict_types=1);

namespace WordPress\AiClient\Common;

use JsonSerializable;
use stdClass;
use WordPress\AiClient\Common\Contracts\WithArrayTransformationInterface;
use WordPress\AiClient\Common\Contracts\WithJsonSchemaInterface;

/**
* Abstract base class for all Data Value Objects in the AI Client.
*
* This abstract class consolidates the common functionality needed by all
* data transfer objects:
* - Array transformation for data manipulation
* - JSON schema support for validation and documentation
* - JSON serialization with proper empty object handling
*
* All DTOs in the AI Client should extend this class to ensure
* consistent behavior across the codebase.
*
* @since n.e.x.t
*
* @template TArrayShape of array<string, mixed>
* @implements WithArrayTransformationInterface<TArrayShape>
*/
abstract class AbstractDataValueObject implements
WithArrayTransformationInterface,
WithJsonSchemaInterface,
JsonSerializable
{
/**
* Converts the object to a JSON-serializable format.
*
* This method uses the toArray() method and then processes the result
* based on the JSON schema to ensure proper object representation for
* empty arrays.
*
* @since n.e.x.t
*
* @return mixed The JSON-serializable representation.
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
$data = $this->toArray();
$schema = static::getJsonSchema();

return $this->convertEmptyArraysToObjects($data, $schema);
}

/**
* Recursively converts empty arrays to stdClass objects where the schema expects objects.
*
* @since n.e.x.t
*
* @param mixed $data The data to process.
* @param array<mixed, mixed> $schema The JSON schema for the data.
* @return mixed The processed data.
*/
private function convertEmptyArraysToObjects($data, array $schema)
{
// If data is an empty array and schema expects object, convert to stdClass
if (is_array($data) && empty($data) && isset($schema['type']) && $schema['type'] === 'object') {
return new stdClass();
}

// If data is an array with content, recursively process nested structures
if (is_array($data)) {
// Handle object properties
if (isset($schema['properties']) && is_array($schema['properties'])) {
foreach ($data as $key => $value) {
if (isset($schema['properties'][$key]) && is_array($schema['properties'][$key])) {
$data[$key] = $this->convertEmptyArraysToObjects($value, $schema['properties'][$key]);
}
}
}

// Handle array items
if (isset($schema['items']) && is_array($schema['items'])) {
foreach ($data as $index => $item) {
$data[$index] = $this->convertEmptyArraysToObjects($item, $schema['items']);
}
}

// Handle oneOf schemas - just use the first one
if (isset($schema['oneOf']) && is_array($schema['oneOf'])) {
foreach ($schema['oneOf'] as $possibleSchema) {
if (is_array($possibleSchema)) {
return $this->convertEmptyArraysToObjects($data, $possibleSchema);
}
}
}
}

return $data;
}
}
34 changes: 34 additions & 0 deletions src/Common/Contracts/WithArrayTransformationInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace WordPress\AiClient\Common\Contracts;

/**
* Interface for objects that support array transformation.
*
* @since 1.0.0
*
* @template TArrayShape of array<string, mixed>
*/
interface WithArrayTransformationInterface
{
/**
* Converts the object to an array representation.
*
* @since 1.0.0
*
* @return TArrayShape The array representation.
*/
public function toArray(): array;

/**
* Creates an instance from array data.
*
* @since 1.0.0
*
* @param TArrayShape $array The array data.
* @return static The created instance.
*/
public static function fromArray(array $array);
}
58 changes: 56 additions & 2 deletions src/Files/DTO/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace WordPress\AiClient\Files\DTO;

use WordPress\AiClient\Common\Contracts\WithJsonSchemaInterface;
use WordPress\AiClient\Common\AbstractDataValueObject;
use WordPress\AiClient\Files\Enums\FileTypeEnum;
use WordPress\AiClient\Files\ValueObjects\MimeType;

Expand All @@ -15,8 +15,17 @@
* and handles them appropriately.
*
* @since n.e.x.t
*
* @phpstan-type FileArrayShape array{
* fileType: string,
* url?: string,
* mimeType?: string,
* base64Data?: string
* }
*
* @extends AbstractDataValueObject<FileArrayShape>
*/
class File implements WithJsonSchemaInterface
final class File extends AbstractDataValueObject
{
/**
* @var MimeType The MIME type of the file.
Expand Down Expand Up @@ -377,4 +386,49 @@ public static function getJsonSchema(): array
],
];
}

/**
* {@inheritDoc}
*
* @since n.e.x.t
*
* @return FileArrayShape
*/
public function toArray(): array
{
$data = [
'fileType' => $this->fileType->value,
'mimeType' => $this->getMimeType(),
];

if ($this->fileType->isRemote() && $this->url !== null) {
$data['url'] = $this->url;
} elseif (!$this->fileType->isRemote() && $this->base64Data !== null) {
$data['base64Data'] = $this->base64Data;
}

return $data;
}

/**
* {@inheritDoc}
*
* @since n.e.x.t
*/
public static function fromArray(array $array): File
{
$fileType = FileTypeEnum::from($array['fileType']);

if ($fileType->isRemote()) {
if (!isset($array['url']) || !isset($array['mimeType'])) {
throw new \InvalidArgumentException('Remote file requires url and mimeType.');
}
return new self($array['url'], $array['mimeType']);
} else {
if (!isset($array['mimeType']) || !isset($array['base64Data'])) {
throw new \InvalidArgumentException('Inline file requires mimeType and base64Data.');
}
return new self($array['base64Data'], $array['mimeType']);
}
}
}
56 changes: 54 additions & 2 deletions src/Messages/DTO/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace WordPress\AiClient\Messages\DTO;

use WordPress\AiClient\Common\Contracts\WithJsonSchemaInterface;
use WordPress\AiClient\Common\AbstractDataValueObject;
use WordPress\AiClient\Messages\Enums\MessageRoleEnum;

/**
Expand All @@ -14,8 +14,17 @@
* containing a role and one or more parts with different content types.
*
* @since n.e.x.t
*
* @phpstan-import-type MessagePartArrayShape from MessagePart
*
* @phpstan-type MessageArrayShape array{
* role: string,
* parts: array<MessagePartArrayShape>
* }
*
* @extends AbstractDataValueObject<MessageArrayShape>
*/
class Message implements WithJsonSchemaInterface
class Message extends AbstractDataValueObject
{
/**
* @var MessageRoleEnum The role of the message sender.
Expand Down Expand Up @@ -90,4 +99,47 @@ public static function getJsonSchema(): array
'required' => ['role', 'parts'],
];
}

/**
* {@inheritDoc}
*
* @since n.e.x.t
*
* @return MessageArrayShape
*/
public function toArray(): array
{
return [
'role' => $this->role->value,
'parts' => array_map(function (MessagePart $part) {
return $part->toArray();
}, $this->parts),
];
}

/**
* {@inheritDoc}
*
* @since n.e.x.t
*
* @return UserMessage|ModelMessage|SystemMessage
*/
final public static function fromArray(array $array): Message
{
$role = MessageRoleEnum::from($array['role']);
$partsData = $array['parts'];
$parts = array_map(function (array $partData) {
return MessagePart::fromArray($partData);
}, $partsData);

// Determine which concrete class to instantiate based on role
if ($role->isUser()) {
return new UserMessage($parts);
} elseif ($role->isModel()) {
return new ModelMessage($parts);
} else {
// System is the only remaining option
return new SystemMessage($parts);
}
}
}
78 changes: 76 additions & 2 deletions src/Messages/DTO/MessagePart.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace WordPress\AiClient\Messages\DTO;

use WordPress\AiClient\Common\Contracts\WithJsonSchemaInterface;
use WordPress\AiClient\Common\AbstractDataValueObject;
use WordPress\AiClient\Files\DTO\File;
use WordPress\AiClient\Messages\Enums\MessagePartTypeEnum;
use WordPress\AiClient\Tools\DTO\FunctionCall;
Expand All @@ -17,8 +17,22 @@
* function calls, etc. This DTO encapsulates one such part.
*
* @since n.e.x.t
*
* @phpstan-import-type FileArrayShape from File
* @phpstan-import-type FunctionCallArrayShape from FunctionCall
* @phpstan-import-type FunctionResponseArrayShape from FunctionResponse
*
* @phpstan-type MessagePartArrayShape array{
* type: string,
* text?: string,
* file?: FileArrayShape,
* functionCall?: FunctionCallArrayShape,
* functionResponse?: FunctionResponseArrayShape
* }
*
* @extends AbstractDataValueObject<MessagePartArrayShape>
*/
class MessagePart implements WithJsonSchemaInterface
final class MessagePart extends AbstractDataValueObject
{
/**
* @var MessagePartTypeEnum The type of this message part.
Expand Down Expand Up @@ -202,4 +216,64 @@ public static function getJsonSchema(): array
],
];
}

/**
* {@inheritDoc}
*
* @since n.e.x.t
*
* @return MessagePartArrayShape
*/
public function toArray(): array
{
$data = ['type' => $this->type->value];

if ($this->type->isText() && $this->text !== null) {
$data['text'] = $this->text;
} elseif ($this->type->isFile() && $this->file !== null) {
$data['file'] = $this->file->toArray();
} elseif ($this->type->isFunctionCall() && $this->functionCall !== null) {
$data['functionCall'] = $this->functionCall->toArray();
} elseif ($this->type->isFunctionResponse() && $this->functionResponse !== null) {
$data['functionResponse'] = $this->functionResponse->toArray();
}

return $data;
}

/**
* {@inheritDoc}
*
* @since n.e.x.t
*/
public static function fromArray(array $array): MessagePart
{
$type = MessagePartTypeEnum::from($array['type']);

if ($type->isText()) {
if (!isset($array['text'])) {
throw new \InvalidArgumentException('Text message part requires text field.');
}
return new self($array['text']);
} elseif ($type->isFile()) {
if (!isset($array['file'])) {
throw new \InvalidArgumentException('File message part requires file field.');
}
$fileData = $array['file'];
return new self(File::fromArray($fileData));
} elseif ($type->isFunctionCall()) {
if (!isset($array['functionCall'])) {
throw new \InvalidArgumentException('Function call message part requires functionCall field.');
}
$functionCallData = $array['functionCall'];
return new self(FunctionCall::fromArray($functionCallData));
} else {
// Function response is the only remaining option
if (!isset($array['functionResponse'])) {
throw new \InvalidArgumentException('Function response message part requires functionResponse field.');
}
$functionResponseData = $array['functionResponse'];
return new self(FunctionResponse::fromArray($functionResponseData));
}
}
}
Loading