class MediaFilterController

Same name and namespace in other branches
  1. 10 core/modules/media/src/Controller/MediaFilterController.php \Drupal\media\Controller\MediaFilterController
  2. 9 core/modules/media/src/Controller/MediaFilterController.php \Drupal\media\Controller\MediaFilterController
  3. 8.9.x core/modules/media/src/Controller/MediaFilterController.php \Drupal\media\Controller\MediaFilterController
  4. main core/modules/media/src/Controller/MediaFilterController.php \Drupal\media\Controller\MediaFilterController

Controller which renders a preview of the provided text.

@internal This is an internal part of the media system in Drupal core and may be subject to change in minor releases. This class should not be instantiated or extended by external code.

Hierarchy

Expanded class hierarchy of MediaFilterController

1 file declares its use of MediaFilterController
TestMediaFilterController.php in core/modules/media/tests/modules/media_test_embed/src/Controller/TestMediaFilterController.php

File

core/modules/media/src/Controller/MediaFilterController.php, line 25

Namespace

Drupal\media\Controller
View source
class MediaFilterController extends ControllerBase {
  public function __construct(protected RendererInterface $renderer, protected EntityRepositoryInterface $entityRepository, protected CsrfTokenGenerator $csrfToken) {
  }
  
  /**
   * Returns a HTML response containing a preview of the text after filtering.
   *
   * Applies all of the given text format's filters, not just the `media_embed`
   * filter, because for example `filter_align` and `filter_caption` may apply
   * to it as well.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   * @param \Drupal\filter\FilterFormatInterface $filter_format
   *   The text format.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The filtered text.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *   Throws an exception if 'text' parameter is not found in the query
   *   string.
   *
   * @see \Drupal\editor\EditorController::getUntransformedText
   */
  public function preview(Request $request, FilterFormatInterface $filter_format) {
    self::checkCsrf($request, $this->currentUser(), $this->csrfToken);
    $text = $request->query
      ->get('text');
    $uuid = $request->query
      ->get('uuid');
    if ($text == '' || $uuid == '') {
      throw new NotFoundHttpException();
    }
    $build = [
      '#type' => 'processed_text',
      '#text' => $text,
      '#format' => $filter_format->id(),
    ];
    $html = $this->renderer
      ->renderInIsolation($build);
    // Load the media item so we can embed the label in the response, for use
    // in an ARIA label.
    $headers = [];
    if ($media = $this->entityRepository
      ->loadEntityByUuid('media', $uuid)) {
      $headers['Drupal-Media-Label'] = $this->entityRepository
        ->getTranslationFromContext($media)
        ->label();
    }
    // Note that we intentionally do not use:
    // - \Drupal\Core\Cache\CacheableResponse because caching it on the server
    //   side is wasteful, hence there is no need for cacheability metadata.
    // - \Drupal\Core\Render\HtmlResponse because there is no need for
    //   attachments nor cacheability metadata.
    return (new Response($html, 200, $headers))->setPrivate()
      ->setMaxAge(300);
  }
  
  /**
   * Checks access based on media_embed filter status on the text format.
   *
   * @param \Drupal\filter\FilterFormatInterface $filter_format
   *   The text format for which to check access.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public static function formatUsesMediaEmbedFilter(FilterFormatInterface $filter_format) {
    $filters = $filter_format->filters();
    return AccessResult::allowedIf($filters->has('media_embed') && $filters->get('media_embed')->status)
      ->addCacheableDependency($filter_format);
  }
  
  /**
   * Throws an AccessDeniedHttpException if the request fails CSRF validation.
   *
   * This is used instead of \Drupal\Core\Access\CsrfAccessCheck, in order to
   * allow access for anonymous users.
   *
   * @todo Refactor this to an access checker.
   */
  private static function checkCsrf(Request $request, AccountInterface $account, CsrfTokenGenerator $csrf_token) {
    $header = 'X-Drupal-MediaPreview-CSRF-Token';
    if (!$request->headers
      ->has($header)) {
      throw new AccessDeniedHttpException();
    }
    if ($account->isAnonymous()) {
      // For anonymous users, just the presence of the custom header is
      // sufficient protection.
      return;
    }
    // For authenticated users, validate the token value.
    $token = $request->headers
      ->get($header);
    if (!$csrf_token->validate($token, $header)) {
      throw new AccessDeniedHttpException();
    }
  }

}

Members

Title Sort descending Modifiers Object type Summary Overrides
AutowiredInstanceTrait::createInstanceAutowired public static function Instantiates a new instance of the implementing class using autowiring.
AutowiredInstanceTrait::getAutowireArguments private static function Resolves arguments for a method using autowiring.
AutowireTrait::create public static function Instantiates a new instance of the implementing class using autowiring. 137
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 2
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 1
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 1
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. 2
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 1
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. 1
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage 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.
MediaFilterController::checkCsrf private static function Throws an AccessDeniedHttpException if the request fails CSRF validation.
MediaFilterController::formatUsesMediaEmbedFilter public static function Checks access based on media_embed filter status on the text format.
MediaFilterController::preview public function Returns a HTML response containing a preview of the text after filtering. 1
MediaFilterController::__construct public function
MessengerTrait::$messenger protected property The messenger. 28
MessengerTrait::messenger public function Gets the messenger. 28
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 2
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. 3
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. 1

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.