public function handle(RequestInterface $request, ResponseInterface $response, FilterChainInterface $filterChain) { $signature = null; if ($request->hasHeader('Cookie')) { $cookies = Cookie::parseList($request->getHeader('Cookie')); foreach ($cookies as $cookie) { if ($cookie->getName() == self::COOKIE_NAME) { $data = $cookie->getValue(); $parts = explode('.', $data, 2); $payload = isset($parts[0]) ? $parts[0] : null; $signature = isset($parts[1]) ? $parts[1] : null; if (strcmp($signature, $this->generateSignature($payload)) === 0) { $request->setAttribute(self::COOKIE_NAME, $this->unserializeData($payload)); } else { // invalid signature } break; } } } $filterChain->handle($request, $response); $data = $request->getAttribute(self::COOKIE_NAME); if (!empty($data)) { $payload = $this->serializeData($data); $newSignature = $this->generateSignature($payload); // send only a new cookie if the data has changed if ($newSignature != $signature) { $response->addHeader('Set-Cookie', self::COOKIE_NAME . '=' . $payload . '.' . $newSignature); } } }