Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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