Passed
Push — master ( 26860c...a0cc9c )
by Arnold
02:11
created

ApplicationEnv   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 60
rs 10
c 0
b 0
f 0
wmc 8

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-environements separated by a dot.
10
 */
11
class ApplicationEnv
12
{
13
    /**
14
     * @var string
15
     */
16
    protected $env;
17
18
    /**
19
     * ApplicationEnv constructor.
20
     *
21
     * @param string $env
22
     */
23
    public function __construct(string $env)
24
    {
25
        $this->env = $env;
26
    }
27
28
    /**
29
     * Cast object to a string
30
     *
31
     * @return string
32
     */
33
    public function __toString(): string
34
    {
35
        return $this->env;
36
    }
37
38
39
    /**
40
     * Check if environment matches or is a parent.
41
     *
42
     * @param string $env
43
     * @return bool
44
     */
45
    public function is(string $env): bool
46
    {
47
        return $this->env === $env || str_starts_with($this->env, "$env.");
48
    }
49
50
    /**
51
     * Traverse through each level of the application env.
52
     *
53
     * @param int           $from
54
     * @param int|null      $to
55
     * @param callable|null $callback
56
     * @return array
57
     */
58
    public function getLevels(int $from = 1, ?int $to = null, ?callable $callback = null): array
0 ignored issues
show
Coding Style introduced by
Incorrect spacing between argument "$from" and equals sign; expected 0 but found 1
Loading history...
Coding Style introduced by
Incorrect spacing between default value and equals sign for argument "$from"; expected 0 but found 1
Loading history...
Coding Style introduced by
Incorrect spacing between argument "$to" and equals sign; expected 0 but found 1
Loading history...
Coding Style introduced by
Incorrect spacing between default value and equals sign for argument "$to"; expected 0 but found 1
Loading history...
Coding Style introduced by
Incorrect spacing between argument "$callback" and equals sign; expected 0 but found 1
Loading history...
Coding Style introduced by
Incorrect spacing between default value and equals sign for argument "$callback"; expected 0 but found 1
Loading history...
59
    {
60
        $parts = explode('.', $this->env);
61
        $n = isset($to) ? min(count($parts), $to) : count($parts);
62
63
        $levels = [];
64
65
        for ($i = $from; $i <= $n; $i++) {
66
            $level = join('.', array_slice($parts, 0, $i));
67
            $levels[] = isset($callback) ? $callback($level) : $level;
68
        }
69
70
        return $levels;
71
    }
72
}
73