Skip to content

How to parse or convert array to Magento classes in custom renderer webapi

I’m trying to implement a Renderer for the Webapp, an addition to the existing ‘application/json’ and ‘application/xml’ renderers. Implementation of the RendererInterface:

class CustomRender implements MagentoFrameworkWebapiRestResponseRendererInterface
{
    /**
     * Render the data 
     *
     * @param object|array|int|string|bool|float|null $data
     * @return string
     * @throws MagentoFrameworkWebapiException
     */
    public function render($data)
    {
        // What to do here, how to obtain types?
    }
}

Now inside the render function, the is_array($data) returns true. And for many endpoints this is fine, the data can be accessed by e.g. $data['entity_id']. However, for Repository endpoints, e.g. ‘/V1/invoices’, the typical response is

{ 
    items: [{...}], 
    search_criteria: {...}, 
    total_count: 399
}

How to obtain any relevant object/class instance like:

MagentoSalesApiDataInvoiceSearchResultsInterface
MagentoSalesApiDataInvoiceInterface[]
MagentoFrameworkApiSearchCriteriaInterface

These instantiations are needed in order to interface with many of the Magento classes, but I do not know how $data can be successfully ‘parsed’. I tried i.a. the following:

$factory = new MagentoFrameworkApiSearchSearchCriteriaFactory($this->objectManager);
$searchCriteria = $factory->create($data['search_criteria']);

But this results in a null object, unfortunately. Any idea how to transform $data in the render function to useful objects/classes?