WhenTrait   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 2
eloc 5
dl 0
loc 34
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A when() 0 5 1
A getWhen() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule\Trait;
6
7
use Closure;
8
use Yiisoft\Validator\WhenInterface;
9
10
/**
11
 * An implementation for {@see WhenInterface} intended to be included in rules. Requires an additional private class
12
 * property `$when`. In package rules it's `null` by default:
13
 *
14
 * ```php
15 27
 * public function __construct(
16
 *     // ...
17 27
 *     private Closure|null $when = null
18 27
 *     // ...
19 27
 * ) {
20
 * }
21
 * ```
22
 *
23
 * @psalm-import-type WhenType from WhenInterface
24
 */
25 811
trait WhenTrait
26
{
27 811
    /**
28
     * An immutable setter to change `$when` property.
29
     *
30
     * @psalm-param WhenType $value
31
     *
32
     * @param Closure|null $value A new value:
33
     *
34
     * - `null` - always apply the validation.
35
     * - `callable` - apply the validation depending on a return value: `true` - apply, `false` - do not apply.
36
     *
37
     * @return $this The new instance with a changed value.
38
     */
39
    public function when(Closure|null $value): static
40
    {
41
        $new = clone $this;
42
        $new->when = $value;
0 ignored issues
show
Bug Best Practice introduced by
The property when does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
43
        return $new;
44
    }
45
46
    /**
47
     * A getter for `$when` property.
48
     *
49
     * @psalm-return WhenType
50
     *
51
     * @return Closure|null Current value:
52
     *
53
     * - `null` - always apply the validation.
54
     * - `callable` - apply the validation depending on a return value: `true` - apply, `false` - do not apply.
55
     */
56
    public function getWhen(): Closure|null
57
    {
58
        return $this->when;
59
    }
60
}
61