Completed
Push — master ( 923dd6...18a39e )
by Oliver
02:44
created

WeightTransition   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 91.3%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 8
c 1
b 0
f 1
lcom 1
cbo 3
dl 0
loc 49
ccs 21
cts 23
cp 0.913
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
B selectTransition() 0 19 6
1
<?php
2
3
namespace Metabor\Statemachine\Factory\TransitionSelector;
4
5
use MetaborStd\Statemachine\Factory\TransitionSelectorInterface;
6
use MetaborStd\WeightedInterface;
7
8
/**
9
 * @author otischlinger
10
 */
11
class WeightTransition implements TransitionSelectorInterface
12
{
13
    /**
14
     * @var TransitionSelectorInterface
15
     */
16
    protected $innerSelector;
17
18
    /**
19
     * @var float
20
     */
21
    protected $epsilon;
22
23
    /**
24
     * @param TransitionSelectorInterface|null $innerSelector
25
     * @param float $epsilon
26
     */
27 2
    public function __construct(TransitionSelectorInterface $innerSelector = null, $epsilon = 0.001)
28
    {
29 2
        if ($innerSelector) {
30
            $this->innerSelector = $innerSelector;
31
        } else {
32 2
            $this->innerSelector = new OneOrNoneActiveTransition();
33
        }
34 2
        $this->epsilon = $epsilon;
35 2
    }
36
37
    /**
38
     * @see \MetaborStd\Statemachine\Factory\TransitionSelectorInterface::selectTransition()
39
     */
40 2
    public function selectTransition(\Traversable $transitions)
41
    {
42 2
        $bestTransitions = array();
43 2
        $bestWeight = null;
44 2
        foreach ($transitions as $transition) {
45 2
            if ($transition instanceof WeightedInterface) {
46 2
                $weight = $transition->getWeight();
47 2
                $diff = ($weight - $bestWeight);
48 2
                if (($bestWeight === null) || ($diff >= $this->epsilon)) {
49 2
                    $bestWeight = $weight;
50 2
                    $bestTransitions = array($transition);
51 2
                } elseif (abs($diff) < $this->epsilon) {
52 1
                    $bestTransitions[] = $transition;
53 1
                }
54 2
            }
55 2
        }
56
57 2
        return $this->innerSelector->selectTransition(new \ArrayIterator($bestTransitions));
58
    }
59
}
60