Skip to content

Instantly share code, notes, and snippets.

@blaues0cke
Created April 13, 2017 10:03
Show Gist options
  • Save blaues0cke/bd9de742389f0fbee6e54ae515313dc4 to your computer and use it in GitHub Desktop.
Save blaues0cke/bd9de742389f0fbee6e54ae515313dc4 to your computer and use it in GitHub Desktop.
api-platform write listener: skip creating entity in special cases
<?php
/**
* Created by PhpStorm.
* User: Thomas Kekeisen <thomas@kekeisen.it>
* Date: 13.04.17
* Time: 11:38
*/
namespace AppBundle\Subscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use AppBundle\Entity\CampaignParticipation;
use AppBundle\Repository\CampaignParticipationRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
class CampaignParticipationApiSubscriber implements EventSubscriberInterface
{
/**
* @var $campaignParticipationRepository CampaignParticipationRepository
*/
protected $campaignParticipationRepository;
/**
* @var TokenStorage
*/
protected $tokenStorage;
/**
* CampaignParticipationApiSubscriber constructor.
* @param CampaignParticipationRepository $campaignParticipationRepository
* @param TokenStorage $tokenStorage
*/
public function __construct(
CampaignParticipationRepository $campaignParticipationRepository,
TokenStorage $tokenStorage
)
{
$this->campaignParticipationRepository = $campaignParticipationRepository;
$this->tokenStorage = $tokenStorage;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => [['checkForDuplicatedCampaignParticipation', EventPriorities::PRE_WRITE]],
];
}
/**
* @param GetResponseForControllerResultEvent $event
*/
public function checkForDuplicatedCampaignParticipation(GetResponseForControllerResultEvent $event)
{
// @formatter:off
$token = $this->tokenStorage->getToken();
$user = $token->getUser();
/**
* @var $campaignParticipationToCreate CampaignParticipation
*/
$campaignParticipationToCreate = $event->getControllerResult();
$campaign = $campaignParticipationToCreate->getCampaign();
$existingCampaignParticipations = $this->campaignParticipationRepository->findOpenByUserAndCampaign(
$user,
$campaign
);
if (count($existingCampaignParticipations) > 0) {
$existingCampaignParticipation = $existingCampaignParticipations[0];
// This will return the existing entity instead of creating a new entity
$event->setControllerResult($existingCampaignParticipation);
}
}
}
campaign_participation.api_subscriber:
arguments:
- '@=service("doctrine.orm.entity_manager").getRepository("AppBundle:CampaignParticipation")'
- '@security.token_storage'
class: AppBundle\Subscriber\CampaignParticipationApiSubscriber
tags:
- { name: kernel.event_subscriber }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment