1 | <?php |
||
32 | class UserContextSubscriber implements EventSubscriberInterface |
||
33 | { |
||
34 | /** |
||
35 | * @var RequestMatcherInterface |
||
36 | */ |
||
37 | private $requestMatcher; |
||
38 | |||
39 | /** |
||
40 | * @var HashGenerator |
||
41 | */ |
||
42 | private $hashGenerator; |
||
43 | |||
44 | /** |
||
45 | * @var string[] |
||
46 | */ |
||
47 | private $userIdentifierHeaders; |
||
48 | |||
49 | /** |
||
50 | * @var string |
||
51 | */ |
||
52 | private $hash; |
||
53 | |||
54 | /** |
||
55 | * @var string |
||
56 | */ |
||
57 | private $hashHeader; |
||
58 | |||
59 | /** |
||
60 | * @var integer |
||
61 | */ |
||
62 | private $ttl; |
||
63 | |||
64 | 25 | public function __construct( |
|
81 | |||
82 | /** |
||
83 | * Return the response to the context hash request with a header containing |
||
84 | * the generated hash. |
||
85 | * |
||
86 | * If the ttl is bigger than 0, cache headers will be set for this response. |
||
87 | * |
||
88 | * @param GetResponseEvent $event |
||
89 | */ |
||
90 | 20 | public function onKernelRequest(GetResponseEvent $event) |
|
122 | |||
123 | /** |
||
124 | * Add the context hash header to the headers to vary on if the header was |
||
125 | * present in the request. |
||
126 | * |
||
127 | * @param FilterResponseEvent $event |
||
128 | */ |
||
129 | 20 | public function onKernelResponse(FilterResponseEvent $event) |
|
130 | { |
||
131 | 20 | if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) { |
|
132 | 3 | return; |
|
133 | } |
||
134 | |||
135 | 19 | $response = $event->getResponse(); |
|
136 | 19 | $request = $event->getRequest(); |
|
137 | |||
138 | 19 | $vary = $response->getVary(); |
|
139 | |||
140 | 19 | if ($request->headers->has($this->hashHeader)) { |
|
141 | // hash has changed, session has most certainly changed, prevent setting incorrect cache |
||
142 | 3 | if (!is_null($this->hash) && $this->hash !== $request->headers->get($this->hashHeader)) { |
|
143 | 1 | $response->setClientTtl(0); |
|
144 | 1 | $response->headers->addCacheControlDirective('no-cache'); |
|
145 | |||
146 | 1 | return; |
|
147 | } |
||
148 | |||
149 | 2 | if (!in_array($this->hashHeader, $vary)) { |
|
150 | 2 | $vary[] = $this->hashHeader; |
|
151 | 2 | } |
|
152 | 2 | } else { |
|
153 | 16 | foreach ($this->userIdentifierHeaders as $header) { |
|
154 | 16 | if (!in_array($header, $vary)) { |
|
155 | 16 | $vary[] = $header; |
|
156 | 16 | } |
|
157 | 16 | } |
|
158 | } |
||
159 | |||
160 | 18 | $response->setVary($vary, true); |
|
161 | 18 | } |
|
162 | |||
163 | /** |
||
164 | * {@inheritdoc} |
||
165 | */ |
||
166 | 23 | public static function getSubscribedEvents() |
|
173 | } |
||
174 |