Aggregate values on API Platform response

Viewed 774

Similar to this question, I am using API Platform with Doctrine entities - I have an Entity which contains a value:

/**
 * @ApiResource()
 */
class Credit
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="integer")
     */
    private $value; 
}

I would like to retrieve the sum of this value and return it in the top level element of the response when querying for a collection:

{
    "@context": "/api/contexts/Credit",
    "@id": "/api/credits",
    "@type": "hydra:Collection",
    "hydra:member": [
        {
            "@id": "/api/credits/1",
            "@type": "Credit",
            "id": 1,
            "value": 200,
            "createdAt": "2019-03"
        },
        {
            "@id": "/api/credits/2",
            "@type": "Credit",
            "id": 2,
            "value": 200,
            "createdAt": "2019-04"
        }
    ],
    "hydra:totalItems": 2,
    "totalValues": 400 
}

However, I would like to achieve this using a copy of the query instead of summing the values after the execution to maintain the same totalValues amount when pagination is applied - much the same way that hydra:totalItems will always return the total number of items.

What would be the best way to achieve this?

1 Answers

You can create a CreditCollectionNormalizer:

<?php

namespace App\Serializer\Normalizer;

use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;

class CreditCollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
    public const RESOURCE_CLASS = \App\Entity\Credit::class;

    private const ALREADY_CALLED = 'CREDIT_COLLECTION_NORMALIZER_ALREADY_CALLED';

    private NormalizerInterface $normalizer;

    public function __construct(NormalizerInterface $normalizer)
    {
        $this->normalizer = $normalizer;
    }

    public function normalize($object, string $format = null, array $context = []): array
    {
        $context[self::ALREADY_CALLED] = true;

        $data = $this->normalizer->normalize($object, $format, $context);

        if ('collection' === $context['operation_type'] &&
            'get' === $context['collection_operation_name'] &&
            self::RESOURCE_CLASS == $context['resource_class']) {

            $balance = 0;
            foreach ($object as $item) {
                $balance += $item->amount;
            }
            $data['hydra:meta']['balance'] = $balance;
        }

        return $data;
    }

    public function supportsNormalization($data, string $format = null, array $context = []): bool
    {
        return $this->normalizer->supportsNormalization($data, $format, $context);
    }

    public function setNormalizer(NormalizerInterface $normalizer)
    {
        if ($this->normalizer instanceof NormalizerAwareInterface) {
            $this->normalizer->setNormalizer($normalizer);
        }
    }
}

Then register it as a CollectionNormalizer decorator in services.yaml:

services:
    App\Serializer\Normalizer\CreditCollectionNormalizer:
        decorates: 'api_platform.hydra.normalizer.collection'
        arguments: [ '@App\Serializer\Normalizer\CreditCollectionNormalizer.inner' ]
        public: false

api/credits should now return the following:

{
    "@context": "/api/contexts/Credit",
    "@id": "/api/credits",
    "@type": "hydra:Collection",
    "hydra:member": [
        {
            "@id": "/api/credits/1",
            "@type": "Credit",
            "id": 1,
            "value": 200,
            "createdAt": "2019-03"
        },
        {
            "@id": "/api/credits/2",
            "@type": "Credit",
            "id": 2,
            "value": 200,
            "createdAt": "2019-04"
        }
    ],
    "hydra:totalItems": 2,
    "hydra:meta": {
        "balance": 400
    }
}
Related