Skip to content

Instantly share code, notes, and snippets.

@fredericbarthelet
Created October 1, 2019 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fredericbarthelet/13e1f18d77291d25e51576ff1c726403 to your computer and use it in GitHub Desktop.
Save fredericbarthelet/13e1f18d77291d25e51576ff1c726403 to your computer and use it in GitHub Desktop.
namespace App\EventListener;
use App\Entity\Counting;
use App\Entity\User;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Symfony\Component\Security\Core\Security;
class CountingEventListener
{
/**
* @var Security
*/
private $security;
/**
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
public function prePersist(Counting $counting, PrePersistEventArgs $event)
{
if (null === $user = $this->security->getUser()) {
return;
}
if ($this->security->isGranted('ROLE_ADMIN')) {
return;
}
if ($this->security->isGranted('ROLE_MANAGER')) {
$counting->setManager($user);
return;
}
if ($this->security->isGranted('ROLE_USER')) {
$counting->setPolicyHolder($user);
}
}
}
services:
# ...
App\EventListener\CountingEventListener:
tags:
-
# these are the basic options that define the entity listener
name: 'doctrine.orm.entity_listener'
event: 'prePersist'
entity: 'App\Entity\Counting'
# set the 'lazy' option to TRUE to only instantiate listeners when they are used
lazy: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment