Skip to content

Commit e2964f4

Browse files
author
Greg Bowler
authored
Set environment variables on sub-process (#49)
* test: fix changed process execution * test: upgrade phpunit * test: implement mess detector and code sniffer * ci: upgrade ci workflows * ci: use pcntl * ci: php 8.1 compatibility * feature: set environment variables closes #239 * test: assert multiple environment variables can be set
1 parent 3bbdf3e commit e2964f4

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

src/Process.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ class Process {
1616
/** @var array<string, mixed> */
1717
protected array $status;
1818
protected bool $isBlocking = false;
19+
/** @var array<string, string> */
20+
protected array $env = [];
1921

2022
public function __construct(string...$command) {
2123
$this->command = $command;
@@ -31,6 +33,10 @@ public function setExecCwd(string $cwd):void {
3133
$this->cwd = $cwd;
3234
}
3335

36+
public function setEnv(string $key, string $value):void {
37+
$this->env[$key] = $value;
38+
}
39+
3440
/**
3541
* Runs the command in a concurrent thread.
3642
* Sets the input, output and errors streams.
@@ -54,7 +60,7 @@ public function exec():void {
5460
$this->command,
5561
$descriptor,
5662
$this->pipes,
57-
// env_vars: $this->env,
63+
env_vars: $this->env,
5864
);
5965
if(!$this->process) {
6066
throw new CommandNotFoundException($this->command[0]);

test/phpunit/ProcessTest.php

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,4 +163,22 @@ public function testExecBlocking() {
163163
$sut->exec();
164164
self::assertFalse($sut->isRunning());
165165
}
166-
}
166+
167+
public function testSetEnv() {
168+
$sut = new Process("printenv");
169+
$sut->setEnv("NAME", "PHPUnit");
170+
$sut->exec();
171+
$output = $sut->getOutput();
172+
self::assertStringContainsString("NAME=PHPUnit\n", $output);
173+
}
174+
175+
public function testSetEnv_multiple() {
176+
$sut = new Process("printenv");
177+
$sut->setEnv("NAME", "PHPUnit");
178+
$sut->setEnv("TEST", "setEnv");
179+
$sut->exec();
180+
$output = $sut->getOutput();
181+
self::assertStringContainsString("TEST=setEnv\n", $output);
182+
self::assertStringContainsString("NAME=PHPUnit\n", $output);
183+
}
184+
}

0 commit comments

Comments
 (0)