<?php

/**
 * Response class
 * @author Jerôme Brilland
 * @version 1.3
 * @copyright (c) 2009, Jerôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class Response {

    /**
     * @var array Headers
     * @access private
     */
    private $headers = array();

    /**
     * @var string the response body
     * @access private
     */
    private $body = null;

    /**
     * @var int HTTP status code
     * @access private
     */
    private $status = 200;

    /**
     * HTTP status codes and messages
     * @access public
     * @static
     */
    public static $messages = array(
        200 => 'OK',
        201 => 'Created',
        204 => 'No Content',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        307 => 'Temporary Redirect',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        403 => 'Forbidden',
        404 => 'Not Found',
        409 => 'Conflict',
        410 => 'Gone',
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        503 => 'Service Unavailable'
    );

    /**
     * Redirects current request to a new URL.
     * @param string url Requested URL
     * @param int HTTP status code
     * @access public
     */
    public function redirect( $url, $status = 302 ) {
        header( $_SERVER['SERVER_PROTOCOL'] . ' ' . $status . ' ' . self::$messages[$status] );
        header( 'Location: ' . $url );
        exit( 0 );
    }

    /**
     * Sets the HTTP response status
     * @param int status HTTP status code
     * @access public
     */
    public function setStatus( $status ) {
        $this->status = $status;
    }

    /**
     * @param string key Key
     * @param string value Value
     * @access public
     */
    public function addHeader( $key, $value ) {
        $this->headers[$key] = $value;
    }

    /**
     * Sets the response body
     * @access public
     */
    public function setBody( $body ) {
        $this->body = $body;
    }

    /**
     * @access public
     */
    public function printOut() {
        header( $_SERVER['SERVER_PROTOCOL'] . ' ' . $this->status . ' ' . self::$messages[$this->status] );
        foreach ( $this->headers as $key => $value ) {
            header( $key . ': ' . $value );
        }
        //ob_start();
        echo $this->body;
        //ob_end_clean();
    }

}

?>