Censor   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 61
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setOption() 0 7 1
A getReplaceCallback() 0 10 2
A filterSingle() 0 12 3
1
<?php
2
declare(strict_types=1);
3
namespace Sirius\Filtration\Filter;
4
5
class Censor extends AbstractFilter
6
{
7
    // how may characters from the benining are left untouched
8
    const OPTION_START_CHARACTERS = 'start_characters';
9
    // how may characters from the end are left untouched
10
    const OPTION_END_CHARACTERS = 'end_characters';
11
    // replacement character
12
    const OPTION_REPLACEMENT_CHAR = 'replacement_char';
13
    // censored words
14
    const OPTION_WORDS = 'words';
15
16
    protected $options = [
17
        self::OPTION_START_CHARACTERS => 1,
18
        self::OPTION_END_CHARACTERS => 1,
19
        self::OPTION_REPLACEMENT_CHAR => '*',
20
        self::OPTION_WORDS => [
21
            'fuck',
22
            'fucker',
23
            'fuckers',
24
            'fucking',
25
            'motherfucker',
26
            'asshole',
27
            'cunt',
28
            'dick'
29
        ]
30
    ];
31
32
    protected $obfuscator;
33
34 1
    public function setOption($name, $value)
35
    {
36 1
        parent::setOption($name, $value);
37
        // reset the obfuscator in case the options are changed during the usage
38 1
        $this->obfuscator = null;
39 1
        return $this;
40
    }
41
42 2
    protected function getReplaceCallback()
43
    {
44 2
        if (! $this->obfuscator) {
45 2
            $this->obfuscator = new Obfuscate($this->options);
46
        }
47 2
        $obfuscator = $this->obfuscator;
48
        return function ($matches) use ($obfuscator) {
49 2
            return $obfuscator->filter($matches[0]);
50 2
        };
51
    }
52
53 3
    public function filterSingle($value, string $valueIdentifier = null)
54
    {
55
        // not a string, move along
56 3
        if (! is_string($value)) {
57 1
            return $value;
58
        }
59 2
        foreach ($this->options[self::OPTION_WORDS] as $word) {
60 2
            $value = \preg_replace_callback("|\b{$word}\b|i", $this->getReplaceCallback(), $value);
61
        }
62
        
63 2
        return $value;
64
    }
65
}
66