| 1: | <?php |
| 2: | |
| 3: | namespace TIC\DormBundle\EventSubscriber; |
| 4: | |
| 5: | use Doctrine\ORM\Event\PrePersistEventArgs; |
| 6: | use Doctrine\ORM\Event\PreUpdateEventArgs; |
| 7: | use Doctrine\ORM\Events; |
| 8: | use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface; |
| 9: | use http\Exception\InvalidArgumentException; |
| 10: | use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; |
| 11: | use TIC\CoreBundle\Util\ClassHelper; |
| 12: | use TIC\DormBundle\Traits\EntityBlameable; |
| 13: | |
| 14: | class BlameableSubscriber implements EventSubscriberInterface |
| 15: | { |
| 16: | |
| 17: | private $tokenStorage; |
| 18: | |
| 19: | public function __construct(TokenStorageInterface $tokenStorage) |
| 20: | { |
| 21: | $this->tokenStorage = $tokenStorage; |
| 22: | } |
| 23: | |
| 24: | |
| 25: | public function getSubscribedEvents(): array |
| 26: | { |
| 27: | return [ |
| 28: | Events::prePersist, |
| 29: | Events::preUpdate, |
| 30: | ]; |
| 31: | } |
| 32: | |
| 33: | public function prePersist(PrePersistEventArgs $args): void |
| 34: | { |
| 35: | $object = $args->getObject(); |
| 36: | if (!$this->isBlameable($object)) return; |
| 37: | |
| 38: | $user = $this->checkUser(); |
| 39: | |
| 40: | if ($user && is_object($object)) { |
| 41: | $object->setCreatedBy($user); |
| 42: | $object->setUpdatedBy($user); |
| 43: | } |
| 44: | } |
| 45: | |
| 46: | public function preUpdate(PreUpdateEventArgs $args): void |
| 47: | { |
| 48: | $object = $args->getObject(); |
| 49: | if (!$this->isBlameable($object)) return; |
| 50: | |
| 51: | $user = $this->checkUser(); |
| 52: | |
| 53: | if ($user && is_object($object)) { |
| 54: | $object->setUpdatedBy($user); |
| 55: | } |
| 56: | } |
| 57: | |
| 58: | public function isBlameable($object): bool |
| 59: | { |
| 60: | return ClassHelper::hasTrait($object, EntityBlameable::class); |
| 61: | } |
| 62: | |
| 63: | public function checkUser() |
| 64: | { |
| 65: | $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null; |
| 66: | |
| 67: | if ($user === null) { |
| 68: | $user = (PHP_SAPI === "cli") ? 'admin' : 'anonymous'; |
| 69: | } |
| 70: | |
| 71: | if (is_object($user)) { |
| 72: | if (method_exists($user, 'getBlameableName')) { |
| 73: | return $user->getBlameableName(); |
| 74: | } |
| 75: | if (method_exists($user, '__toString')) { |
| 76: | return $user->__toString(); |
| 77: | } |
| 78: | |
| 79: | throw new InvalidArgumentException('User must be a string, or object shoud have method __toString'); |
| 80: | } |
| 81: | |
| 82: | return $user; |
| 83: | } |
| 84: | } |
| 85: | |