Completed
Pull Request — master (#175)
by
unknown
01:58
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 0 Features 0
Metric Value
cc 5
eloc 7
c 1
b 0
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 $name = null): void
50
    {
51
        if ($name === null) {
52
            self::$headers = [];
53
        } else {
54
            $name = strtolower($name);
55
            if (key_exists($name, self::$headers)) {
56
                unset(self::$headers[$name]);
57
            }
58
        }
59
    }
60
61
    /**
62
     * Returns a list of response headers sent
63
     *
64
     * @return string[]
65
     */
66
    public static function headers_list(): array
67
    {
68
        $result = [];
69
        foreach (self::$headers as $values) {
70
            foreach ($values as $header) {
71
                $result[] = $header;
72
            }
73
        }
74
        return $result;
75
    }
76
77
    /**
78
     * Get or Set the HTTP response code
79
     */
80
    public static function http_response_code(?int $response_code = null): int
81
    {
82
        if ($response_code !== null) {
83
            self::$responseCode = $response_code;
84
        }
85
        return self::$responseCode;
86
    }
87
88
    /**
89
     * Check header is exists
90
     */
91
    public static function hasHeader(string $header): bool
92
    {
93
        $name = strtolower($header);
94
        return key_exists($name, self::$headers);
95
    }
96
}
97