contacts_events-8.x-1.x-dev/src/Access/EventAccessTrait.php
src/Access/EventAccessTrait.php
<?php
namespace Drupal\contacts_events\Access;
use Drupal\contacts_events\Entity\EventInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
/**
* Trait to help manage access for optional event features.
*/
trait EventAccessTrait {
/**
* The current route match.
*
* @var \Drupal\Core\Routing\CurrentRouteMatch
*/
private $routeMatch;
/**
* The Contacts Event entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
private $storage;
/**
* Set the current route match.
*
* @param \Drupal\Core\Routing\CurrentRouteMatch $route_match
* The current route match.
*
* @return $this
*/
public function setRouteMatch(CurrentRouteMatch $route_match) {
$this->routeMatch = $route_match;
return $this;
}
/**
* Set the event entity storage handler.
*
* @param \Drupal\Core\Entity\EntityStorageInterface $storage
* The event entity storage handler.
*
* @return $this
*/
public function setEventStorage(EntityStorageInterface $storage) {
$this->storage = $storage;
return $this;
}
/**
* Attempt to get the event from the context or the route match.
*
* @param array $context
* The context.
*
* @return \Drupal\contacts_events\Entity\EventInterface|null
* The event, or NULL if unable to find one.
*/
protected function getEventFromContextOrRoute(array $context) {
if (isset($context['contacts_event']) && $context['contacts_event'] instanceof EventInterface) {
$event = $context['contacts_event'];
}
elseif ($event = $this->routeMatch->getParameter('contacts_event')) {
if (is_scalar($event)) {
$event = $this->storage->load($event);
}
}
return $event instanceof EventInterface ? $event : NULL;
}
}
