Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / modules / media / src / MediaPermissions.php
diff --git a/web/core/modules/media/src/MediaPermissions.php b/web/core/modules/media/src/MediaPermissions.php
new file mode 100644 (file)
index 0000000..034d84a
--- /dev/null
@@ -0,0 +1,92 @@
+<?php
+
+namespace Drupal\media;
+
+use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\Core\StringTranslation\StringTranslationTrait;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+
+/**
+ * Provides dynamic permissions for each media type.
+ */
+class MediaPermissions implements ContainerInjectionInterface {
+
+  use StringTranslationTrait;
+
+  /**
+   * The entity type manager service.
+   *
+   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+   */
+  protected $entityTypeManager;
+
+  /**
+   * MediaPermissions constructor.
+   *
+   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
+   *   The entity type manager service.
+   */
+  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
+    $this->entityTypeManager = $entity_type_manager;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container) {
+    return new static($container->get('entity_type.manager'));
+  }
+
+  /**
+   * Returns an array of media type permissions.
+   *
+   * @return array
+   *   The media type permissions.
+   *
+   * @see \Drupal\user\PermissionHandlerInterface::getPermissions()
+   */
+  public function mediaTypePermissions() {
+    $perms = [];
+    // Generate media permissions for all media types.
+    $media_types = $this->entityTypeManager
+      ->getStorage('media_type')->loadMultiple();
+    foreach ($media_types as $type) {
+      $perms += $this->buildPermissions($type);
+    }
+    return $perms;
+  }
+
+  /**
+   * Returns a list of media permissions for a given media type.
+   *
+   * @param \Drupal\media\MediaTypeInterface $type
+   *   The media type.
+   *
+   * @return array
+   *   An associative array of permission names and descriptions.
+   */
+  protected function buildPermissions(MediaTypeInterface $type) {
+    $type_id = $type->id();
+    $type_params = ['%type_name' => $type->label()];
+
+    return [
+      "create $type_id media" => [
+        'title' => $this->t('%type_name: Create new media', $type_params),
+      ],
+      "edit own $type_id media" => [
+        'title' => $this->t('%type_name: Edit own media', $type_params),
+      ],
+      "edit any $type_id media" => [
+        'title' => $this->t('%type_name: Edit any media', $type_params),
+      ],
+      "delete own $type_id media" => [
+        'title' => $this->t('%type_name: Delete own media', $type_params),
+      ],
+      "delete any $type_id media" => [
+        'title' => $this->t('%type_name: Delete any media', $type_params),
+      ],
+    ];
+  }
+
+}