Passed
Pull Request — master (#240)
by Dmitriy
03:45
created

ValidationContext::setParameter()   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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Yiisoft\Arrays\ArrayHelper;
8
9
/**
10
 * Validation context that rule may take into account when performing validation.
11
 */
12
final class ValidationContext
13
{
14
    /**
15
     * @param DataSetInterface|null $dataSet Data set the attribute belongs to. Null if a single value is validated.
16
     * @param string|null $attribute Validated attribute name. Null if a single value is validated.
17
     * @param array $parameters Arbitrary parameters.
18
     */
19 534
    public function __construct(
20
        private ?DataSetInterface $dataSet,
21
        private ?string $attribute = null,
22
        private array $parameters = [],
23
    ) {
24
    }
25
26
    /**
27
     * @return DataSetInterface|null Data set the attribute belongs to. Null if a single value is validated.
28
     */
29 2
    public function getDataSet(): ?DataSetInterface
30
    {
31 2
        return $this->dataSet;
32
    }
33
34
    /**
35
     * @return string|null Validated attribute name. Null if a single value is validated.
36
     */
37 333
    public function getAttribute(): ?string
38
    {
39 333
        return $this->attribute;
40
    }
41
42
    /**
43
     * @param string|null $attribute Validated attribute name. Null if a single value is validated.
44
     *
45
     * @return self
46
     */
47 15
    public function withAttribute(?string $attribute): self
48
    {
49 15
        $new = clone $this;
50 15
        $new->attribute = $attribute;
51 15
        return $new;
52
    }
53
54
    /**
55
     * @return array Arbitrary parameters.
56
     */
57 3
    public function getParameters(): array
58
    {
59 3
        return $this->parameters;
60
    }
61
62
    /**
63
     * Get named parameter.
64
     *
65
     * @param string $key Parameter name.
66
     * @param mixed $default Default value to return in case parameter with a given name does not exist.
67
     *
68
     * @return mixed Parameter value.
69
     *
70
     * @see ArrayHelper::getValue()
71
     */
72 2
    public function getParameter(string $key, mixed $default = null): mixed
73
    {
74 2
        return ArrayHelper::getValue($this->parameters, $key, $default);
75
    }
76
77 26
    public function setParameter(string $key, $value): void
78
    {
79 26
        $this->parameters[$key] = $value;
80
    }
81
}
82