ShopConfig::getDbDataFromEnv()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 9
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 11
ccs 0
cts 0
cp 0
crap 2
rs 9.9666
1
<?php
2
3
namespace Deployee\Plugins\ShopwareTasks\Shop;
4
5
use Symfony\Component\Dotenv\Dotenv;
6
use Enqueue\Dsn\Dsn;
7
8
class ShopConfig
9
{
10
    const BASE_ENV_FILE = '.env';
11
    const APP_ENV = 'APP_ENV';
12
    const DB_URL = 'DATABASE_URL';
13
14
    /**
15
     * @var string
16
     */
17
    private $configFilePath;
18
19
    /**
20
     * @var array
21
     */
22 2
    private $config;
23
24 2
    /**
25 2
     * ShopConfig constructor.
26
     * @param string $configFilePath
27
     */
28
    public function __construct(string $configFilePath)
29
    {
30
        $this->configFilePath = $configFilePath;
31 2
    }
32
33 2
    /**
34
     * @param string $id
35
     * @return mixed|null
36
     */
37
    public function get(string $id)
38
    {
39 2
        return $this->getConfig()[$id] ?? null;
40
    }
41 2
42 2
    /**
43 1
     * @return array
44
     */
45
    private function getConfig(): array
46 1
    {
47
        if ($this->config === null) {
48
            if (!is_file($this->configFilePath)) {
49 1
                throw new \InvalidArgumentException("Path to shopware config was not found or is invalid");
50
            }
51 1
52
            $appEnv = getenv(ShopConfig::APP_ENV);
53
            $dotenv = new Dotenv($appEnv);
54
            $envs = $dotenv->parse(file_get_contents($this->configFilePath));
55
56
            if (!$this->checkDatabaseUrlIsSet($envs))
57
            {
58
                throw new \InvalidArgumentException(
59
                    "env file does not contain the required DATABASE_URL param. env path = " . $this->configFilePath
60
                );
61
            }
62
63
            $this->config = $this->getDbDataFromEnv($envs);
64
        }
65
66
        return $this->config;
67
    }
68
69
    /**
70
     * @param array $envs
71
     * @return bool
72
     */
73
    private function checkDatabaseUrlIsSet(array $envs): bool
74
    {
75
        return array_key_exists(ShopConfig::DB_URL, $envs);
76
    }
77
78
    /**
79
     * @param array $envs
80
     * @return array
81
     */
82
    private function getDbDataFromEnv(array $envs): array
83
    {
84
        $dsn = Dsn::parse($envs[ShopConfig::DB_URL]);
85
        $dsn = $dsn[0]->toArray();
86
        return [
87
            'username' => $dsn['user'],
88
            'password' => $dsn['password'],
89
            'type' => $dsn['scheme'],
90
            'host' => $dsn['host'],
91
            'port' => $dsn['port'],
92
            'dbname' => str_replace('/', '', $dsn['path']),
93
        ];
94
    }
95
}