/** * Add headers represented by an array of header lines. * * @param string[] $headers Response headers as array of header lines. * * @return $this * * @throws \UnexpectedValueException For invalid header values. * @throws \InvalidArgumentException For invalid status code arguments. */ public function setHeadersFromArray(array $headers) { $statusLine = trim(array_shift($headers)); $parts = explode(' ', $statusLine, 3); if (count($parts) < 2 || substr(strtolower($parts[0]), 0, 5) !== 'http/') { throw new \UnexpectedValueException(sprintf('"%s" is not a valid HTTP status line', $statusLine)); } $reasonPhrase = count($parts) > 2 ? $parts[2] : ''; $this->response = $this->response->withStatus((int) $parts[1], $reasonPhrase)->withProtocolVersion(substr($parts[0], 5)); foreach ($headers as $headerLine) { $headerLine = trim($headerLine); if ('' === $headerLine) { continue; } $parts = explode(':', $headerLine, 2); if (count($parts) !== 2) { throw new \UnexpectedValueException(sprintf('"%s" is not a valid HTTP header line', $headerLine)); } $name = trim(urldecode($parts[0])); $value = trim(urldecode($parts[1])); if ($this->response->hasHeader($name)) { $this->response = $this->response->withAddedHeader($name, $value); } else { $this->response = $this->response->withHeader($name, $value); } } return $this; }
/** * Options * * Responding to OPTIONS requests and checks for implemented * methods that matches HTTP METHODS. * * @return array * @throws MethodNotAllowed */ public function options() { if (!$this->response instanceof ResponseInterface) { throw new MethodNotAllowed(); } // Get all implemented methods for this resources $methods = get_class_methods(get_class($this)); // Get supported verbs $validMethods = $this->container['validHttpVerbs']; // Loop though class functions/methods foreach ($methods as $key => &$method) { $method = strtoupper($method); // If class function/method isn't a verb, then unset it if (!in_array($method, $validMethods)) { unset($methods[$key]); } } // Set accept header $this->response = $this->response->withAddedHeader('Allow', implode(', ', $methods)); // Prepare output $output = []; $output['Content-Type'] = $this->container['contentTypes']; $output['Accept'] = $this->container['acceptTypes']; foreach ($methods as $verb) { $doc = $this->parseMethodDoc($verb); // Check if there is any output to show if (!empty($doc)) { $output['methods'][$verb] = $doc; } } // return output return $output; }
/** * Proxy to PsrResponseInterface::withAddedHeader() * * {@inheritdoc} */ public function withAddedHeader($header, $value) { if ($this->complete) { return $this; } $new = $this->psrResponse->withAddedHeader($header, $value); return new self($new); }
/** * Add the set cookies to a response. * * @param ResponseInterface $response * * @return ResponseInterface */ public function addToResponse(ResponseInterface $response) : ResponseInterface { $header = []; foreach ($this->cookies as $setCookie) { $header[] = $setCookie->toHeaderValue(); } return $response->withAddedHeader('Set-Cookie', $header); }
/** * Proxy to PsrResponseInterface::withAddedHeader() * * {@inheritdoc} * @throws RuntimeException if response is already completed */ public function withAddedHeader($header, $value) { if ($this->complete) { throw $this->responseIsAlreadyCompleted(__METHOD__); } $new = $this->psrResponse->withAddedHeader($header, $value); return new self($new); }
/** * Create all headers for a regular request */ protected function createRequestHeaders() { $headers = []; // Set Allowed origin header (either * or Origin from request) $headers = $this->createOriginHeader($headers); // Set support credentials header $headers = $this->createCredentialsHeader($headers); // Set exposed headers header $headers = $this->createExposedHeadersHeader($headers); // Add the headers to the response foreach ($headers as $name => $value) { $this->response = $this->response->withAddedHeader($name, (string) $value); } }
/** * Add header represented by a string. * * @param string $headerLine Response header as a string. * * @return $this * * @throws \InvalidArgumentException For invalid header names or values. */ public function addHeader($headerLine) { $parts = explode(':', $headerLine, 2); if (count($parts) !== 2) { throw new \InvalidArgumentException(sprintf('"%s" is not a valid HTTP header line', $headerLine)); } $name = trim(urldecode($parts[0])); $value = trim(urldecode($parts[1])); if ($this->response->hasHeader($name)) { $this->response = $this->response->withAddedHeader($name, $value); } else { $this->response = $this->response->withHeader($name, $value); } return $this; }
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $index = $this->storage->getIndex(); return $response->withAddedHeader('X-Demeter-Index', $index); }
/** * {@inheritdoc} */ public function withAddedHeader($name, $value) { return new HttpException($this->response->withAddedHeader($name, $value), $this->attributes); }
public function addToResponse(ResponseInterface $response) : ResponseInterface { return $response->withAddedHeader('Set-Cookie', $this->toHeaderValue()); }
/** * Add session cookie Set-Cookie header to response. * * @param ResponseInterface $response * * @throws \InvalidArgumentException * * @return ResponseInterface */ protected function respondWithSessionCookie(ResponseInterface $response) { if (session_status() !== PHP_SESSION_ACTIVE || !array_key_exists($this->sessionTimeoutKey, $_SESSION)) { $expireTime = time() - $this->sessionLifetime; } else { $expireTime = $_SESSION[$this->sessionTimeoutKey]; } $cookieParams = [sprintf('expires=%s; max-age=%s', gmdate('D, d M Y H:i:s T', $expireTime), $this->sessionLifetime)]; if (trim($this->getSessionSetting('cookie_path')) !== '') { $cookieParams[] = 'path=' . $this->getSessionSetting('cookie_path'); } if (trim($this->getSessionSetting('cookie_domain')) !== '') { $cookieParams[] = 'domain=' . $this->getSessionSetting('cookie_domain'); } if ((bool) $this->getSessionSetting('cookie_secure')) { $cookieParams[] = 'secure'; } if ((bool) $this->getSessionSetting('cookie_httponly')) { $cookieParams[] = 'httponly'; } return $response->withAddedHeader('Set-Cookie', sprintf('%s=%s; %s', urlencode($this->sessionName), urlencode(session_id()), implode('; ', $cookieParams))); }
public function apply(ResponseInterface $respose) { return $respose->withAddedHeader(self::HEADER_NAME, (string) $this); }
/** * {@inheritdoc} */ public function removeToken(Request $request, Response $response, TokenInterface $token) { return $response->withAddedHeader('Set-Cookie', $this->cookieHeader($request, null)); }
/** * {@inheritdoc} */ public function mountToken(Request $request, Response $response, TokenInterface $token) { return $response->withAddedHeader($this->header, $token->getHash()); }
/** * {@inheritDoc} */ public function withAddedHeader($name, $value) { return new self($this->app, $this->decorated->withAddedHeader($name, $value)); }
/** * Add no-cache cache headers to response. * * @param ResponseInterface $response * * @throws \InvalidArgumentException * * @return ResponseInterface */ protected function respondWithNoCacheCache(ResponseInterface $response) { return $response->withAddedHeader('Expires', static::CACHE_EXPIRED)->withAddedHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0')->withAddedHeader('Pragma', 'no-cache'); }
/** * Set tags on a response. * * @param ResponseInterface $response Original response * @param bool $replace Whether to replace the current tags * on the response * * @return ResponseInterface Tagged response */ public function tagResponse(ResponseInterface $response, $replace = false) { if ($replace) { return $response->withHeader($this->getTagsHeaderName(), $this->getTagsHeaderValue()); } return $response->withAddedHeader($this->getTagsHeaderName(), $this->getTagsHeaderValue()); }
/** * @inheritDoc */ public function withAddedHeader($name, $value) { return new self($this->psrResponse->withAddedHeader($name, $value)); }
/** * Set content type to response * * @param string $type * * @return static */ protected function setContentType($type) { $this->response = $this->response->withAddedHeader('Content-Type', $type); return $this; }
/** * Sets/renews the site access cookie. Only call this if the user has * actually access to the website. This method does nothing if the website * has no site key set. * @param ResponseInterface $response The current response. * @return ResponseInterface The response with the Set-Cookie header. */ private function withSiteAccessCookie(ResponseInterface $response) { $siteKey = $this->website->getConfig()->get(Config::OPTION_ACCESS_CODE); if (empty($siteKey)) { // The website doesn't use an access key return $response; } $now = new DateTimeImmutable(); $expires = $now->add(new DateInterval('P60D'))->format('r'); $siteUrl = $this->website->getText()->getUrlMain(); $path = empty($siteUrl->getPath()) ? '/' : $siteUrl->getPath(); $cookieInstructioh = "key={$siteKey}; expires={$expires}; path={$path}"; return $response->withAddedHeader("Set-Cookie", $cookieInstructioh); }
public function withAddedHeader($name, $value) { $response = clone $this; $response->response = $this->response->withAddedHeader($name, $value); return $response; }
/** * Return an instance with the specified header appended with the given value. * * Existing values for the specified header will be maintained. The new * value(s) will be appended to the existing list. If the header did not * exist previously, it will be added. * * This method MUST be implemented in such a way as to retain the * immutability of the message, and MUST return an instance that has the * new header and/or value. * * @param string $name Case-insensitive header field name to add. * @param string|string[] $value Header value(s). * @return self * @throws \InvalidArgumentException for invalid header names or values. */ function withAddedHeader($name, $value) { return $this->response->withAddedHeader($name, $value); }
/** * Expire a cookie in the response. * * Do not worry about duplicated cookies, they will be deduped when the * response is rendered by "EncryptedCookieMiddleware". * * @param ResponseInterface $response * @param string $name * * @return ResponseInterface */ public function expireCookie(ResponseInterface $response, $name) { $cookie = SetCookie::createExpired($name)->withMaxAge($this->configuration['maxAge'])->withPath($this->configuration['path'])->withDomain($this->configuration['domain'])->withSecure($this->configuration['secure'])->withHttpOnly($this->configuration['httpOnly']); return $response->withAddedHeader(static::RESPONSE_COOKIE_NAME, $cookie); }
/** * Add the CSRF token to the response cookies. * * @param \Psr\Http\Message\ResponseInterface $response * * @return \Psr\Http\Message\ResponseInterface */ protected function addCookieToResponse(ResponseInterface $response) : ResponseInterface { $config = $this->manager->getConfig(); $setCookie = new Cookie('XSRF-TOKEN', $this->tokenService->generate(), $config->get('session::csrf.livetime', Chronos::now()->getTimestamp() + 60 * 120), $config->get('path'), $config->get('domain'), $config->get('secure', false), false, $config->get('session::csrf.samesite', false)); return $response->withAddedHeader('Set-Cookie', (string) $setCookie); }
/** * Mount session id or remove session cookie. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param SessionStore $store * @param array $cookies * @return ResponseInterface */ protected function setCookie(ServerRequestInterface $request, ResponseInterface $response, SessionStore $store, array $cookies) { if ($store->isStarted()) { $store->commit(); } if (!isset($cookies[self::COOKIE]) || $cookies[self::COOKIE] != $store->getID()) { if ($response instanceof ResponseInterface) { return $response->withAddedHeader('Set-Cookie', Cookie::create(self::COOKIE, $store->getID(), $store->config()['lifetime'], $request->getAttribute('basePath'), $request->getAttribute('cookieDomain'))->packHeader()); } } return $response; }