/**
* Get the attributes array.
*
* @param array|\stdClass|CMSObject $post The data container
* @param array|null $fields The requested fields to be rendered
*
* @return array
*
* @since 4.0.0
*/
public function getAttributes($post, array $fields = null)
{
if (!$post instanceof \stdClass && !\is_array($post) && !$post instanceof CMSObject) {
$message = sprintf('Invalid argument for %s. Expected array or %s. Got %s', static::class, CMSObject::class, \gettype($post));
throw new \InvalidArgumentException($message);
}
// The response from a standard ListModel query
if ($post instanceof \stdClass) {
$post = (array) $post;
}
// The response from a standard AdminModel query also works for Table which extends CMSObject
if ($post instanceof CMSObject) {
$post = $post->getProperties();
}
$event = new Events\OnGetApiAttributes('onGetApiAttributes', ['attributes' => $post, 'context' => $this->type]);
/** @var Events\OnGetApiAttributes $eventResult */
$eventResult = Factory::getApplication()->getDispatcher()->dispatch('onGetApiAttributes', $event);
$combinedData = array_merge($post, $eventResult->getAttributes());
return \is_array($fields) ? array_intersect_key($combinedData, array_flip($fields)) : $combinedData;
}