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