Passed
Pull Request — master (#164)
by
unknown
03:13
created

Header::normalizeHeaderKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
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.4.0
13
 */
14
15
namespace Quantum\Http\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
	      list($keyWithHyphens, $keyWithUnderscores) = self::normalizeHeaderKey($key);
50
51
	      if (array_key_exists($keyWithHyphens, self::$__headers)) {
52
		        return self::$__headers[$keyWithHyphens];
53
	      } elseif (array_key_exists($keyWithUnderscores, self::$__headers)) {
54
		        return self::$__headers[$keyWithUnderscores];
55
	      }
56
	      return null;
57
    }
58
59
    /**
60
     * Sets the request header
61
     * @param string $key
62
     * @param mixed $value
63
     */
64
    public static function setHeader(string $key, $value)
65
    {
66
        self::$__headers[strtolower($key)] = $value;
67
    }
68
69
    /**
70
     * Gets all request headers
71
     * @return array
72
     */
73
    public static function allHeaders(): array
74
    {
75
        return self::$__headers;
76
    }
77
78
    /**
79
     * Deletes the header by given key
80
     * @param string $key
81
     */
82
    public static function deleteHeader(string $key)
83
    {
84
        if (self::hasHeader($key)) {
85
            unset(self::$__headers[strtolower($key)]);
86
        }
87
    }
88
89
	  /**
90
	   * @param string $key
91
	   * @return array
92
	   */
93
	  private static function normalizeHeaderKey(string $key): array
94
	  {
95
	  	$keyWithHyphens = str_replace('_', '-', strtolower($key));
96
	  	$keyWithUnderscores = str_replace('-', '_', $key);
97
	  	return [$keyWithHyphens, $keyWithUnderscores];
98
	  }
99
}