View source
<?php
namespace Drupal\notifications_widget\Services;
use Drupal\Core\Database\Connection;
use Drupal\Core\Session\AccountProxy;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Logger\LoggerChannelFactory;
use Drupal\Core\Utility\Token;
use Drupal\Component\Datetime\TimeInterface;
class NotificationsWidgetService {
protected $currentUser;
protected $request;
protected $database;
protected $configFactory;
protected $loggerFactory;
protected $token;
protected $time;
public function __construct(AccountProxy $current_user, Connection $database, RequestStack $request, ConfigFactoryInterface $config_factory, LoggerChannelFactory $loggerFactory, Token $token, TimeInterface $time) {
$this->currentUser = $current_user;
$this->database = $database;
$this->request = $request;
$this->configFactory = $config_factory;
$this->loggerFactory = $loggerFactory
->get('activity_tracking');
$this->token = $token;
$this->time = $time;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('current_user'), $container
->get('database'), $container
->get('request_stack'), $container
->get('config.factory'), $container
->get('token'), $container
->get('datetime.time'));
}
public function logNotification($message, $userAction, $entity) {
$currentUser = $this->currentUser;
if ($entity
->bundle() == 'user') {
$entityUid = $entity
->id();
}
elseif (method_exists($entity, 'getOwner')) {
$entityUid = $entity
->getOwner()
->id();
}
else {
$entityUid = 1;
}
$notificationConfig = $this->configFactory
->get('notifications_widget.settings');
$excludeList = $notificationConfig
->get('excluded_entities');
$excludeBundles = explode(',', $excludeList);
if ($message['content_link'] == '[entity:url]') {
$entityUrl = $entity
->toUrl()
->toString();
}
else {
$entityUrl = $message['content_link'];
}
if (!in_array($entity
->bundle(), $excludeBundles)) {
$messageItems = '<a class="noti-store-msg" href="javascript:;" data-link="' . $entityUrl . '">' . $message['content'] . '</a>';
$messageItems = $this->token
->replace($messageItems, [
'user' => $this->currentUser,
'node' => $entity,
'comment' => $entity,
]);
$keys = [
'id' => NULL,
];
$fields = [
'entity_id' => $message['id'],
'entity_uid' => $entityUid,
'action' => $userAction,
'bundle' => $message['bundle'],
'uid' => $currentUser
->id(),
'user_name' => $currentUser
->getDisplayName(),
'message' => $messageItems,
'status' => 0,
'created' => $this->time
->getRequestTime(),
];
try {
$this->database
->merge('notifications')
->key($keys)
->fields($fields)
->execute();
} catch (Exception $e) {
$this->loggerFactory
->error($e
->getMessage());
}
}
}
}