You are here

class PreviewController in Entity Embed 8

Controller which renders a preview of the provided text.

Hierarchy

Expanded class hierarchy of PreviewController

File

src/Controller/PreviewController.php, line 16

Namespace

Drupal\entity_embed\Controller
View source
class PreviewController implements ContainerInjectionInterface {

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

  /**
   * Constructs an PreviewController instance.
   *
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer service.
   */
  public function __construct(RendererInterface $renderer) {
    $this->renderer = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('renderer'));
  }

  /**
   * Returns a HTML response containing a preview of the text after filtering.
   *
   * Applies all of the given text format's filters, not just the `entity_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 request.
   *
   * @see \Drupal\editor\EditorController::getUntransformedText
   */
  public function preview(Request $request, FilterFormatInterface $filter_format) {
    $text = $request
      ->get('text');
    if ($text == '') {
      throw new NotFoundHttpException();
    }
    $build = [
      '#type' => 'processed_text',
      '#text' => $text,
      '#format' => $filter_format
        ->id(),
    ];
    $html = $this->renderer
      ->renderPlain($build);

    // 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))
      ->setPrivate()
      ->setMaxAge(300);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
PreviewController::$renderer protected property The renderer service.
PreviewController::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create
PreviewController::preview public function Returns a HTML response containing a preview of the text after filtering.
PreviewController::__construct public function Constructs an PreviewController instance.