MediaPermissions.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace Drupal\media;
  3. use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
  4. use Drupal\Core\Entity\EntityTypeManagerInterface;
  5. use Drupal\Core\StringTranslation\StringTranslationTrait;
  6. use Symfony\Component\DependencyInjection\ContainerInterface;
  7. /**
  8. * Provides dynamic permissions for each media type.
  9. */
  10. class MediaPermissions implements ContainerInjectionInterface {
  11. use StringTranslationTrait;
  12. /**
  13. * The entity type manager service.
  14. *
  15. * @var \Drupal\Core\Entity\EntityTypeManagerInterface
  16. */
  17. protected $entityTypeManager;
  18. /**
  19. * MediaPermissions constructor.
  20. *
  21. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
  22. * The entity type manager service.
  23. */
  24. public function __construct(EntityTypeManagerInterface $entity_type_manager) {
  25. $this->entityTypeManager = $entity_type_manager;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public static function create(ContainerInterface $container) {
  31. return new static($container->get('entity_type.manager'));
  32. }
  33. /**
  34. * Returns an array of media type permissions.
  35. *
  36. * @return array
  37. * The media type permissions.
  38. *
  39. * @see \Drupal\user\PermissionHandlerInterface::getPermissions()
  40. */
  41. public function mediaTypePermissions() {
  42. $perms = [];
  43. // Generate media permissions for all media types.
  44. $media_types = $this->entityTypeManager
  45. ->getStorage('media_type')->loadMultiple();
  46. foreach ($media_types as $type) {
  47. $perms += $this->buildPermissions($type);
  48. }
  49. return $perms;
  50. }
  51. /**
  52. * Returns a list of media permissions for a given media type.
  53. *
  54. * @param \Drupal\media\MediaTypeInterface $type
  55. * The media type.
  56. *
  57. * @return array
  58. * An associative array of permission names and descriptions.
  59. */
  60. protected function buildPermissions(MediaTypeInterface $type) {
  61. $type_id = $type->id();
  62. $type_params = ['%type_name' => $type->label()];
  63. return [
  64. "create $type_id media" => [
  65. 'title' => $this->t('%type_name: Create new media', $type_params),
  66. ],
  67. "edit own $type_id media" => [
  68. 'title' => $this->t('%type_name: Edit own media', $type_params),
  69. ],
  70. "edit any $type_id media" => [
  71. 'title' => $this->t('%type_name: Edit any media', $type_params),
  72. ],
  73. "delete own $type_id media" => [
  74. 'title' => $this->t('%type_name: Delete own media', $type_params),
  75. ],
  76. "delete any $type_id media" => [
  77. 'title' => $this->t('%type_name: Delete any media', $type_params),
  78. ],
  79. ];
  80. }
  81. }