EntityCreateAccessCheck.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Drupal\Core\Entity;
  3. use Drupal\Core\Access\AccessResult;
  4. use Drupal\Core\Routing\Access\AccessInterface;
  5. use Drupal\Core\Routing\RouteMatchInterface;
  6. use Drupal\Core\Session\AccountInterface;
  7. use Symfony\Component\Routing\Route;
  8. /**
  9. * Defines an access checker for entity creation.
  10. */
  11. class EntityCreateAccessCheck implements AccessInterface {
  12. /**
  13. * The entity manager.
  14. *
  15. * @var \Drupal\Core\Entity\EntityManagerInterface
  16. */
  17. protected $entityManager;
  18. /**
  19. * The key used by the routing requirement.
  20. *
  21. * @var string
  22. */
  23. protected $requirementsKey = '_entity_create_access';
  24. /**
  25. * Constructs a EntityCreateAccessCheck object.
  26. *
  27. * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
  28. * The entity manager.
  29. */
  30. public function __construct(EntityManagerInterface $entity_manager) {
  31. $this->entityManager = $entity_manager;
  32. }
  33. /**
  34. * Checks access to create the entity type and bundle for the given route.
  35. *
  36. * @param \Symfony\Component\Routing\Route $route
  37. * The route to check against.
  38. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  39. * The parametrized route.
  40. * @param \Drupal\Core\Session\AccountInterface $account
  41. * The currently logged in account.
  42. *
  43. * @return \Drupal\Core\Access\AccessResultInterface
  44. * The access result.
  45. */
  46. public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
  47. list($entity_type, $bundle) = explode(':', $route->getRequirement($this->requirementsKey) . ':');
  48. // The bundle argument can contain request argument placeholders like
  49. // {name}, loop over the raw variables and attempt to replace them in the
  50. // bundle name. If a placeholder does not exist, it won't get replaced.
  51. if ($bundle && strpos($bundle, '{') !== FALSE) {
  52. foreach ($route_match->getRawParameters()->all() as $name => $value) {
  53. $bundle = str_replace('{' . $name . '}', $value, $bundle);
  54. }
  55. // If we were unable to replace all placeholders, deny access.
  56. if (strpos($bundle, '{') !== FALSE) {
  57. return AccessResult::neutral(sprintf("Could not find '%s' request argument, therefore cannot check create access.", $bundle));
  58. }
  59. }
  60. return $this->entityManager->getAccessControlHandler($entity_type)->createAccess($bundle, $account, [], TRUE);
  61. }
  62. }