1: <?php
2: namespace Worldline\Connect\Sdk\Logging;
3:
4: /**
5: * Class HeaderObfuscator
6: *
7: * @package Worldline\Connect\Sdk\Logging
8: */
9: class HeaderObfuscator
10: {
11: /**
12: * @var ValueObfuscator
13: */
14: protected ValueObfuscator $valueObfuscator;
15:
16: /**
17: * @var array<string, callable>
18: */
19: private array $customRules = array();
20:
21: public function __construct()
22: {
23: $this->valueObfuscator = new ValueObfuscator();
24: }
25:
26: /**
27: * @param string[] $headers
28: *
29: * @return string[]
30: */
31: public function obfuscateHeaders(array $headers): array
32: {
33: foreach ($headers as $headerName => &$headerValue) {
34: $headerValue = $this->obfuscateHeaderValue($headerName, $headerValue);
35: }
36: return $headers;
37: }
38:
39: /**
40: * @param string $key
41: * @param array|string $value
42: *
43: * @return array|string
44: */
45: protected function obfuscateHeaderValue(string $key, $value)
46: {
47: $lowerKey = mb_strtolower($key, 'UTF-8');
48: if (isset($this->customRules[$lowerKey])) {
49: return $this->replaceHeaderValueWithCustomRule($value, $this->customRules[$lowerKey]);
50: }
51: switch ($lowerKey) {
52: case 'authorization':
53: case 'www-authenticate':
54: case 'proxy-authenticate':
55: case 'proxy-authorization':
56: case 'x-gcs-authentication-token':
57: case 'x-gcs-callerpassword':
58: return $this->replaceHeaderValueWithFixedNumberOfCharacters($value, 8);
59: default:
60: return $value;
61: }
62: }
63:
64: /**
65: * @param array|string $value
66: * @param int $numberOfCharacters
67: *
68: * @return array|string
69: */
70: protected function replaceHeaderValueWithFixedNumberOfCharacters($value, int $numberOfCharacters)
71: {
72: if (is_array($value)) {
73: return array_fill(0, count($value), $this->valueObfuscator->obfuscateFixedLength($numberOfCharacters));
74: } else {
75: return $this->valueObfuscator->obfuscateFixedLength($numberOfCharacters);
76: }
77: }
78:
79: /**
80: * @param array|string $value
81: * @param callable $customRule
82: *
83: * @return array|string
84: */
85: protected function replaceHeaderValueWithCustomRule($value, callable $customRule)
86: {
87: if (is_array($value)) {
88: return array_map(
89: function ($v) use ($customRule) {
90: return call_user_func($customRule, $v, $this->valueObfuscator);
91: },
92: $value
93: );
94: } else {
95: return call_user_func($customRule, $value, $this->valueObfuscator);
96: }
97: }
98:
99: /**
100: * @param string $headerName
101: * @param callable $customRule
102: *
103: * @return void
104: */
105: public function setCustomRule(string $headerName, callable $customRule): void
106: {
107: $lowerName = mb_strtolower($headerName, 'UTF-8');
108: $this->customRules[$lowerName] = $customRule;
109: }
110: }
111: