SanitizeSpec::to()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Mbright\Validation\Spec;
4
5
use Mbright\Validation\Exception\ValidationFailureException;
6
use Mbright\Validation\Rule\Sanitize\SanitizeRuleInterface;
7
8
class SanitizeSpec extends AbstractSpec
9
{
10
    /**
11
     * Value to use when inserting
12
     *
13
     * @var mixed
14
     */
15
    protected $blankValue;
16
17
    /**
18
     * Failure mode for the rule.
19
     *
20
     * @var string
21
     */
22
    protected $failureMode = 'HARD_FAILURE';
23
24
    /**
25
     * Invokes the rule the spec is configured for.
26
     *
27
     * @param object $subject
28
     *
29
     * @return bool
30
     */
31 24
    public function __invoke($subject): bool
32
    {
33 24
        if (!$this->subjectFieldIsBlank($subject)) {
34 9
            return parent::__invoke($subject);
35
        }
36
37 15
        if (!$this->allowBlanks) {
38 9
            return false;
39
        }
40
41 6
        $subject->{$this->field} = $this->blankValue;
42
43 6
        return true;
44
    }
45
46
    /**
47
     * Set the Sanitize rule to be used.
48
     *
49
     * @param SanitizeRuleInterface $rule
50
     *
51
     * @return SanitizeSpec
52
     */
53 21
    public function to(SanitizeRuleInterface $rule): self
54
    {
55 21
        $this->rule = $rule;
56 21
        $this->ruleClass = get_class($rule);
57
58 21
        return $this;
59
    }
60
61
    /**
62
     * Sets the blank value to use.
63
     *
64
     * Defaults to null.
65
     *
66
     * @param $blankValue
67
     *
68
     * @return SanitizeSpec
69
     */
70 9
    public function usingBlank($blankValue = null): self
71
    {
72 9
        $this->allowBlanks = true;
73 9
        $this->blankValue = $blankValue;
74
75 9
        return $this;
76
    }
77
78
    /**
79
     * Returns the default failure message for this rule specification.
80
     *
81
     * @return string
82
     */
83 6
    protected function getDefaultMessage(): string
84
    {
85 6
        $message = $this->field . ' should have sanitized to ';
86
87 6
        if ($this->allowBlanks) {
88
            $message .= 'blank or ';
89
        }
90
91 6
        return "{$message}" . parent::getDefaultMessage();
92
    }
93
}
94