Skip to content

Instantly share code, notes, and snippets.

@drubb
Last active November 21, 2023 08:44
Show Gist options
  • Save drubb/c6c2366d3cb337f7e9b67aaa4a5a2e4e to your computer and use it in GitHub Desktop.
Save drubb/c6c2366d3cb337f7e9b67aaa4a5a2e4e to your computer and use it in GitHub Desktop.
Example for a Drupal custom node context, for use e.g. in block visibility settings
<?php
namespace Drupal\frs_blocks\Plugin\Context;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextProviderInterface;
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\Plugin\Context\EntityContextDefinition;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\frs_caching\StackMiddleware\CacheTimeout;
use Drupal\frs_entities\Entity\Bundle\NewsBundle;
/**
* Provides a Workshop Context for node routes.
*
* It's active for nodes of type 'news' with the news type 'Workshop'
* and a deadline in the future.
*/
class SignupOpenContext implements ContextProviderInterface {
use StringTranslationTrait;
/**
* The route match object.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected RouteMatchInterface $routeMatch;
/**
* Constructs a new WorkshopContext.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match object.
*/
public function __construct(RouteMatchInterface $route_match) {
$this->routeMatch = $route_match;
}
/**
* {@inheritdoc}
*/
public function getRuntimeContexts(array $unqualified_context_ids): array {
$result = [];
$context_definition = EntityContextDefinition::create(
'node'
)->setRequired(FALSE);
$value = NULL;
// Get the currently displayed node and check if it's a workshop.
if ($node = $this->routeMatch->getParameter('node')) {
// If deadline is all day, add a day to the timestamp.
if ($node->field_deadline?->duration === 1439) {
$node->field_deadline->value += 86400;
}
switch (TRUE) {
case !$node instanceof NewsBundle:
case $this->routeMatch->getRouteName() !== 'entity.node.canonical':
case $node->field_news_type?->entity?->name?->value !== 'Workshop':
case $node->field_deadline?->value < time():
break;
default:
$value = $node;
}
}
// Add cacheability metadata.
$cacheability = new CacheableMetadata();
$cacheability->setCacheContexts(['route']);
$cacheability->setCacheTags([CacheTimeout::HOURLY]);
// Return the node context.
$context = new Context($context_definition, $value);
$context->addCacheableDependency($cacheability);
$result['node'] = $context;
return $result;
}
/**
* {@inheritdoc}
*/
public function getAvailableContexts(): array {
$context = EntityContext::fromEntityTypeId(
'node',
$this->t('Workshop - Signup Open')
);
return ['node' => $context];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment