knowledge-8.x-1.x-dev/src/Plugin/Block/KnowledgeQualityBlock.php
src/Plugin/Block/KnowledgeQualityBlock.php
<?php
namespace Drupal\knowledge\Plugin\Block;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Displays the Quality, either view or form.
*
* @Block(
* id = "knowledge_quality_block",
* admin_label = @Translation("Knowledge Quality block"),
* category = @Translation("Knowledge")
* )
*/
class KnowledgeQualityBlock extends BlockBase implements ContainerFactoryPluginInterface {
/**
* The current route match.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;
/**
* Knowledge Quality constructor.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The current route match service.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
RouteMatchInterface $route_match,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->routeMatch = $route_match;
}
/**
* {@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')
);
}
/**
* {@inheritdoc}
*/
public function build() {
$route_name = $this->routeMatch->getRouteName();
if ($route_name != 'entity.node.canonical') {
return NULL;
}
/** @var \Drupal\node\NodeInterface $node */
$node = $this->routeMatch->getParameter('node');
$build['knowledge_quality_form'] = [
'#lazy_builder' => [
'knowledge.lazy_builders:renderQualityForm',
[
'node',
$node->id(),
$node->getRevisionId(),
$node->getOwnerId(),
],
],
'#create_placeholder' => TRUE,
];
$build['#cache']['max-age'] = 0;
return $build;
}
/**
* {@inheritdoc}
*/
public function blockAccess(AccountInterface $account) {
return AccessResult::allowedIfHasPermission($account, 'add quality entities');
}
/**
* {@inheritdoc}
*/
public function getCacheTags() {
/** @var \Drupal\node\NodeInterface $node */
if ($node = $this->routeMatch->getParameter('node')) {
// If there is node add its cachetag.
return Cache::mergeTags(parent::getCacheTags(), ['node:' . $node->id()]);
}
else {
// Return default tags instead.
return parent::getCacheTags();
}
}
/**
* {@inheritdoc}
*/
public function getCacheContexts() {
return Cache::mergeContexts(parent::getCacheContexts(), ['route', 'user']);
}
}
