Completed
Branch master (c08b38)
by Oliver
03:58
created

OnEnterObserver::getStateMachineContext()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 8
cp 0
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
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
    public function __construct($eventName = self::DEFAULT_EVENT_NAME)
26
    {
27
        $this->eventName = $eventName;
28
    }
29
30
    /**
31
     * @see SplObserver::update()
32
     */
33
    public function update(\SplSubject $stateMachine)
34
    {
35
        if ($stateMachine instanceof StatemachineInterface && $stateMachine->getCurrentState()->hasEvent($this->eventName)) {
36
            if ($stateMachine instanceof Statemachine) {
37
                $autoreleaseLock = $stateMachine->isAutoreleaseLock();
38
                $stateMachine->setAutoreleaseLock(false);
39
                $stateMachine->triggerEvent($this->eventName, $stateMachine->getCurrentContext());
40
                $stateMachine->setAutoreleaseLock($autoreleaseLock);
41
            } else {
42
                $stateMachine->triggerEvent($this->eventName);
43
            }
44
        }
45
    }
46
}
47