ApplicationEnv   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 12
c 1
b 0
f 0
dl 0
loc 47
ccs 14
cts 14
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getLevels() 0 13 4
A is() 0 3 2
A __construct() 0 3 1
A __toString() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny;
6
7
/**
8
 * Logic around APPLICATION_ENV environment variable
9
 * Supports sub-environments separated by a dot.
10
 */
11
class ApplicationEnv
12
{
13
    protected string $env;
14
15
    /**
16
     * ApplicationEnv constructor.
17
     */
18 12
    public function __construct(string $env)
19
    {
20 12
        $this->env = $env;
21
    }
22
23
    /**
24
     * Cast object to a string
25
     */
26 1
    public function __toString(): string
27
    {
28 1
        return $this->env;
29
    }
30
31
32
    /**
33
     * Check if environment matches or is a parent.
34
     */
35 1
    public function is(string $env): bool
36
    {
37 1
        return $this->env === $env || str_starts_with($this->env, "$env.");
38
    }
39
40
    /**
41
     * Traverse through each level of the application env.
42
     *
43
     * @return array<mixed>
44
     */
45 10
    public function getLevels(int $from = 1, ?int $to = null, ?callable $callback = null): array
46
    {
47 10
        $parts = explode('.', $this->env);
48 10
        $n = isset($to) ? min(count($parts), $to) : count($parts);
49
50 10
        $levels = [];
51
52 10
        for ($i = $from; $i <= $n; $i++) {
53 10
            $level = join('.', array_slice($parts, 0, $i));
54 10
            $levels[] = isset($callback) ? $callback($level) : $level;
55
        }
56
57 10
        return $levels;
58
    }
59
}
60