You are here

public function UnpublishedNodesRedirectOn403Subscriber::on403 in Unpublished Nodes Redirect 2.x

Fires redirects whenever a 403 meets the criteria for unpublished nodes.

unpublished node should be redirected.

Parameters

GetResponseForExceptionEvent $event:

See also

Utils::checksBeforeRedirect for criteria relating to if a node

File

src/EventSubscriber/UnpublishedNodesRedirectOn403Subscriber.php, line 33

Class

UnpublishedNodesRedirectOn403Subscriber
Unpublished Nodes Redirect On 403 Subscriber class.

Namespace

Drupal\unpublished_nodes_redirect\EventSubscriber

Code

public function on403(GetResponseForExceptionEvent $event) {
  if ($event
    ->getRequest()->attributes
    ->get('node') != NULL) {
    $nid = \Drupal::routeMatch()
      ->getRawParameter('node');
    $node = Node::load($nid);
    $node_type = $node
      ->getType();
    $is_published = $node
      ->isPublished();
    $config = \Drupal::config('unpublished_nodes_redirect.settings');
    $is_anonymous = \Drupal::currentUser()
      ->isAnonymous();

    // Get the redirect path for this node type.
    $redirect_path = $config
      ->get(Utils::getNodeTypeKey($node_type));

    // Get the response code for this node type.
    $response_code = $config
      ->get(Utils::getResponseCodeKey($node_type));
    if (Utils::checksBeforeRedirect($is_published, $is_anonymous, $redirect_path, $response_code)) {
      $metadata = CacheableMetadata::createFromObject($node)
        ->addCacheableDependency($config)
        ->addCacheTags([
        'rendered',
      ]);
      $response = new TrustedRedirectResponse($redirect_path, $response_code);
      $response
        ->addCacheableDependency($metadata);

      // Set response as not cacheable, otherwise browser will cache it.
      $response
        ->setCache([
        'max_age' => 0,
      ]);
      $event
        ->setResponse($response);
    }
  }
}