alert_message-1.0.x-dev/src/Plugin/Block/AlertMessage.php
src/Plugin/Block/AlertMessage.php
<?php
namespace Drupal\alert_message\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a block for alert message.
*
* @Block(
* id = "alert_message",
* admin_label = @Translation("Alert message")
* )
*/
class AlertMessage extends BlockBase implements ContainerFactoryPluginInterface {
/**
* The current account.
*
* @var \Drupal\Core\Session\AccountProxy
*/
protected $currentUser;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Class constructor.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $current_user, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentUser = $current_user;
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_user'),
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function build() {
$alert_messages = $this->entityTypeManager->getStorage('alert_message')->loadByProperties([
'status' => TRUE,
]);
$alert_message_view_builder = $this->entityTypeManager->getViewBuilder('alert_message');
/** @var \Drupal\alert_message\Entity\AlertMessage $alert_message */
foreach ($alert_messages as $key => $alert_message) {
// User doesn't have targeted role.
if ($role_ids = $alert_message->getTargetedRoleIds()) {
$user_roles = $this->currentUser->getRoles();
if (!array_intersect($role_ids, $user_roles)) {
unset($alert_messages[$key]);
continue;
}
}
// User is not in targeted user.
if ($user_ids = $alert_message->getTargetedUserIds()) {
if (!in_array($this->currentUser->id(), $user_ids)) {
unset($alert_messages[$key]);
continue;
}
}
$alert_messages[$key] = $alert_message_view_builder->view($alert_message);
}
return [
'#theme' => 'block__alert_messages',
'#alert_messages' => $alert_messages,
];
}
/**
* {@inheritdoc}
*/
public function getCacheMaxAge() {
// Covers logged-in users.
// We keep this for people who wants
// to deactivate the stack middleware.
return 0;
}
/**
* {@inheritdoc}
*/
public function getCacheTags() {
// Covers logged-in and anonymous users.
// @see StackMiddleware/AlertMessage.php
// Add an hardcoded cache tag we can invalidate.
return Cache::mergeTags(parent::getCacheTags(), ['alert_message']);
}
}
