Completed
Push — master ( 299de3...93b43e )
by Alexander
02:01
created

HTTPFunctions::header()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 5
eloc 7
c 1
b 1
f 0
nc 6
nop 3
dl 0
loc 11
rs 9.6111
1
<?php
2
/**
3
 * This class used to override some header*() functions and http_response_code()
4
 *
5
 * We put these into the Yii namespace, so that Yiisoft\Yii\Web\Emitter will use these versions of header*() and
6
 * http_response_code() when we test its output.
7
 */
8
9
declare(strict_types=1);
10
11
namespace Yiisoft\Yii\Web\Tests\Emitter;
12
13
class HTTPFunctions
14
{
15
    /** @var string[][] */
16
    private static $headers = [];
17
    /** @var int */
18
    private static $responseCode = 200;
19
20
    /**
21
     * Reset state
22
     */
23
    public static function reset(): void
24
    {
25
        self::$headers = [];
26
        self::$responseCode = 200;
27
    }
28
29
    /**
30
     * Send a raw HTTP header
31
     */
32
    public static function header(string $string, bool $replace = true, ?int $http_response_code = null): void
33
    {
34
        if (substr($string, 0, 5) !== 'HTTP/') {
35
            $header = strtolower(explode(':', $string)[0]);
36
            if ($replace || !key_exists($header, self::$headers)) {
37
                self::$headers[$header] = [];
38
            }
39
            self::$headers[$header][] = $string;
40
        }
41
        if ($http_response_code !== null) {
42
            self::$responseCode = $http_response_code;
43
        }
44
    }
45
46
    /**
47
     * Remove previously set headers
48
     */
49
    public static function header_remove(?string $header = null): void
50
    {
51
        if ($header === null) {
52
            self::$headers = [];
53
        } else {
54
            unset(self::$headers[strtolower($header)]);
55
        }
56
    }
57
58
    /**
59
     * Returns a list of response headers sent
60
     *
61
     * @return string[]
62
     */
63
    public static function headers_list(): array
64
    {
65
        $result = [];
66
        foreach (self::$headers as $values) {
67
            foreach ($values as $header) {
68
                $result[] = $header;
69
            }
70
        }
71
        return $result;
72
    }
73
74
    /**
75
     * Get or Set the HTTP response code
76
     */
77
    public static function http_response_code(?int $response_code = null): int
78
    {
79
        if ($response_code !== null) {
80
            self::$responseCode = $response_code;
81
        }
82
        return self::$responseCode;
83
    }
84
85
    /**
86
     * Check header is exists
87
     */
88
    public static function hasHeader(string $header): bool
89
    {
90
        return key_exists(strtolower($header), self::$headers);
91
    }
92
}
93