You are here

public function Response::prepare in RESTful 7.2

Prepares the Response before it is sent to the client.

This method tweaks the Response to ensure that it is compliant with RFC 2616. Most of the changes are based on the Request that is "associated" with this Response.

Parameters

RequestInterface $request: A Request instance

Overrides ResponseInterface::prepare

File

src/Http/Response.php, line 209
Contains \Drupal\restful\Http\Response.

Class

Response

Namespace

Drupal\restful\Http

Code

public function prepare(RequestInterface $request) {
  $headers = $this->headers;
  if ($this
    ->isInformational() || $this
    ->isEmpty()) {
    $this
      ->setContent(NULL);
    $headers
      ->remove('Content-Type');
    $headers
      ->remove('Content-Length');
  }
  else {

    // Content-type based on the Request. The content type should have been
    // set in the RestfulFormatter.
    // Fix Content-Type
    $charset = $this->charset ?: 'UTF-8';
    $content_type = $headers
      ->get('Content-Type')
      ->getValueString();
    if (stripos($content_type, 'text/') === 0 && stripos($content_type, 'charset') === FALSE) {

      // add the charset
      $headers
        ->add(HttpHeader::create('Content-Type', $content_type . '; charset=' . $charset));
    }

    // Fix Content-Length
    if ($headers
      ->has('Transfer-Encoding')) {
      $headers
        ->remove('Content-Length');
    }
    if ($request
      ->getMethod() == RequestInterface::METHOD_HEAD) {

      // cf. RFC2616 14.13
      $length = $headers
        ->get('Content-Length')
        ->getValueString();
      $this
        ->setContent(NULL);
      if ($length) {
        $headers
          ->add(HttpHeader::create('Content-Length', $length));
      }
    }
  }

  // Fix protocol
  $server_info = $request
    ->getServer();
  if ($server_info['SERVER_PROTOCOL'] != 'HTTP/1.0') {
    $this
      ->setProtocolVersion('1.1');
  }

  // Check if we need to send extra expire info headers
  if ($this
    ->getProtocolVersion() == '1.0' && $this->headers
    ->get('Cache-Control')
    ->getValueString() == 'no-cache') {
    $this->headers
      ->add(HttpHeader::create('pragma', 'no-cache'));
    $this->headers
      ->add(HttpHeader::create('expires', -1));
  }
  $this
    ->ensureIEOverSSLCompatibility($request);
}