Backgroundable::BackgroundDispatcher()   B
last analyzed

Complexity

Conditions 7
Paths 8

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 19
rs 8.8333
cc 7
nc 8
nop 1
1
<?php
2
3
namespace Knp\FriendlyContexts\Dictionary;
4
5
use Behat\Behat\Hook\Scope\BeforeStepScope;
6
7
trait Backgroundable
8
{
9
    private $HOOK_BEFORE_BACKGROUND = 'BeforeBackground';
10
    private $HOOK_AFTER_BACKGROUND  = 'AfterBackground';
11
12
    private $inBackground = false;
13
    private $afterBackground = false;
14
15
    /**
16
     * @BeforeStep
17
     **/
18
    public function BackgroundDispatcher(BeforeStepScope $event)
19
    {
20
        $feature = $event->getFeature();
21
        $background = $feature->getBackground() ?: null;
22
        $steps = null === $background ? [] : $background->getSteps();
23
        $underBackground = in_array($event->getStep(), $steps);
24
25
        if (null === $background && false === $this->afterBackground) {
26
            $this->displachEvent($this->HOOK_BEFORE_BACKGROUND, $event);
27
            $this->displachEvent($this->HOOK_AFTER_BACKGROUND, $event);
28
            $this->afterBackground = true;
29
        } elseif ($underBackground !== $this->inBackground) {
30
            if (true === $underBackground) {
31
                $this->displachEvent($this->HOOK_BEFORE_BACKGROUND, $event);
32
            } else {
33
                $this->displachEvent($this->HOOK_AFTER_BACKGROUND, $event);
34
            }
35
36
            $this->inBackground = $underBackground;
37
        }
38
    }
39
40
    protected function displachEvent($name, $event)
41
    {
42
        $methods = $this->getHookMethodsByName($name);
43
44
        foreach ($methods as $method) {
45
            $this->$method($event);
46
        }
47
    }
48
49
    protected function getHookMethodsByName($name)
50
    {
51
        $methods = [];
52
        $rfl = new \ReflectionClass($this);
53
54
        foreach ($rfl->getMethods() as $method) {
55
            $comments = explode("\n", $method->getDocComment());
56
57
            $tags = [];
58
            foreach ($comments as $comment) {
59
                if (preg_match('/@(\w*)/', $comment, $tags)) {
60
                    if (in_array($name, $tags)) {
61
                        $methods[] = $method->name;
62
                    }
63
                }
64
            }
65
        }
66
67
        return array_unique($methods);
68
    }
69
}
70