Magento2InitListener::initMagento()   B
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 33
rs 8.8571
cc 2
eloc 20
nc 2
nop 0
1
<?php
2
3
namespace Bex\Behat\Magento2InitExtension\Listener;
4
5
use Behat\Testwork\EventDispatcher\Event\SuiteTested;
6
use Bex\Behat\Magento2InitExtension\Fixtures\MagentoConfigManager;
7
use Bex\Behat\Magento2InitExtension\ServiceContainer\Config;
8
use Magento\Framework\App\Bootstrap;
9
use Magento\Framework\App\Filesystem\DirectoryList;
10
use Magento\Framework\App\ObjectManager;
11
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
12
13
final class Magento2InitListener implements EventSubscriberInterface
14
{
15
    /**
16
     * @var Config
17
     */
18
    private $config;
19
20
    /**
21
     * @var MagentoConfigManager
22
     */
23
    private $magentoConfigManager;
24
25
    /**
26
     * @param Config $config
27
     */
28
    public function __construct(Config $config)
29
    {
30
        $this->config = $config;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public static function getSubscribedEvents()
37
    {
38
        return [
39
            SuiteTested::BEFORE => 'initMagento',
40
            SuiteTested::AFTER => 'resetMagentoConfig'
41
        ];
42
    }
43
44
    public function initMagento()
45
    {
46
        $bootstrapPath = $this->config->getMagentoBootstrapPath();
47
48
        if (!file_exists($bootstrapPath)) {
49
            throw new \RuntimeException(sprintf("Magento's bootstrap file was not found at path '%s'", $bootstrapPath));
50
        }
51
52
        include $bootstrapPath;
53
54
        $params = $_SERVER;
55
56
        $params[Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS] = [
57
            DirectoryList::PUB => [DirectoryList::URL_PATH => ''],
58
            DirectoryList::MEDIA => [DirectoryList::URL_PATH => 'media'],
59
            DirectoryList::STATIC_VIEW => [DirectoryList::URL_PATH => 'static'],
60
            DirectoryList::UPLOAD => [DirectoryList::URL_PATH => 'media/upload'],
61
        ];
62
63
        putenv('BEHAT_RUNNING=true');
64
65
        $bootstrap = Bootstrap::create(BP, $params);
66
        $bootstrap->createApplication('Magento\Framework\App\Http');
67
        ObjectManager::getInstance();
68
69
        $this->magentoConfigManager = new MagentoConfigManager();
70
        $this->magentoConfigManager->changeConfigs($this->config->getRequiredMagentoConfig());
71
72
        // reinit magento to reload config
73
        $bootstrap = Bootstrap::create(BP, $params);
74
        $bootstrap->createApplication('Magento\Framework\App\Http');
75
        ObjectManager::getInstance();
76
    }
77
78
    public function resetMagentoConfig()
79
    {
80
        $this->magentoConfigManager->revertAllConfig();
81
    }
82
}
83