Completed
Push — master ( 6d76a1...f81267 )
by Oliver
12s
created

OnEnterObserver::update()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 3
eloc 3
nc 2
nop 1
crap 3
1
<?php
2
3
namespace Metabor\Statemachine\Observer;
4
5
use Metabor\Statemachine\Statemachine;
6
use MetaborStd\Statemachine\StatemachineInterface;
7
8
/**
9
 * Triggers automatically an event if the status changes and the new status has it.
10
 *
11
 * @author otischlinger
12
 */
13
class OnEnterObserver implements \SplObserver
14
{
15
    const DEFAULT_EVENT_NAME = 'onEnter';
16
17
    /**
18
     * @var string
19
     */
20
    private $eventName;
21
22
    /**
23
     * @param string $eventName
24
     */
25 2
    public function __construct($eventName = self::DEFAULT_EVENT_NAME)
26
    {
27 2
        $this->eventName = $eventName;
28 2
    }
29
30
    /**
31
     * @see SplObserver::update()
32
     */
33 2
    public function update(\SplSubject $stateMachine)
34
    {
35 2
        if ($stateMachine instanceof StatemachineInterface && $stateMachine->getCurrentState()->hasEvent($this->eventName)) {
36 2
            $stateMachine->triggerEvent($this->eventName, $this->getStateMachineContext($stateMachine));
37 2
        }
38 2
    }
39
40
    /**
41
     * @param \SplSubject|StatemachineInterface|Statemachine $stateMachine
42
     * @return \ArrayAccess|null
43
     */
44 2
    private function getStateMachineContext($stateMachine)
45
    {
46 2
        $context = null;
47 2
        if ($stateMachine instanceof Statemachine) {
48 2
            $context = $stateMachine->getCurrentContext();
49 2
        }
50
51 2
        return $context;
52
    }
53
}
54