RequestObfuscator::obfuscateContentWithPattern()   C
last analyzed

Complexity

Conditions 8
Paths 8

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 20
nc 8
nop 2
1
<?php
2
3
namespace Rezzza\SecurityBundle\Request\Obfuscator;
4
5
use Rezzza\SecurityBundle\Exception\ObfuscateBadPatternException;
6
7
/**
8
 * RequestObfuscator
9
 *
10
 * @uses ObfuscatorInterface
11
 * @author Stephane PY <[email protected]>
12
 */
13
class RequestObfuscator implements ObfuscatorInterface
14
{
15
    CONST TOKEN_REPLACE = 'X';
16
    CONST TOKEN_ALL = '*';
17
18
    /**
19
     * {@inheritdoc}
20
     */
21
    public function obfuscate(array $data, array $obfuscatedPatterns)
22
    {
23
        foreach ($obfuscatedPatterns as $key => $pattern) {
24
            if (isset($data[$key])) {
25
                $data[$key] = $this->obfuscateContentWithPattern($data[$key], $pattern);
26
            }
27
        }
28
29
        return $data;
30
    }
31
32
    private function obfuscateContentWithPattern($content, $pattern)
33
    {
34
        if (!is_array($content)) {
35
            return is_scalar($content) ? $this->obfuscateContent($content) : null;
36
        }
37
38
        if ($pattern === self::TOKEN_ALL) {
39
            return self::TOKEN_REPLACE;
40
        }
41
42
        $patterns    = (array) $pattern;
43
        foreach ($patterns as $pattern) {
44
            $keys = array_map(function($v) {
45
                return str_replace(']', '', $v);
46
            }, explode('[', $pattern));
47
48
            $pattern = array_shift($keys);
49
50
            if (array_key_exists($pattern, $content)) {
51
                if (count($keys) === 0) {
52
                    $content[$pattern] = $this->obfuscateContent($content[$pattern]);
53
                } else {
54
                    $newPattern = array_shift($keys);
55
                    foreach ($keys as $key) {
56
                        $newPattern .= sprintf('[%s]', $key);
57
                    }
58
                    $content[$pattern] = $this->obfuscateContentWithPattern($content[$pattern], $newPattern);
59
                }
60
            }
61
        }
62
63
        return $content;
64
    }
65
66
    private function obfuscateContent($content)
67
    {
68
        return is_scalar($content) ? str_repeat(self::TOKEN_REPLACE, strlen($content)) : self::TOKEN_REPLACE;
69
    }
70
}
71