localgov_services-2.1.19/src/Plugin/Block/ServicesBlockBase.php
src/Plugin/Block/ServicesBlockBase.php
<?php
namespace Drupal\localgov_services\Plugin\Block;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Service pages block base class.
*
* @package Drupal\localgov_services\Plugin\Block
*/
abstract class ServicesBlockBase extends BlockBase implements ContainerFactoryPluginInterface {
/**
* Service node instance.
*
* @var \Drupal\node\Entity\Node
*/
protected $node = FALSE;
/**
* Route match service.
*
* @var \Drupal\Core\Routing\CurrentRouteMatch
*/
protected $routeMatch;
/**
* Entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Initialise new service page block instance.
*
* @param array $configuration
* The plugin configuration.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Routing\CurrentRouteMatch $route_match
* The route match service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, CurrentRouteMatch $route_match, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->routeMatch = $route_match;
$this->entityTypeManager = $entity_type_manager;
if ($this->routeMatch->getParameter('node')) {
$this->node = $this->routeMatch->getParameter('node');
if (!$this->node instanceof NodeInterface) {
$node_storage = $this->entityTypeManager->getStorage('node');
$this->node = $node_storage->load($this->node);
}
}
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_route_match'),
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
protected function blockAccess(AccountInterface $account) {
return AccessResult::allowedIf($this->node);
}
/**
* {@inheritdoc}
*/
public function getCacheTags() {
return Cache::mergeTags(parent::getCacheTags(), ['node:' . $this->node->id()]);
}
/**
* {@inheritdoc}
*/
public function getCacheContexts() {
return Cache::mergeContexts(parent::getCacheContexts(), ['route']);
}
}
