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