Transition::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 4
dl 0
loc 6
ccs 5
cts 5
cp 1
crap 2
rs 10
1
<?php
2
/**
3
 * @author: RunnerLee
4
 * @email: [email protected]
5
 * @time: 2018-02
6
 */
7
8
namespace Runner\Heshen;
9
10
use Runner\Heshen\Contracts\StatefulInterface;
11
12
class Transition
13
{
14
    /**
15
     * @var string
16
     */
17
    protected $name;
18
19
    /**
20
     * @var State[]
21
     */
22
    protected $fromStates;
23
24
    /**
25
     * @var State
26
     */
27
    protected $toState;
28
29
    /**
30
     * @var callable|null
31
     */
32
    protected $checker;
33
34
    /**
35
     * Transition constructor.
36
     *
37
     * @param string      $name
38
     * @param array|State $from
39
     * @param State       $to
40
     * @param callable    $checker
41
     */
42 12
    public function __construct(string $name, $from, State $to, $checker = null)
43
    {
44 12
        $this->name = $name;
45 12
        $this->fromStates = !is_array($from) ? [$from] : $from;
46 12
        $this->toState = $to;
47 12
        $this->checker = $checker;
48 12
    }
49
50
    /**
51
     * @return State[]
52
     */
53 2
    public function getFromStates(): array
54
    {
55 2
        return $this->fromStates;
56
    }
57
58
    /**
59
     * @return State
60
     */
61 4
    public function getToState(): State
62
    {
63 4
        return $this->toState;
64
    }
65
66
    /**
67
     * @param StatefulInterface $stateful
68
     * @param array             $parameters
69
     *
70
     * @return bool
71
     */
72 5
    public function can(StatefulInterface $stateful, array $parameters = []): bool
73
    {
74 5
        foreach ($this->fromStates as $state) {
75 5
            if ($state->getName() === $stateful->getState()) {
76 4
                if (!is_null($this->checker) && !(bool) call_user_func($this->checker, $stateful, $parameters)) {
77 1
                    return false;
78
                }
79
80 5
                return true;
81
            }
82
        }
83
84 4
        return false;
85
    }
86
}
87