<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

class WV_HTTP_Response {
	protected $headers;
	protected $content;
	protected $status;
	protected $statusMessage;

	public function __construct($content, $headers) {
		$this->content = $content;
		$this->headers = array();

		// In Headers können die Header mehrerer Requests enthalten sein.
		// Daher leere wir die Liste der aktuellen Header nach jeder HTTP/-Zeile.

		foreach ($headers as $header) {
			$header = trim($header);

			if (empty($header)) {
				continue;
			}

			if (preg_match('#^HTTP/(0\.9|1\.0|1\.1) ([1-5][0-9]{2}) (.+?)$#i', $header, $matches)) {
				$this->status        = intval($matches[2]);
				$this->statusMessage = $matches[3];
				$this->headers       = array();
			}
			else {
				list($header, $message) = array_map('trim', explode(':', $header, 2));
				if (!isset($this->headers[strtolower($header)])) {
					$this->headers[strtolower($header)] = array();
				}
				$this->headers[strtolower($header)][] = $message;
			}
		}
	}

	public function getStatus() {
		return $this->status;
	}

	public function getStatusMessage() {
		return $this->statusMessage;
	}

	public function isNotFound() {
		return $this->status == 404;
	}

	public function isOK() {
		return $this->status == 200;
	}

	public function getContent() {
		return $this->content;
	}

	public function __toString() {
		return $this->content;
	}

	public function getHeaders() {
		return $this->headers;
	}

	public function getHeader($header, $default = '') {
		if (!$this->hasHeader($header)) {
			return $default;
		}

		$header = $this->headers[strtolower($header)];
		return count($header) == 1 ? $header[0] : $header;
	}

	public function hasHeader($header) {
		return isset($this->headers[strtolower($header)]);
	}
}
