Passed
Push — master ( 067df8...90cf91 )
by Zoilo
01:50
created

HttpHeaderSanitizer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 28
c 1
b 0
f 0
dl 0
loc 74
ccs 22
cts 22
cp 1
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A headerMath() 0 11 3
A sanitize() 0 11 3
A wildcardMatch() 0 11 1
1
<?php
2
3
namespace ZoiloMora\ElasticAPM\Helper;
4
5
final class HttpHeaderSanitizer
6
{
7
    /**
8
     * @var array Default list of keys to sanitise
9
     *
10
     * @link https://github.com/elastic/apm/blob/master/docs/agents/agent-development.md#http-transactions
11
     */
12
    private static $wildcards = [
13
        'password',
14
        'passwd',
15
        'pwd',
16
        'secret',
17
        '*key',
18
        '*token*',
19
        '*session*',
20
        '*credit*',
21
        '*card*',
22
        'authorization',
23
        'set-cookie',
24
    ];
25
26
    /**
27
     * @param array $headers
28
     *
29
     * @return array
30
     */
31 25
    public static function sanitize(array $headers)
32
    {
33 25
        $result = [];
34
35 25
        foreach ($headers as $key => $value) {
36 23
            if (false === self::headerMath($key)) {
37 1
                $result[$key] = $value;
38 1
            }
39 25
        }
40
41 25
        return $result;
42
    }
43
44
    /**
45
     * @param string $header
46
     *
47
     * @return bool
48
     */
49 23
    private static function headerMath($header)
50
    {
51 23
        $header = strtolower($header);
52
53 23
        foreach (self::$wildcards as $wildcard) {
54 23
            if (true === self::wildcardMatch($wildcard, $header)) {
55 22
                return true;
56
            }
57 22
        }
58
59 1
        return false;
60
    }
61
62
    /**
63
     * @param string $pattern
64
     * @param string $subject
65
     *
66
     * @return bool
67
     */
68 23
    private static function wildcardMatch($pattern, $subject)
69
    {
70 23
        $pattern = strtr(
71 23
            $pattern,
72
            [
73 23
                '*' => '.*?',
74 23
                '?' => '.',
75
            ]
76 23
        );
77
78 23
        return (bool) preg_match("/$pattern/", $subject);
79
    }
80
}
81