1<?php
2
3
4namespace ComboStrap;
5
6
7class Http
8{
9
10    public static function removeHeaderIfPresent(string $key)
11    {
12        foreach (headers_list() as $header) {
13            if (preg_match("/$key/i", $header)) {
14                header_remove($key);
15            }
16        }
17
18    }
19
20    public static function getHeader(string $name)
21    {
22
23        $result = array();
24        foreach (self::getHeaders() as $header) {
25            if (substr($header, 0, strlen($name) + 1) == $name . ':') {
26                $result[] = $header;
27            }
28        }
29
30        return count($result) == 1 ? $result[0] : $result;
31
32    }
33
34    private static function getHeaders(): array
35    {
36        return (function_exists('xdebug_get_headers') ? xdebug_get_headers() : headers_list());
37    }
38
39    /**
40     * Set the HTTP status
41     * Dokuwiki test does not {@link \TestResponse::getStatusCode()} capture the status with all php function such
42     * as {@link http_response_code},
43     *
44     * @param int $int
45     */
46    public static function setStatus(int $int)
47    {
48        /**
49         * {@link http_status} function
50         * that creates
51         * header('HTTP/1.1 301 Moved Permanently');
52         * header('HTTP/1.0 304 Not Modified');
53         * header('HTTP/1.1 404 Not Found');
54         *
55         * not {@link http_response_code}
56         */
57        http_status($int);
58
59    }
60
61    public static function getStatus()
62    {
63        /**
64         * See also {@link Http::getHeader()}
65         * if this does not work
66         */
67        return http_response_code();
68    }
69
70    public static function setMime(string $mime)
71    {
72        $contentTypeHeader = Mime::HEADER_CONTENT_TYPE;
73        header("$contentTypeHeader: $mime");
74    }
75
76    public static function setJsonMime()
77    {
78        Http::setMime(Mime::JSON);
79    }
80
81    /**
82     * PHP is blocking and fsockopen also.
83     * Don't use it in a page rendering flow
84     * https://segment.com/blog/how-to-make-async-requests-in-php/
85     * @param $url
86     */
87    function sendAsyncRequest($url)
88    {
89        $parts=parse_url($url);
90        $fp = fsockopen($parts['host'],isset($parts['port'])?$parts['port']:80,$errno, $errstr, 30);
91        $out = "GET ".$parts['path'] . "?" . $parts['query'] . " HTTP/1.1\r\n";
92        $out.= "Host: ".$parts['host']."\r\n";
93        $out.= "Content-Length: 0"."\r\n";
94        $out.= "Connection: Close\r\n\r\n";
95
96        fwrite($fp, $out);
97        fclose($fp);
98    }
99
100
101}
102