Completed
Push — master ( f56bcc...e284f5 )
by Changwan
04:45 queued 01:40
created

Sanitizer::sanitize()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 4
nop 1
dl 0
loc 15
ccs 11
cts 11
cp 1
crap 5
rs 8.8571
c 0
b 0
f 0
1
<?php
2
namespace Wandu\Validator;
3
4
use ReflectionClass;
5
6
class Sanitizer
7
{
8
    /** @var \Wandu\Validator\Validator */
9
    protected $validator;
10
    
11
    /** @var string */
12
    protected $T;
13
    
14
    /** @var \ReflectionClass */
15
    private $refl;
16
17
    /**
18
     * @param string|\Wandu\Validator\Contracts\RuleInterface|\Wandu\Validator\Contracts\TesterInterface|\Wandu\Validator\Validator $rule
19
     * @param string $T
20
     */
21 1
    public function __construct($rule, string $T = null)
22
    {
23 1
        if ($rule instanceof Validator) {
24
            $this->validator = $rule;
25
        } else {
26 1
            $this->validator = validator($rule);
27
        }
28 1
        $this->T = $T;
29 1
    }
30
31
    /**
32
     * @param mixed $data
33
     * @return mixed|{$this->T}
0 ignored issues
show
Documentation introduced by
The doc-type mixed|{$this->T} could not be parsed: Unknown type name "{$this-" at position 6. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
34
     */
35 1
    public function sanitize($data)
36
    {
37 1
        $this->validator->assert($data);
38 1
        if (!$this->T || !class_exists($this->T)) return $data;
39 1
        $refl = $this->getReflectionClass();
40 1
        $instance = $refl->newInstanceWithoutConstructor();
41 1
        foreach ($refl->getProperties() as $reflectionProperty) {
42 1
            $propertyName = $reflectionProperty->getName();
43 1
            if (isset($data[$propertyName])) {
44 1
                $reflectionProperty->setAccessible(true);
45 1
                $reflectionProperty->setValue($instance, $data[$propertyName]);
46
            }
47
        }
48 1
        return $instance;
49
    }
50
51
    /**
52
     * @return \ReflectionClass
53
     */
54 1
    protected function getReflectionClass(): ReflectionClass
55
    {
56 1
        if (!isset($this->refl)) {
57 1
            $this->refl = new ReflectionClass($this->T);
58
        }
59 1
        return $this->refl;
60
    }
61
}
62