DomainRouteCheck.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Drupal\domain\Access;
  3. use Drupal\Core\Access\AccessResult;
  4. use Drupal\Core\Routing\Access\AccessInterface;
  5. use Drupal\Core\Session\AccountInterface;
  6. use Symfony\Component\Routing\Route;
  7. use Drupal\domain\DomainNegotiatorInterface;
  8. /**
  9. * Determines access to routes based on domains.
  10. *
  11. * You can specify the '_domain' key on route requirements. If you specify a
  12. * single domain, users with that domain with have access. If you specify
  13. * multiple ones you can join them by using "+".
  14. *
  15. * This access checker is separate from the global check used by inactive
  16. * domains. It is expressly for use with Views and other systems that need
  17. * to add a domain requirement to a specific route.
  18. */
  19. class DomainRouteCheck implements AccessInterface {
  20. /**
  21. * The key used by the routing requirement.
  22. *
  23. * @var string
  24. */
  25. protected $requirementsKey = '_domain';
  26. /**
  27. * The Domain negotiator.
  28. *
  29. * @var \Drupal\domain\DomainNegotiatorInterface
  30. */
  31. protected $domainNegotiator;
  32. /**
  33. * Constructs the object.
  34. *
  35. * @param \Drupal\domain\DomainNegotiatorInterface $negotiator
  36. * The domain negotiation service.
  37. */
  38. public function __construct(DomainNegotiatorInterface $negotiator) {
  39. $this->domainNegotiator = $negotiator;
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function applies(Route $route) {
  45. return $route->hasRequirement($this->requirementsKey);
  46. }
  47. /**
  48. * Checks access to a route with a _domain requirement.
  49. *
  50. * @param \Symfony\Component\Routing\Route $route
  51. * The route to check against.
  52. * @param \Drupal\Core\Session\AccountInterface $account
  53. * The currently logged in account.
  54. *
  55. * @return \Drupal\Core\Access\AccessResultInterface
  56. * The access result.
  57. *
  58. * @see \Drupal\domain\Plugin\views\access\Domain
  59. */
  60. public function access(Route $route, AccountInterface $account) {
  61. // Requirements just allow strings, so this might be a comma separated list.
  62. $string = $route->getRequirement($this->requirementsKey);
  63. $domain = $this->domainNegotiator->getActiveDomain();
  64. // Since only one domain can be active per request, we only suport OR logic.
  65. $allowed = array_filter(array_map('trim', explode('+', $string)));
  66. if (!empty($domain) && in_array($domain->id(), $allowed)) {
  67. return AccessResult::allowed()->addCacheContexts(['url.site']);
  68. }
  69. // If there is no allowed domain, give other access checks a chance.
  70. return AccessResult::neutral()->addCacheContexts(['url.site']);
  71. }
  72. }