NodePermissions.php 2.4 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

namespace Drupal\node;

use Drupal\Core\Routing\UrlGeneratorTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\Entity\NodeType;

/**
10
 * Provides dynamic permissions for nodes of different types.
11 12 13 14 15 16 17
 */
class NodePermissions {

  use StringTranslationTrait;
  use UrlGeneratorTrait;

  /**
18
   * Returns an array of node type permissions.
19 20
   *
   * @return array
21 22
   *   The node type permissions.
   *   @see \Drupal\user\PermissionHandlerInterface::getPermissions()
23 24
   */
  public function nodeTypePermissions() {
25
    $perms = [];
26 27 28 29 30 31 32 33 34
    // Generate node permissions for all node types.
    foreach (NodeType::loadMultiple() as $type) {
      $perms += $this->buildPermissions($type);
    }

    return $perms;
  }

  /**
35
   * Returns a list of node permissions for a given node type.
36 37
   *
   * @param \Drupal\node\Entity\NodeType $type
38
   *   The node type.
39 40
   *
   * @return array
41
   *   An associative array of permission names and descriptions.
42 43 44
   */
  protected function buildPermissions(NodeType $type) {
    $type_id = $type->id();
45
    $type_params = ['%type_name' => $type->label()];
46

47 48
    return [
      "create $type_id content" => [
49
        'title' => $this->t('%type_name: Create new content', $type_params),
50 51
      ],
      "edit own $type_id content" => [
52
        'title' => $this->t('%type_name: Edit own content', $type_params),
53 54
      ],
      "edit any $type_id content" => [
55
        'title' => $this->t('%type_name: Edit any content', $type_params),
56 57
      ],
      "delete own $type_id content" => [
58
        'title' => $this->t('%type_name: Delete own content', $type_params),
59 60
      ],
      "delete any $type_id content" => [
61
        'title' => $this->t('%type_name: Delete any content', $type_params),
62 63
      ],
      "view $type_id revisions" => [
64
        'title' => $this->t('%type_name: View revisions', $type_params),
65
        'description' => t('To view a revision, you also need permission to view the content item.'),
66 67
      ],
      "revert $type_id revisions" => [
68
        'title' => $this->t('%type_name: Revert revisions', $type_params),
69
        'description' => t('To revert a revision, you also need permission to edit the content item.'),
70 71
      ],
      "delete $type_id revisions" => [
72
        'title' => $this->t('%type_name: Delete revisions', $type_params),
73
        'description' => $this->t('To delete a revision, you also need permission to delete the content item.'),
74 75
      ],
    ];
76 77 78
  }

}