Completed
Push — master ( c6f836...23da77 )
by Arman
18s queued 15s
created

Header::getBasicAuthCredentials()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 13
nc 5
nop 0
dl 0
loc 25
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.9.8
13
 */
14
15
namespace Quantum\Http\Traits\Request;
16
17
/**
18
 * Trait Header
19
 * @package Quantum\Http\Request
20
 */
21
trait Header
22
{
23
24
    /**
25
     * Request headers
26
     * @var array
27
     */
28
    private static $__headers = [];
29
30
    /**
31
     * Checks the request header existence by given key
32
     * @param string $key
33
     * @return bool
34
     */
35
    public static function hasHeader(string $key): bool
36
    {
37
        list($keyWithHyphens, $keyWithUnderscores) = self::normalizeHeaderKey($key);
38
39
        return isset(self::$__headers[$keyWithHyphens]) || isset(self::$__headers[$keyWithUnderscores]);
40
    }
41
42
    /**
43
     * Gets the request header by given key
44
     * @param string $key
45
     * @return string|null
46
     */
47
    public static function getHeader(string $key): ?string
48
    {
49
        if (self::hasHeader($key)) {
50
            list($keyWithHyphens, $keyWithUnderscores) = self::normalizeHeaderKey($key);
51
            return self::$__headers[$keyWithHyphens] ?? self::$__headers[$keyWithUnderscores];
52
        }
53
54
        return null;
55
    }
56
57
    /**
58
     * Sets the request header
59
     * @param string $key
60
     * @param mixed $value
61
     */
62
    public static function setHeader(string $key, $value)
63
    {
64
        self::$__headers[strtolower($key)] = $value;
65
    }
66
67
    /**
68
     * Gets all request headers
69
     * @return array
70
     */
71
    public static function allHeaders(): array
72
    {
73
        return self::$__headers;
74
    }
75
76
    /**
77
     * Deletes the header by given key
78
     * @param string $key
79
     */
80
    public static function deleteHeader(string $key)
81
    {
82
        if (self::hasHeader($key)) {
83
            unset(self::$__headers[strtolower($key)]);
84
        }
85
    }
86
87
    /**
88
     * Gets Authorization Bearer token
89
     * @return string|null
90
     */
91
    public static function getAuthorizationBearer(): ?string
92
    {
93
        $bearerToken = null;
94
95
        $authorization = (string)self::getHeader('Authorization');
96
97
        if (self::hasHeader('Authorization')) {
98
            if (preg_match('/Bearer\s(\S+)/', $authorization, $matches)) {
99
                $bearerToken = $matches[1];
100
            }
101
        }
102
103
        return $bearerToken;
104
    }
105
106
107
    /**
108
     * Gets Basic Auth Credentials
109
     * @return array|null
110
     */
111
    public static function getBasicAuthCredentials(): ?array
112
    {
113
        if (self::$server->has('PHP_AUTH_USER') && static::$server->has('PHP_AUTH_PW')) {
114
            return [
115
                'username' => self::$server->get('PHP_AUTH_USER'),
116
                'password' => self::$server->get('PHP_AUTH_PW'),
117
            ];
118
        }
119
120
        if (!self::hasHeader('Authorization')) {
121
            return null;
122
        }
123
124
        $authorization = (string)self::getHeader('Authorization');
125
126
        if (preg_match('/Basic\s(\S+)/', $authorization, $matches)) {
127
            $decoded = base64_decode($matches[1], true);
128
129
            if ($decoded && strpos($decoded, ':') !== false) {
130
                list($username, $password) = explode(':', $decoded, 2);
131
                return ['username' => $username, 'password' => $password];
132
            }
133
        }
134
135
        return null;
136
    }
137
138
    /**
139
     * Checks to see if request was AJAX request
140
     * @return bool
141
     */
142
    public static function isAjax(): bool
143
    {
144
        return self::hasHeader('X-REQUESTED-WITH') || self::$server->ajax();
145
    }
146
147
    /**
148
     * Gets the referrer
149
     * @return string|null
150
     */
151
    public static function getReferrer(): ?string
152
    {
153
        return self::$server->referrer();
154
    }
155
156
    /**
157
     * @param string $key
158
     * @return array
159
     */
160
    private static function normalizeHeaderKey(string $key): array
161
    {
162
        $keyWithHyphens = str_replace('_', '-', strtolower($key));
163
        $keyWithUnderscores = str_replace('-', '_', $key);
164
165
        return [$keyWithHyphens, $keyWithUnderscores];
166
    }
167
}