Completed
Push — 7.5 ( 473879...5be6c9 )
by
unknown
32:31 queued 12:05
created

BehatSiteAccessInitializer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
5
 * @license For full copyright and license information view LICENSE file distributed with this source code.
6
 */
7
declare(strict_types=1);
8
9
namespace eZ\Bundle\PlatformBehatBundle\Initializer;
10
11
use Behat\Behat\EventDispatcher\Event\ExampleTested;
12
use Behat\Behat\EventDispatcher\Event\ScenarioTested;
13
use eZ\Publish\Core\MVC\Symfony\Event\ScopeChangeEvent;
14
use eZ\Publish\Core\MVC\Symfony\MVCEvents;
15
use eZ\Publish\Core\MVC\Symfony\SiteAccess;
16
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
17
use Symfony\Component\HttpKernel\KernelInterface;
18
19
final class BehatSiteAccessInitializer implements EventSubscriberInterface
20
{
21
    private const EZPLATFORM_SITEACCESS_ENV_VAR = 'EZPLATFORM_SITEACCESS';
22
    private const DEFAULT_SITEACCESS_PARAMETER = 'ezpublish.siteaccess.default';
23
    private const EVENT_DISPATCHER_SERVICE_ID = 'event_dispatcher';
24
25
    /** @var \Symfony\Component\HttpKernel\KernelInterface */
26
    private $kernel;
27
28
    public function __construct(KernelInterface $kernel)
29
    {
30
        $this->kernel = $kernel;
31
    }
32
33
    public static function getSubscribedEvents(): array
34
    {
35
        return [
36
            ScenarioTested::BEFORE => ['setSiteAccess'],
37
            ExampleTested::BEFORE => ['setSiteAccess'],
38
        ];
39
    }
40
41
    public function setSiteAccess(): void
42
    {
43
        $siteAccess = $this->getSiteAccess();
44
        // We cannot inject EventDispatcher directly because it would be the one used by Behat internally
45
        // We need to get the one made available by Symfony2Extension
46
        $this->kernel
47
            ->getContainer()
48
            ->get(self::EVENT_DISPATCHER_SERVICE_ID)
49
            ->dispatch(MVCEvents::CONFIG_SCOPE_CHANGE, new ScopeChangeEvent($siteAccess));
50
    }
51
52
    private function getSiteAccess(): SiteAccess
53
    {
54
        $siteAccessFromEnvVar = getenv(self::EZPLATFORM_SITEACCESS_ENV_VAR);
55
        $defaultSiteAccess = $this->kernel->getContainer()->getParameter(self::DEFAULT_SITEACCESS_PARAMETER);
56
57
        $siteAccessName = $siteAccessFromEnvVar !== false ? $siteAccessFromEnvVar : $defaultSiteAccess;
58
59
        return new SiteAccess($siteAccessName, 'cli');
60
    }
61
}
62