You are here

class MediaRevisionController in Media Revisions UI 8

Same name and namespace in other branches
  1. 2.0.x src/Controller/MediaRevisionController.php \Drupal\media_revisions_ui\Controller\MediaRevisionController

Provides a list of media revisions for a given media.

Hierarchy

Expanded class hierarchy of MediaRevisionController

File

src/Controller/MediaRevisionController.php, line 20

Namespace

Drupal\media_revisions_ui\Controller
View source
class MediaRevisionController extends ControllerBase {

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The entity repository service.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * Constructs a MediaRevisionController object.
   *
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter service.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer service.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository.
   */
  public function __construct(DateFormatterInterface $date_formatter, RendererInterface $renderer, EntityRepositoryInterface $entity_repository = NULL) {
    $this->dateFormatter = $date_formatter;
    $this->renderer = $renderer;
    $this->entityRepository = $entity_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('date.formatter'), $container
      ->get('renderer'), $container
      ->get('entity.repository'));
  }

  /**
   * Generates an overview table of older revisions of media.
   *
   * @param \Drupal\media\MediaInterface $media
   *   A media object.
   *
   * @return array
   *   An array expected by \Drupal\Core\Render\RendererInterface::render().
   */
  public function revisionOverview(MediaInterface $media) {
    $account = $this
      ->currentUser();
    $langcode = $media
      ->language()
      ->getId();
    $langname = $media
      ->language()
      ->getName();
    $languages = $media
      ->getTranslationLanguages();
    $hasTranslations = count($languages) > 1;

    /** @var \Drupal\media\MediaStorage $mediaStorage */
    $mediaStorage = $this
      ->entityTypeManager()
      ->getStorage('media');
    $title = $this
      ->t('Revisions for %title', [
      '%title' => $media
        ->label(),
    ]);
    if ($hasTranslations) {
      $title = $this
        ->t('@langname revisions for %title', [
        '@langname' => $langname,
        '%title' => $media
          ->label(),
      ]);
    }
    $build['#title'] = $title;
    $header = [
      $this
        ->t('Revision'),
      $this
        ->t('Operations'),
    ];
    $type = $media
      ->bundle();
    $canRevert = $this
      ->accountHasRevertPermission($type, $account) && $media
      ->access('update');
    $canDelete = $this
      ->accountHasDeletePermission($type, $account) && $media
      ->access('delete');
    $rows = [];
    $defaultRevision = $media
      ->getRevisionId();
    $currentRevisionDisplayed = FALSE;
    foreach ($this
      ->getRevisionIds($media, $mediaStorage) as $vid) {

      /** @var \Drupal\media\MediaInterface $revision */
      $revision = $mediaStorage
        ->loadRevision($vid);
      if ($revision
        ->hasTranslation($langcode) && $revision
        ->getTranslation($langcode)
        ->isRevisionTranslationAffected()) {
        $username = [
          '#theme' => 'username',
          '#account' => $revision
            ->getRevisionUser(),
        ];
        $date = $this->dateFormatter
          ->format($revision
          ->getRevisionCreationTime(), 'short');
        $isCurrentRevision = $vid == $defaultRevision || !$currentRevisionDisplayed && $revision
          ->wasDefaultRevision();
        if (!$isCurrentRevision) {
          $link = Link::fromTextAndUrl($date, new Url('entity.media.revision', [
            'media' => $media
              ->id(),
            'media_revision' => $vid,
          ]))
            ->toString();
        }
        else {
          $link = $media
            ->toLink($date)
            ->toString();
          $currentRevisionDisplayed = TRUE;
        }
        $row = [];
        $column = [
          'data' => [
            '#type' => 'inline_template',
            '#template' => '{% trans %}{{ date }} by {{ username }}{% endtrans %}{% if message %}<p class="revision-log">{{ message }}</p>{% endif %}',
            '#context' => [
              'date' => $link,
              'username' => $this->renderer
                ->renderPlain($username),
              'message' => [
                '#markup' => $revision
                  ->getRevisionLogMessage(),
                '#allowed_tags' => Xss::getHtmlTagList(),
              ],
            ],
          ],
        ];
        $this->renderer
          ->addCacheableDependency($column['data'], $username);
        $row[] = $column;
        if ($isCurrentRevision) {
          $row[] = [
            'data' => [
              '#prefix' => '<em>',
              '#markup' => $this
                ->t('Current revision'),
              '#suffix' => '</em>',
            ],
          ];
          $rows[] = [
            'data' => $row,
            'class' => [
              'revision-current',
            ],
          ];
        }
        else {
          $links = [];
          if ($canRevert) {
            $revertLink = Url::fromRoute('entity.media.revision_revert_confirm', [
              'media' => $media
                ->id(),
              'media_revision' => $vid,
            ]);
            if ($hasTranslations) {
              $revertLink = Url::fromRoute('entity.media.revision_revert_translation_confirm', [
                'media' => $media
                  ->id(),
                'media_revision' => $vid,
                'langcode' => $langcode,
              ]);
            }
            $title = $this
              ->t('Set as current revision');
            if ($vid < $media
              ->getRevisionId()) {
              $title = $this
                ->t('Revert');
            }
            $links['revert'] = [
              'title' => $title,
              'url' => $revertLink,
            ];
          }
          if ($canDelete) {
            $links['delete'] = [
              'title' => $this
                ->t('Delete'),
              'url' => Url::fromRoute('entity.media.revision_delete_confirm', [
                'media' => $media
                  ->id(),
                'media_revision' => $vid,
              ]),
            ];
          }
          $row[] = [
            'data' => [
              '#type' => 'operations',
              '#links' => $links,
            ],
          ];
          $rows[] = $row;
        }
      }
    }
    $build['media_revisions_table'] = [
      '#theme' => 'table',
      '#rows' => $rows,
      '#header' => $header,
      '#attached' => [
        'library' => [
          'media_revisions_ui/media_revisions_ui.admin',
        ],
      ],
      '#attributes' => [
        'class' => 'media-revision-table',
      ],
    ];
    $build['pager'] = [
      '#type' => 'pager',
    ];
    return $build;
  }

  /**
   * Gets a list of media revision IDs for a given media.
   *
   * @param \Drupal\media\MediaInterface $media
   *   Media entity to search for revisions.
   * @param \Drupal\media\MediaStorage $mediaStorage
   *   Media storage to load revisions from.
   *
   * @return int[]
   *   Media revision IDs in descending order.
   */
  protected function getRevisionIds(MediaInterface $media, MediaStorage $mediaStorage) {
    $result = $mediaStorage
      ->getQuery()
      ->allRevisions()
      ->condition('mid', $media
      ->id())
      ->sort('vid', 'DESC')
      ->pager(50)
      ->execute();
    return array_keys($result);
  }

  /**
   * Checks if account can revert a given media type.
   *
   * @param string $mediaType
   *   Media type to check permission.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Account to check for permissions.
   *
   * @return bool
   *   TRUE if account can revert a given media type, otherwise FALSE.
   */
  protected function accountHasRevertPermission($mediaType, AccountInterface $account) {
    $hasRevertPermission = FALSE;
    $revertPermissions = [
      "revert {$mediaType} media revisions",
      'revert all media revisions',
      'administer media',
    ];
    foreach ($revertPermissions as $permission) {
      if ($account
        ->hasPermission($permission)) {
        $hasRevertPermission = TRUE;
        break;
      }
    }
    return $hasRevertPermission;
  }

  /**
   * Checks if account can delete a given media type.
   *
   * @param string $mediaType
   *   Media type to check permission.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Account to check for permissions.
   *
   * @return bool
   *   TRUE if account can delete a given media type, otherwise FALSE.
   */
  protected function accountHasDeletePermission($mediaType, AccountInterface $account) {
    $hasRevertPermission = FALSE;
    $revertPermissions = [
      "delete {$mediaType} media revisions",
      'delete all media revisions',
      'administer media',
    ];
    foreach ($revertPermissions as $permission) {
      if ($account
        ->hasPermission($permission)) {
        $hasRevertPermission = TRUE;
        break;
      }
    }
    return $hasRevertPermission;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MediaRevisionController::$dateFormatter protected property The date formatter service.
MediaRevisionController::$entityRepository protected property The entity repository service.
MediaRevisionController::$renderer protected property The renderer service.
MediaRevisionController::accountHasDeletePermission protected function Checks if account can delete a given media type.
MediaRevisionController::accountHasRevertPermission protected function Checks if account can revert a given media type.
MediaRevisionController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
MediaRevisionController::getRevisionIds protected function Gets a list of media revision IDs for a given media.
MediaRevisionController::revisionOverview public function Generates an overview table of older revisions of media.
MediaRevisionController::__construct public function Constructs a MediaRevisionController object.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.