1 | <?php declare(strict_types=1); |
||
2 | |||
3 | namespace Cocotte\Shell; |
||
4 | |||
5 | use Assert\Assertion; |
||
6 | |||
7 | final class DefaultEnv implements Env |
||
8 | { |
||
9 | |||
10 | public function put(string $name, string $value) |
||
11 | { |
||
12 | global $_SERVER; |
||
0 ignored issues
–
show
|
|||
13 | Assertion::true(putenv($name.'='.$value), "Could not put env with name '$name' and value '$value'."); |
||
14 | Assertion::same( |
||
15 | $value, |
||
16 | $retrieved = $this->get($name), |
||
17 | "Failed asserting that value '$value' for env with name '$name' has been preserved when putting it. ". |
||
18 | "Retrieved value was '$retrieved'." |
||
19 | ); |
||
20 | /** |
||
21 | * @see \Symfony\Component\Process\Process::getDefaultEnv |
||
22 | */ |
||
23 | $_SERVER[$name] = $value; |
||
24 | } |
||
25 | |||
26 | public function get(string $name, $default = null): ?string |
||
27 | { |
||
28 | $value = getenv($name); |
||
29 | if (false !== $value) { |
||
30 | return $value; |
||
31 | } |
||
32 | |||
33 | return $default; |
||
34 | } |
||
35 | |||
36 | public function unset(string $name) |
||
37 | { |
||
38 | global $_SERVER; |
||
0 ignored issues
–
show
Compatibility
Best Practice
introduced
by
Use of
global functionality is not recommended; it makes your code harder to test, and less reusable.
Instead of relying on 1. Pass all data via parametersfunction myFunction($a, $b) {
// Do something
}
2. Create a class that maintains your stateclass MyClass {
private $a;
private $b;
public function __construct($a, $b) {
$this->a = $a;
$this->b = $b;
}
public function myFunction() {
// Do something
}
}
![]() |
|||
39 | Assertion::true(putenv($name), "Could not unset env with name '$name'."); |
||
40 | Assertion::same( |
||
41 | null, |
||
42 | $retrieved = $this->get($name), |
||
43 | "Failed asserting that env with name '$name' has been unset. ". |
||
44 | "Retrieved value was '$retrieved'." |
||
45 | ); |
||
46 | /** |
||
47 | * @see \Symfony\Component\Process\Process::getDefaultEnv |
||
48 | */ |
||
49 | unset($_SERVER[$name]); |
||
50 | Assertion::keyNotExists( |
||
51 | $_SERVER, |
||
52 | $name, |
||
53 | "Failed asserting that env with name '$name' has been unset in global _SERVER." |
||
54 | ); |
||
55 | } |
||
56 | |||
57 | } |
||
58 |
Instead of relying on
global
state, we recommend one of these alternatives:1. Pass all data via parameters
2. Create a class that maintains your state