Determine the http status to be sent in php

I am trying to write a test case for a class that manages the headers for my application. Among the headers he sends are http status headers. I use headers_list () to see which headers will be sent if I sent the headers now. The problem with headers_list () is that it does not include the http status header (although this is not documented on php.net). Thus, I cannot find a way to determine which http status will be sent. Even if I send headers (which I try not to do, so I can check many different things at a time), the status does not appear in headers_list (). Any ideas?

PS I understand that I can do this by requesting a page and analyzing the answer, but this makes it difficult to conduct tests at the unit level, so I try to avoid this.

+3
source share
1 answer

Either use a Mock that returns a header but does not send it or write a Response object, for example.

class HttpResponse 
{
    protected $_status = '200 OK';
    protected $_headers = array();
    protected $_body = null;

    public function setStatus($status)
    {
        $this->_status = $status;
    }

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

    public function addHeader($name, $value)
    {
        $this->_headers[$name] = $value;
        return $this;
    }

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

    public function write($data)
    {
        $this->_body .= $data;
        return $this;
    }

    public function send()
    {
        header('HTTP/1.0 ' . $this->_status);
        foreach ($this->headers as $name => $value) {
            header("$name : $value");
        }
        echo $this->_body;
        $this->resetRequest();
    }

   public function resetRequest()
   {
        $this->_status  = '200 OK';
        $this->_headers = array();
        $this->_body    = null;
   }
}

So, while you're not send(), you can check the status through getters. You can also add a method __toString()that returns the Entire Response as a string and a regular expression to see if it looks like what you expect it to look like.

0
source

Source: https://habr.com/ru/post/1723912/


All Articles