Completed
Pull Request — master (#36)
by Robert
08:59 queued 05:11
created

PhpDotEnv::__invoke()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 3
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Psr\Http\Message\ServerRequestInterface;
7
8
/**
9
 * Middleware to load a .env into PHP Environment Variables
10
 *
11
 * @author Robert Schönthal <[email protected]>
12
 */
13
class PhpDotEnv
14
{
15
    /**
16
     * @var string
17
     */
18
    private $dir;
19
    /**
20
     * @var string
21
     */
22
    private $filename;
23
24
    public function __construct($dir, $filename = '.env')
25
    {
26
        $this->dir = $dir;
27
        $this->filename = $filename;
28
    }
29
30
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
31
    {
32
        $this->loadEnvironment();
33
34
        return $next($request, $response, $next);
35
    }
36
37
    private function loadEnvironment()
38
    {
39
        if (!file_exists(realpath($this->dir) . '/' . $this->filename)) {
40
            return false;
41
        }
42
43
        if (class_exists('Dotenv\Dotenv')) { //2.x branch
44
            $dotenv = new \Dotenv\Dotenv($this->dir, $this->filename);
45
            $dotenv->load();
46
47
            return true;
48
        } elseif (class_exists('DotEnv')) { //1.x branch
49
            \Dotenv::load($this->dir, $this->filename);
50
51
            return true;
52
        }
53
54
        throw new \RuntimeException('no suitable .env loader found');
55
    }
56
}
57