EnvConfiguration::__construct()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 9.8666
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 4
1
<?php
2
3
namespace Equip\Configuration;
4
5
use Auryn\Injector;
6
use Equip\Env;
7
use Equip\Exception\EnvException;
8
use josegonzalez\Dotenv\Loader;
9
10
class EnvConfiguration implements ConfigurationInterface
11
{
12
    /**
13
     * @var string
14
     */
15
    private $envfile;
16
17
    /**
18
     * @param string $envfile
19
     *
20
     * @throws EnvException If a missing or unreadable file is specified
21
     */
22 3
    public function __construct($envfile = null)
23
    {
24 3
        if (empty($envfile)) {
25 2
            $envfile = $this->detectEnvFile();
26 1
        }
27
28 2
        if (!is_file($envfile) || !is_readable($envfile)) {
29 1
            throw EnvException::invalidFile($envfile);
30
        }
31
32 1
        $this->envfile = $envfile;
33 1
    }
34
35
    /**
36
     * @inheritDoc
37
     */
38 1
    public function apply(Injector $injector)
39
    {
40 1
        $injector->define(Loader::class, [
41 1
            ':filepaths' => $this->envfile,
42 1
        ]);
43
44 1
        $injector->share(Env::class);
45
46 1
        $injector->prepare(Env::class, function (Env $env, Injector $injector) {
47 1
            $loader = $injector->make(Loader::class);
48 1
            $values = $loader->parse()->toArray();
49 1
            return $env->withValues($values);
50 1
        });
51 1
    }
52
53
    /**
54
     * Find a .env file by traversing up the filesystem
55
     *
56
     * @return string
57
     *
58
     * @throws EnvException If no file is found
59
     */
60 2
    private function detectEnvFile()
61
    {
62 2
        $env = DIRECTORY_SEPARATOR . '.env';
63 2
        $dir = dirname(dirname(__DIR__));
64
65
        do {
66 2
            if (is_file($dir . $env)) {
67 1
                return $dir . $env;
68
            }
69 2
            $dir = dirname($dir);
70 2
        } while (is_readable($dir) && dirname($dir) !== $dir);
71
72 1
        throw EnvException::detectionFailed();
73
    }
74
}
75