Passed
Push — master ( 9aef17...9e5266 )
by Gabriel
05:26
created

HasConstraintTrait::setContraintName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace ByTIC\MediaLibrary\Validation\Constraints\Traits;
4
5
use ByTIC\MediaLibrary\Validation\Constraints\AbstractConstraint;
6
use ByTIC\MediaLibrary\Validation\Validators\AbstractValidator;
7
8
/**
9
 * Trait HasValidatorTrait.
10
 */
11
trait HasConstraintTrait
12
{
13
    /**
14
     * @var null|AbstractConstraint
15
     */
16
    protected $constraint = null;
17
18
    /**
19
     * @var string
20
     */
21
    protected $contraintName = null;
22
23
    /**
24
     * @return AbstractConstraint|null
25
     */
26 3
    public function getConstraint()
27
    {
28 3
        if ($this->constraint === null) {
29 3
            $this->initConstraint();
30
        }
31
32 3
        return $this->constraint;
33
    }
34
35
    /**
36
     * @param AbstractConstraint|null $constraint
37
     */
38 3
    public function setConstraint($constraint)
39
    {
40 3
        $this->constraint = $constraint;
41 3
    }
42
43 3
    protected function initConstraint()
44
    {
45 3
        $constraint = $this->generateConstraint();
46 3
        $this->setConstraint($constraint);
47 3
    }
48
49
    /**
50
     * @return AbstractConstraint
51
     */
52 3
    protected function generateConstraint()
53
    {
54 3
        $constraint = $this->newConstraint();
55 3
        $this->hydrateConstraint($constraint);
56
57 3
        return $constraint;
58
    }
59
60
    /**
61
     * @return AbstractConstraint
62
     */
63 3
    protected function newConstraint()
64
    {
65 3
        $class = $this->getValidator()->getConstraintClassName();
66
67 3
        return new $class();
68
    }
69
70
    /**
71
     * @return mixed
72
     */
73 3
    public function getContraintName()
74
    {
75 3
        return $this->contraintName;
76
    }
77
78
    /**
79
     * @param string $contraintName
80
     */
81 12
    public function setContraintName(string $contraintName)
82
    {
83 12
        $this->contraintName = $contraintName;
84 12
    }
85
86
    /**
87
     * @return AbstractValidator
88
     */
89
    abstract protected function getValidator();
90
91
    /**
92
     * @param AbstractConstraint $constraint
93
     */
94 3
    protected function hydrateConstraint($constraint)
95
    {
96 3
        $contraintName = $this->getContraintName();
97 3
        if ($contraintName) {
98 3
            $constraint->setName($contraintName);
99
        }
100 3
        $constraint->init();
101 3
    }
102
}
103