<?php
namespace Qii\Response;

use Qii\Exceptions\Response;

class Http extends \Qii\Base\Response
{

    /**
     * 判断是否可以输出header
     *
     * @param bool $throw 是否抛出异常
     * @return bool
     * @throws \Exception
     */
    public function canSendHeaders($throw = false)
    {
        $ok = headers_sent($file, $line);
        if ($ok && $throw) {
            throw new \Exception('Cannot send headers; headers already sent in ' . $file . ', line ' . $line);
        }
        return !$ok;
    }
    /**
     * Send all headers
     *
     * Sends any headers specified.
     * If an {@link setResponseCode() HTTP response code}
     * has been specified, it is sent with the first header.
     *
     * @return Qii\Response\Http
     */
    protected function sendHeaders()
    {
        $httpCodeSent = false;
        if (!$this->_sendHeader || !is_array($this->headers)) {
            return $this;
        }
        if(!$this->canSendHeaders()){
            return;
        }

        foreach ($this->headers as $header) {
            if (!$httpCodeSent && $this->_responseCode) {
                header(
                    $header['name'] . ': ' . $header['value'],
                    $header['replace'], $this->_responseCode
                );
                $httpCodeSent = true;
            } else {
                header(
                    $header['name'] . ': ' . $header['value'],
                    $header['replace']
                );
            }
        }
        return $this;
    }

    /**
     * Set redirect URL
     *
     * Sets Location header. Forces replacement of any prior redirects.
     *
     * @param string $url
     * @return Qii_Response_Abstract
     */
    public function setRedirect($url)
    {
        $this->setHeader('Location', $url, true)
            ->setResponseCode(302);
        return $this;
    }
}