CclService.php in Custom Contextual Links 8.2
Namespace
Drupal\cclFile
src/CclService.phpView source
<?php
namespace Drupal\ccl;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Url;
use Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher as EventDispatcher;
use Drupal\Core\Utility\Token;
/**
* Class CclService.
*/
class CclService {
/**
* The cache service.
*
* @var \Drupal\Core\Cache\CacheBackendInterface
*/
protected $cache;
/**
* The event dispatcher service.
*
* @var \Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher
*/
protected $eventDispatcher;
/**
* The token service.
*
* @var \Drupal\Core\Utility\Token
*/
protected $token;
/**
* CclService constructor.
*
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* Inject cache backend service.
* @param \Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher $event_dispatcher
* Inject event dispatcher service.
* @param \Drupal\Core\Utility\Token $token
* Inject token service.
*/
public function __construct(CacheBackendInterface $cache_backend, EventDispatcher $event_dispatcher, Token $token) {
$this->cache = $cache_backend;
$this->eventDispatcher = $event_dispatcher;
$this->token = $token;
}
/**
* Helper function to retrieve cached links and generate them if not set.
*
* @param string $type
* The id of the cache type.
*
* @return array
* The cached link data.
*/
public function getCachedLinks($type) {
$cachedLinks = $this->cache
->get($type);
if (!isset($cachedLinks->cid)) {
$this->eventDispatcher
->dispatch('ccl_update_cache');
$cachedLinks = $this->cache
->get($type);
}
return $cachedLinks->data;
}
/**
* Prepare a link for injection by running token replacement and access check.
*
* @param array $link
* The cached link object.
* @param null|\Drupal\node\Entity\Node $node
* The node to sue for token replacement.
*
* @return array|bool
* If access is granted returns a link to be added to contextual links.
*/
public function prepareLink(array $link, $node = NULL) {
$title = $node ? $this->token
->replace($link['title'], [
'node' => $node,
]) : $this->token
->replace($link['title']);
$url = $node ? $this->token
->replace($link['url'], [
'node' => $node,
]) : $this->token
->replace($link['url']);
if ($link['urlOptions']['query']) {
$query = $node ? $this->token
->replace($link['urlOptions']['query'], [
'node' => $node,
]) : $this->token
->replace($link['urlOptions']['query']);
parse_str($query, $link['urlOptions']['query']);
}
$processedUrl = Url::fromUri($url, $link['urlOptions']);
$processedLink = [
'title' => $title,
'url' => $processedUrl,
'attributes' => $link['attributes'],
];
return $processedUrl
->access() ? $processedLink : FALSE;
}
}
Classes
Name | Description |
---|---|
CclService | Class CclService. |