Skip to content

Processors

Processors in API Platform (formerly known as Data Transformers) are used to modify the data before it is persisted to the database or returned to the client. Processors are used to manipulate the data in a way that is not possible with the built-in features of API Platform.

API Platform 3 comes with an interface for processors. The interface is called ProcessorInterface. The interface contains a method process which is used to modify the data.

Usage

To create a processor, you need to create a class that implements the ProcessorInterface. The class should contain a method process that takes the data as an argument and returns the modified data.

The following example shows how to create a processor:

<?php

namespace App\State;

use ApiPlatform\Doctrine\Common\State\PersistProcessor;
use ApiPlatform\Doctrine\Common\State\RemoveProcessor;
use ApiPlatform\State\ProcessorInterface;
use ApiPlatform\Metadata\DeleteOperationInterface;
use ApiPlatform\Metadata\Operation;
use App\Entity\User;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

/**
 * @implements ProcessorInterface<User, User>
 */
class UserProcessor implements ProcessorInterface
{
    /**
     * @param PersistProcessor $persistProcessor
     * @param RemoveProcessor $removeProcessor
     */
    public function __construct(
        #[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
        private readonly  ProcessorInterface $persistProcessor,
        #[Autowire(service: 'api_platform.doctrine.orm.state.remove_processor')]
        private readonly ProcessorInterface $removeProcessor,
    )
    {
    }

    /**
     * @return User|void
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = [])
    {
        if (!$data instanceof User) {
            return $data;
        }

        if ($operation instanceof DeleteOperationInterface) {
            $this->removeProcessor->process($data, $operation, $uriVariables, $context);
            return;
        }

        // Do something with the data

        $result = $this->persistProcessor->process($data, $operation, $uriVariables, $context);

        return $result;
    }
}