contacts_events-8.x-1.x-dev/modules/accommodation/src/AccommodationAccessControlHandler.php
modules/accommodation/src/AccommodationAccessControlHandler.php
<?php
namespace Drupal\contacts_events_accommodation;
use Drupal\contacts_events\Access\EventAccessTrait;
use Drupal\contacts_events\Entity\EventInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Access controller for the Accommodation entity.
*
* @see \Drupal\contacts_events_accommodation\Entity\Accommodation.
*/
class AccommodationAccessControlHandler extends EntityAccessControlHandler implements EntityHandlerInterface {
use EventAccessTrait;
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return (new static($entity_type))
->setRouteMatch($container->get('current_route_match'))
->setEventStorage($container->get('entity_type.manager')->getStorage('contacts_event'));
}
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\contacts_events_teams\Entity\TeamInterface $entity */
$event = $entity->getEvent();
if (!$this->checkEvent($event, $entity->bundle())) {
return AccessResult::forbidden()
->addCacheableDependency($event);
}
return parent::checkAccess($entity, $operation, $account);
}
/**
* {@inheritdoc}
*/
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
if ($event = $this->getEventFromContextOrRoute($context)) {
if (!$this->checkEvent($event, $entity_bundle)) {
return AccessResult::forbidden()
->addCacheableDependency($event);
}
}
return parent::checkCreateAccess($account, $context, $entity_bundle);
}
/**
* Check whether accommodation is enabled for the event.
*
* @param \Drupal\contacts_events\Entity\EventInterface $event
* The event the accommodation is for.
* @param string $bundle
* The bundle of accommodation we are checking.
*
* @return bool
* Whether accommodation is enabled.
*/
protected function checkEvent(EventInterface $event, $bundle) {
if (!$event->hasField('accommodation_types')) {
return FALSE;
}
$accommodation_types = array_map(function ($item) {
return $item['target_id'];
}, $event->get('accommodation_types')->getValue());
return in_array($bundle, $accommodation_types);
}
}
