Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
131 changes: 131 additions & 0 deletions src/Common/AbstractDataValueObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
<?php

declare(strict_types=1);

namespace WordPress\AiClient\Common;

use InvalidArgumentException;
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
{
/**
* Validates that required keys exist in the array data.
*
* @since n.e.x.t
*
* @param TArrayShape $data The array data to validate.
* @param string[] $requiredKeys The keys that must be present.
* @throws InvalidArgumentException If any required key is missing.
*/
protected static function validateFromArrayData(array $data, array $requiredKeys): void
{
$missingKeys = [];

foreach ($requiredKeys as $key) {
if (!array_key_exists($key, $data)) {
$missingKeys[] = $key;
}
}

if (!empty($missingKeys)) {
throw new InvalidArgumentException(
sprintf(
'%s::fromArray() missing required keys: %s',
static::class,
implode(', ', $missingKeys)
)
);
}
}

/**
* 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 n.e.x.t
*
* @template TArrayShape of array<string, mixed>
*/
interface WithArrayTransformationInterface
{
/**
* Converts the object to an array representation.
*
* @since n.e.x.t
*
* @return TArrayShape The array representation.
*/
public function toArray(): array;

/**
* Creates an instance from array data.
*
* @since n.e.x.t
*
* @param TArrayShape $array The array data.
* @return self<TArrayShape> The created instance.
*/
public static function fromArray(array $array): self;
}
83 changes: 73 additions & 10 deletions src/Files/DTO/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

namespace WordPress\AiClient\Files\DTO;

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

Expand All @@ -15,9 +17,22 @@
* 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
class File extends AbstractDataValueObject
{
public const KEY_FILE_TYPE = 'fileType';
public const KEY_MIME_TYPE = 'mimeType';
public const KEY_URL = 'url';
public const KEY_BASE64_DATA = 'base64Data';
/**
* @var MimeType The MIME type of the file.
*/
Expand Down Expand Up @@ -335,46 +350,94 @@ public static function getJsonSchema(): array
'oneOf' => [
[
'properties' => [
'fileType' => [
self::KEY_FILE_TYPE => [
'type' => 'string',
'const' => FileTypeEnum::REMOTE,
'description' => 'The file type.',
],
'mimeType' => [
self::KEY_MIME_TYPE => [
'type' => 'string',
'description' => 'The MIME type of the file.',
'pattern' => '^[a-zA-Z0-9][a-zA-Z0-9!#$&\\-\\^_+.]*\\/[a-zA-Z0-9]'
. '[a-zA-Z0-9!#$&\\-\\^_+.]*$',
],
'url' => [
self::KEY_URL => [
'type' => 'string',
'format' => 'uri',
'description' => 'The URL to the remote file.',
],
],
'required' => ['fileType', 'mimeType', 'url'],
'required' => [self::KEY_FILE_TYPE, self::KEY_MIME_TYPE, self::KEY_URL],
],
[
'properties' => [
'fileType' => [
self::KEY_FILE_TYPE => [
'type' => 'string',
'const' => FileTypeEnum::INLINE,
'description' => 'The file type.',
],
'mimeType' => [
self::KEY_MIME_TYPE => [
'type' => 'string',
'description' => 'The MIME type of the file.',
'pattern' => '^[a-zA-Z0-9][a-zA-Z0-9!#$&\\-\\^_+.]*\\/[a-zA-Z0-9]'
. '[a-zA-Z0-9!#$&\\-\\^_+.]*$',
],
'base64Data' => [
self::KEY_BASE64_DATA => [
'type' => 'string',
'description' => 'The base64-encoded file data.',
],
],
'required' => ['fileType', 'mimeType', 'base64Data'],
'required' => [self::KEY_FILE_TYPE, self::KEY_MIME_TYPE, self::KEY_BASE64_DATA],
],
],
];
}

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

if ($this->url !== null) {
$data[self::KEY_URL] = $this->url;
} elseif (!$this->fileType->isRemote() && $this->base64Data !== null) {
$data[self::KEY_BASE64_DATA] = $this->base64Data;
} else {
throw new RuntimeException(
'File requires either url or base64Data. This should not be a possible condition.'
);
}

return $data;
}

/**
* {@inheritDoc}
*
* @since n.e.x.t
*/
public static function fromArray(array $array): self
{
static::validateFromArrayData($array, [self::KEY_FILE_TYPE]);

// Check which properties are set to determine how to construct the File
$mimeType = $array[self::KEY_MIME_TYPE] ?? null;

if (isset($array[self::KEY_URL])) {
return new self($array[self::KEY_URL], $mimeType);
} elseif (isset($array[self::KEY_BASE64_DATA])) {
return new self($array[self::KEY_BASE64_DATA], $mimeType);
} else {
throw new InvalidArgumentException('File requires either url or base64Data.');
}
}
}
Loading