UpdateCacheSubscriber.php in Custom Contextual Links 8.2
File
src/EventSubscriber/UpdateCacheSubscriber.php
View source
<?php
namespace Drupal\ccl\EventSubscriber;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Entity\EntityTypeManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UpdateCacheSubscriber implements EventSubscriberInterface {
protected $entityStorage;
protected $cache;
protected $linkType;
public function __construct(EntityTypeManager $entity_manager, CacheBackendInterface $cache_backend) {
$this->entityStorage = $entity_manager
->getStorage('custom_contextual_link');
$this->cache = $cache_backend;
$this->linkType = 'node';
}
public static function getSubscribedEvents() {
return [
'ccl_update_cache' => 'onUpdateCache',
];
}
public function onUpdateCache() {
$linkIds = $this->entityStorage
->getQuery()
->execute();
$links = $this->entityStorage
->loadMultiple($linkIds);
$typeLinks = [];
foreach ($links as $link) {
if ($link
->getLinkType() == $this->linkType) {
$typeLinks[] = $link;
}
}
$this
->processLinks($typeLinks);
}
public function processLinks(array $links) {
$nodeCache = [
'globalLinks' => [],
'contentTypeLinks' => [],
'nodeLinks' => [],
];
foreach ($links as $link) {
$css = $link
->getAdvancedOption('css');
$target = $link
->getAdvancedOption('target');
$url = $link
->get('link');
$element = [
'title' => $link
->get('title'),
'url' => strpos($url, '/') !== 0 ? $url : 'internal:' . $url,
'urlOptions' => [
'query' => $link
->getAdvancedOption('query'),
'fragment' => $link
->getAdvancedOption('anchor'),
],
'attributes' => [
'class' => $css ? explode(' ', $css) : '',
'target' => $target != 'default' ? $target : '',
],
];
switch ($link
->getLinkOption('node_option')) {
case 'node':
$nodeCache['nodeLinks'][$link
->getLinkOption('node_id')][] = $element;
break;
case 'ct':
$nodeCache['contentTypeLinks'][$link
->getLinkOption('node_type')][] = $element;
break;
case 'global':
$nodeCache['globalLinks'][] = $element;
break;
}
}
$this->cache
->set('ccl:nodes', $nodeCache, CacheBackendInterface::CACHE_PERMANENT, [
'ccl',
]);
}
}