You are here

public function StaticPreviewRequestSubscriber::onRequest in Tome 8

Sets a response in case of a Dynamic Page Cache hit.

Parameters

\Symfony\Component\HttpKernel\Event\GetResponseEvent $event: The event to process.

File

modules/tome_static/src/EventSubscriber/StaticPreviewRequestSubscriber.php, line 75

Class

StaticPreviewRequestSubscriber
Routes valid requests to the static build.

Namespace

Drupal\tome_static\EventSubscriber

Code

public function onRequest(GetResponseEvent $event) {
  $request = $event
    ->getRequest();
  if (!$this->session
    ->get(static::SESSION_KEY) || $this->routeMatch
    ->getRouteName() === 'tome_static.preview_exit') {
    return;
  }
  $path = realpath($this
    ->joinPaths($this->static
    ->getStaticDirectory(), $request
    ->getPathInfo()));
  if (is_dir($path)) {
    $path = $this
      ->joinPaths($path, 'index.html');
  }
  $exit_message = $this
    ->t('<a style="@style" href=":link">Exit preview</a>', [
    ':link' => Url::fromRoute('tome_static.preview_exit')
      ->setAbsolute(TRUE)
      ->toString(),
    '@style' => 'position: fixed;top: 0;left: calc(50% - 60px);z-index: 2147483647;text-align: center;padding: 10px 20px;background: #00000063;border: 0;border-radius: 0 0 10px 10px;color: white;text-decoration: none;font-size: 13px;font-weight: bold;font-family: "Source Sans Pro","Lucida Grande",Verdana,sans-serif;',
  ]);
  if (strpos($path, realpath($this->static
    ->getStaticDirectory())) === 0 && file_exists($path)) {
    $contents = file_get_contents($path);
    if (pathinfo($path, PATHINFO_EXTENSION) === 'html') {
      if (strpos($contents, '</body>') !== FALSE) {
        $contents = str_replace('</body>', $exit_message . '</body>', $contents);
      }
      else {
        $contents .= $exit_message;
      }
    }
    $mime_type = (new File($path))
      ->getMimeType();
    $code = 200;
  }
  else {
    $contents = $this
      ->t('<p>Request path not present in the static build.</p>') . $exit_message;
    $mime_type = 'text/html';
    $code = 404;
  }
  $event
    ->setResponse(new Response($contents, $code, [
    'Content-Type' => $mime_type,
  ]));
}