Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
89.47% covered (warning)
89.47%
17 / 19
85.71% covered (warning)
85.71%
6 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
Env
89.47% covered (warning)
89.47%
17 / 19
85.71% covered (warning)
85.71%
6 / 7
8.07
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 load
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 require
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 validate
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 string
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 bool
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 int
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Cosray\Config;
6
7use Dotenv\Dotenv;
8
9use function Cosray\env;
10
11final class Env
12{
13    private function __construct(
14        private readonly Dotenv $dotenv,
15    ) {}
16
17    public static function load(string $root): self
18    {
19        $dotenv = Dotenv::createImmutable($root);
20        $dotenv->safeLoad();
21
22        return new self($dotenv);
23    }
24
25    /** @param non-empty-string|list<non-empty-string> $variables */
26    public function require(string|array $variables): void
27    {
28        $this->dotenv->required($variables);
29    }
30
31    public function validate(): void
32    {
33        $this->dotenv->ifPresent([
34            'APP_DEBUG',
35            'SITE_SESSION_ENABLED',
36            'SESSION_COOKIE_SECURE',
37        ])->isBoolean();
38
39        $this->dotenv->ifPresent([
40            'AUTH_REMEMBER_LIFETIME',
41            'SESSION_COOKIE_LIFETIME',
42            'SESSION_IDLE_TIMEOUT',
43        ])->isInteger();
44    }
45
46    public function string(string $key, ?string $default = null): ?string
47    {
48        $value = env($key, $default);
49
50        return $value === null ? null : (string) $value;
51    }
52
53    public function bool(string $key, bool $default): bool
54    {
55        return filter_var(env($key, $default), FILTER_VALIDATE_BOOL);
56    }
57
58    public function int(string $key, int $default): int
59    {
60        return (int) env($key, $default);
61    }
62}