AbstractDataTransferObject::convertEmptyArraysToObjects( mixed $data,  $schema ): mixed

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.

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

Parameters

$datamixedrequired
The data to process.
mixed> $schema The JSON schema for the data.

Return

mixed The processed data.

Source

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;
}

Changelog

VersionDescription
0.1.0Introduced.

User Contributed Notes

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