Problem/Motivation

My problem is Drupal behind a proxy and I need the vary header to properly set the language.
http-response set-header Vary "Accept-Language, Cookie, Accept-Encoding".
How can I use your code to make that possible?
Thank you?

Steps to reproduce

Proposed resolution

Remaining tasks

User interface changes

API changes

Data model changes

Comments

maxilein created an issue.

elendev’s picture

I would add a custom CacheContext extending the VaryCacheContextInterface, and provide all the wanted Vary headers through the `getVaryHeaders` method.

If you need Drupal to handle variation, you can also compute all those headers in the `getContext` method.

I would do a custom CacheContext per Vary header though.

You could try to "decorate" the existing CacheContexts (like language, cookie, and so on) and provide a "VaryCacheContextInterface" decorator.

You need to create a custom module in any case.

I hope this helps

maxilein’s picture

Thank you for your help!
Does this look good?

<?php

namespace Drupal\proxy_language_vary\Cache\Context;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\page_cache_vary\VaryCacheContextInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Defines the ProxyLanguageCacheContext service.
 *
 * This cache context varies the cache by the Accept-Language, Cookie, and
 * Accept-Encoding headers, as suggested by the page_cache_vary maintainer.
 */
class ProxyLanguageCacheContext implements CacheContextInterface, VaryCacheContextInterface {

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructs a new ProxyLanguageCacheContext object.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   * The request stack.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t('Proxy Language Vary');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    $request = $this->requestStack->getCurrentRequest();
    if (!$request) {
      return '';
    }

    $accept_language = $request->headers->get('Accept-Language');
    $cookie = $request->headers->get('Cookie');
    $accept_encoding = $request->headers->get('Accept-Encoding');

    return hash('sha256', $accept_language . $cookie . $accept_encoding);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

  /**
   * {@inheritdoc}
   */
  public function getVaryHeaders() {
    return ['Accept-Language', 'Cookie', 'Accept-Encoding'];
  }

}