Censor::filterSingle()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 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