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

getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 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