Completed
Pull Request — master (#5)
by Dmitriy
05:16
created

DotEnvFileReaderAdapter::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 8
ccs 5
cts 6
cp 0.8333
crap 2.0185
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lamoda\MultiEnv\FileReader;
6
7
use Lamoda\MultiEnv\FileReader\Exception\EnvFileReaderException;
8
use Lamoda\MultiEnv\FileReader\FileNameResolver\FileNameResolverInterface;
9
use Lamoda\MultiEnv\FileReader\PathResolver\PathResolverInterface;
10
use Lamoda\MultiEnv\Model\HostId;
11
12
final class DotEnvFileReaderAdapter implements EnvFileReaderInterface
13
{
14
    /**
15
     * @var PathResolverInterface
16
     */
17
    private $pathResolver;
18
19
    /**
20
     * @var FileNameResolverInterface
21
     */
22
    private $fileNameResolver;
23
24
    /**
25
     * @var bool
26
     */
27
    private $isEnvFileAlreadyLoaded;
28
29 8
    public function __construct(PathResolverInterface $pathResolver, FileNameResolverInterface $fileNameResolver)
30
    {
31 8
        if (!class_exists(\Dotenv\Dotenv::class)) {
32
            throw EnvFileReaderException::becauseAdapterCanNotBeCreated(__CLASS__, \Dotenv\Dotenv::class);
33
        }
34 8
        $this->pathResolver = $pathResolver;
35 8
        $this->fileNameResolver = $fileNameResolver;
36 8
        $this->isEnvFileAlreadyLoaded = false;
37 8
    }
38
39 14
    public function readEnvFile(HostId $hostId): void
40
    {
41 14
        if ($this->isEnvFileAlreadyLoaded) {
42
            return;
43
        }
44
45
        try {
46 14
            $dotEnv = \Dotenv\Dotenv::create(
47 14
                $this->pathResolver->resolvePathToEnvFile($hostId),
48 14
                $this->fileNameResolver->resolveEnvFileName($hostId)
49
            );
50 14
            $dotEnv->overload();
51 13
            $this->isEnvFileAlreadyLoaded = true;
52 1
        } catch (\Dotenv\Exception\ExceptionInterface $exception) {
53 1
            throw EnvFileReaderException::becauseEnvFileCanNotBeProcessed($exception);
54
        }
55 13
    }
56
}
57