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