WordPress\AiClient\Common

AbstractDataTransferObject::convertEmptyArraysToObjectsprivateWP 0.1.0

Recursively converts empty arrays to stdClass objects where the schema expects objects.

Method of the class: AbstractDataTransferObject{}

No Hooks.

Returns

Mixed. The processed data.

Usage

// private - for code of main (parent) class only
$result = $this->convertEmptyArraysToObjects( $data, $schema );
$data(mixed) (required)
The data to process.
$schema(array) (required)
.

Changelog

Since 0.1.0 Introduced.

AbstractDataTransferObject::convertEmptyArraysToObjects() code WP 7.0.2

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/anyOf schemas - just use the first one
        foreach (['oneOf', 'anyOf'] as $keyword) {
            if (isset($schema[$keyword]) && is_array($schema[$keyword])) {
                foreach ($schema[$keyword] as $possibleSchema) {
                    if (is_array($possibleSchema)) {
                        return $this->convertEmptyArraysToObjects($data, $possibleSchema);
                    }
                }
            }
        }
    }
    return $data;
}