Run code before API Platform processor
24 April 2025 (Updated 1 June 2025)
<?php
declare(strict_types=1);
namespace App\Processor;
use ApiPlatform\Doctrine\Common\State\PersistProcessor;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\Contact;
use App\Service\AuthService;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
/**
* @implements ProcessorInterface<Contact, Contact>
*/
final class CreateContactProcessor implements ProcessorInterface
{
public function __construct(
#[Autowire(service: PersistProcessor::class)]
private ProcessorInterface $persistProcessor,
private AuthService $authService,
) {}
/**
* @param Contact $data
*/
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): Contact
{
// Do whatever you need to before the default processor
$data->setUser($this->authService->getCurrentUserOrFail());
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
}
}
Tagged:
API Platform recipes