Q:

How to add computed property in Symfony's API Platform response?

I need to calculate a value property and add it into API Platform response.
I have this object:
"project": {
    "@id": "/api/projects/1",
    "@type": "Projects",
    "id": 1,
    "name": "UI/UX",
    "beginDatetime": 1562662050,
    "maxHours": 8,
    "isActive": true,
  }

And I need this object:
"project": {
    "@id": "/api/projects/1",
    "@type": "Projects",
    "id": 1,
    "name": "UI/UX",
    "estEndDatetime": 1562662050 + (8*3600), // Autocalculated value
    "maxHours": 8,
    "isActive": true,
  }

I'm using Symfony 4 with API Platform

A:

You can create a getter method and add the @Groups annotation to it. For example:
/**
 * @Groups({"your_group_name_here"})
 */
public function getEstEndDatetime(): DateTimeInterface
{
    return $this->getBeginDatetime()->modify('+ ' . ($this->getMaxHours() * 3600) . ' seconds');
}

Note that when doing this if the date is a mutable date it will be changed. So it will be better to use an immutable date for beginDateTime property.

