Regex::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Mbright\Validation\Rule\Sanitize;
4
5
class Regex implements SanitizeRuleInterface
6
{
7
    /** @var string  */
8
    protected $expr;
9
10
    /** @var string */
11
    protected $replace;
12
13
    /**
14
     * @param string $expr The regular expression pattern to apply.
15
     * @param string $replace Value to replace the found pattern with
16
     */
17 6
    public function __construct(string $expr, string $replace)
18
    {
19 6
        $this->expr = $expr;
20 6
        $this->replace =$replace;
21 6
    }
22
23
    /**
24
     * Applies `preg_replace()` to the value.
25
     *
26
     * @param object $subject The subject to be filtered.
27
     * @param string $field The subject field name.
28
     *
29
     * @return bool True if the value was sanitized, false if not.
30
     */
31 6
    public function __invoke($subject, string $field): bool
32
    {
33 6
        $value = $subject->$field;
34 6
        if (!is_scalar($value)) {
35 3
            return false;
36
        }
37 3
        $subject->$field = preg_replace($this->expr, $this->replace, $value);
38
39 3
        return true;
40
    }
41
}
42