Completed
Push — master ( 15ba03...8dddee )
by Runner
23:37
created

Transition   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 89
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 89
rs 10
c 0
b 0
f 0
wmc 11

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getChecker() 0 3 1
A getToState() 0 3 1
A getName() 0 3 1
A __construct() 0 6 2
A getFromStates() 0 3 1
B can() 0 13 5
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 null|callable
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 null        $checker
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $checker is correct as it would always require null to be passed?
Loading history...
41
     */
42
    public function __construct(string $name, $from, State $to, $checker = null)
43
    {
44
        $this->name = $name;
45
        $this->fromStates = !is_array($from) ? [$from] : $from;
46
        $this->toState = $to;
47
        $this->checker = $checker;
48
    }
49
50
    /**
51
     * @return string
52
     */
53
    public function getName(): string
54
    {
55
        return $this->name;
56
    }
57
58
    /**
59
     * @return State[]
60
     */
61
    public function getFromStates(): array
62
    {
63
        return $this->fromStates;
64
    }
65
66
    /**
67
     * @return State
68
     */
69
    public function getToState(): State
70
    {
71
        return $this->toState;
72
    }
73
74
    /**
75
     * @return callable|null
76
     */
77
    public function getChecker()
78
    {
79
        return $this->checker;
80
    }
81
82
    /**
83
     * @param StatefulInterface $stateful
84
     * @param array             $parameters
85
     *
86
     * @return bool
87
     */
88
    public function can(StatefulInterface $stateful, array $parameters = []): bool
89
    {
90
        foreach ($this->fromStates as $state) {
91
            if ($state->getName() === $stateful->getState()) {
92
                if (!is_null($this->checker) && !(bool) call_user_func($this->checker, $stateful, $parameters)) {
93
                    return false;
94
                }
95
96
                return true;
97
            }
98
        }
99
100
        return false;
101
    }
102
}
103