FlagEvents.php in Message Subscribe 8
File
message_subscribe_email/src/EventSubscriber/FlagEvents.php
View source
<?php
namespace Drupal\message_subscribe_email\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\flag\Event\FlagEvents as Flag;
use Drupal\flag\Event\FlaggingEvent;
use Drupal\flag\Event\UnflaggingEvent;
use Drupal\flag\FlaggingInterface;
use Drupal\flag\FlagServiceInterface;
use Drupal\message_subscribe\Exception\MessageSubscribeException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class FlagEvents implements EventSubscriberInterface {
protected $configFactory;
protected $flagService;
public function __construct(ConfigFactoryInterface $config_factory, FlagServiceInterface $flag_service) {
$this->configFactory = $config_factory;
$this->flagService = $flag_service;
}
public static function getSubscribedEvents() {
$events[Flag::ENTITY_FLAGGED] = [
'onFlag',
50,
];
$events[Flag::ENTITY_UNFLAGGED] = [
'onUnflag',
50,
];
return $events;
}
public function onFlag(FlaggingEvent $event) {
$this
->triggerEmailFlag($event
->getFlagging(), 'flag');
}
public function onUnflag(UnflaggingEvent $event) {
foreach ($event
->getFlaggings() as $flagging) {
$this
->triggerEmailFlag($flagging, 'unflag');
}
}
protected function triggerEmailFlag(FlaggingInterface $flagging, $action) {
if (strpos($flagging
->getFlagId(), $this->configFactory
->get('message_subscribe.settings')
->get('flag_prefix') . '_') === 0) {
if ($flagging
->getOwner()->message_subscribe_email->value || $action == 'unflag') {
$prefix = $this->configFactory
->get('message_subscribe.settings')
->get('flag_prefix');
$email_flag_name = $this->configFactory
->get('message_subscribe_email.settings')
->get('flag_prefix') . '_' . str_replace($prefix . '_', '', $flagging
->getFlagId());
$flag = $this->flagService
->getFlagById($email_flag_name);
if (!$flag) {
throw new MessageSubscribeException('There is no corresponding email flag (' . $email_flag_name . ') for the ' . $flagging
->getFlagId() . ' flag.');
}
if ($action === 'flag') {
$this->flagService
->flag($flag, $flagging
->getFlaggable(), $flagging
->getOwner());
}
elseif ($this->flagService
->getFlagging($flag, $flagging
->getFlaggable(), $flagging
->getOwner())) {
$this->flagService
->unflag($flag, $flagging
->getFlaggable(), $flagging
->getOwner());
}
}
}
}
}