ApplicationEnv::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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