Failed Conditions
Push — feature/stepLogger ( 5a6073 )
by Yo
03:03
created

BehatContextSubscriberInitializer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 52.94%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 50
ccs 9
cts 17
cp 0.5294
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A initializeContext() 0 11 2
A getSubscribedEvents() 0 4 1
A clearBehatContextSubscriber() 0 7 2
1
<?php
2
namespace Yoanm\Behat3SymfonyExtension\Context\Initializer;
3
4
use Behat\Behat\Context\Context;
5
use Behat\Behat\Context\Initializer\ContextInitializer;
6
use Behat\Behat\EventDispatcher\Event\FeatureTested;
7
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
8
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
use Yoanm\Behat3SymfonyExtension\Context\BehatContextSubscriberInterface;
10
11
/**
12
 * Class BehatContextSubscriberInitializer
13
 */
14
class BehatContextSubscriberInitializer implements ContextInitializer, EventSubscriberInterface
15
{
16
    /** @var EventDispatcherInterface */
17
    private $behatEventDispatcher;
18
    /** @var BehatContextSubscriberInterface[] */
19
    private $registeredContextList = [];
20
21
22
    /**
23
     * @param EventDispatcherInterface $behatEventDispatcher
24
     */
25 2
    public function __construct(EventDispatcherInterface $behatEventDispatcher)
26
    {
27 2
        $this->behatEventDispatcher = $behatEventDispatcher;
28 2
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 2
    public function initializeContext(Context $context)
34
    {
35 2
        if (!$context instanceof BehatContextSubscriberInterface) {
36 1
            return;
37
        }
38
        // This method is called before each scenario/example, so context is probably already registered
39
        // To avoid any problem, keep a trace of registered context and remove it at feature end
40
        // (See clearBehatContextSubscriber method)
41 1
        $this->registeredContextList[] = $context;
42 1
        $this->behatEventDispatcher->addSubscriber($context);
43 1
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public static function getSubscribedEvents()
49
    {
50
        return [FeatureTested::AFTER => 'clearBehatContextSubscriber'];
51
    }
52
53
    /**
54
     * Clear contexts subscriber after each feature
55
     */
56
    public function clearBehatContextSubscriber()
57
    {
58
        foreach ($this->registeredContextList as $context) {
59
            $this->behatEventDispatcher->removeSubscriber($context);
60
        }
61
        $this->registeredContextList = [];
62
    }
63
}
64