50 lines
1.6 KiB
PHP
50 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\State;
|
|
|
|
use ApiPlatform\Metadata\Operation;
|
|
use ApiPlatform\State\ProcessorInterface;
|
|
use App\Entity\Scenario;
|
|
use App\Entity\User;
|
|
use Symfony\Bundle\SecurityBundle\Security;
|
|
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
|
|
use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;
|
|
|
|
/**
|
|
* Stamps the authenticated user as the owner of a Scenario on write,
|
|
* then hands off to the core Doctrine persist processor.
|
|
*
|
|
* @implements ProcessorInterface<object, object|null>
|
|
*/
|
|
#[AsDecorator('api_platform.doctrine.orm.state.persist_processor')]
|
|
final class ScenarioOwnerProcessor implements ProcessorInterface
|
|
{
|
|
/**
|
|
* @param ProcessorInterface<object, object|null> $decorated
|
|
*/
|
|
public function __construct(
|
|
#[AutowireDecorated]
|
|
private readonly ProcessorInterface $decorated,
|
|
private readonly Security $security,
|
|
) {
|
|
}
|
|
|
|
public function process(
|
|
mixed $data,
|
|
Operation $operation,
|
|
array $uriVariables = [],
|
|
array $context = [],
|
|
): mixed {
|
|
if ($data instanceof Scenario) {
|
|
// The Scenario Post operation is gated by `is_granted('ROLE_USER')`
|
|
// (see #[ApiResource] on App\Entity\Scenario), so by the time this
|
|
// processor runs the security pipeline guarantees a logged-in User.
|
|
$user = $this->security->getUser();
|
|
\assert($user instanceof User);
|
|
|
|
$data->setOwner($user);
|
|
}
|
|
|
|
return $this->decorated->process($data, $operation, $uriVariables, $context);
|
|
}
|
|
}
|