• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / utils / 42394424989

07 Nov 2026 05:03PM UTC coverage: 93.395% (-0.04%) from 93.439%
42394424989

Pull #346

github

web-flow
Merge 2dd7739ae into a3f9e75b5
Pull Request #346: More precise types

2121 of 2271 relevant lines covered (93.39%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.9
/src/Utils/Process.php
1
<?php declare(strict_types=1);
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace Nette\Utils;
9

10
use Nette;
11
use function is_resource, is_string, strlen;
12
use const PHP_VERSION_ID;
13

14

15
/**
16
 * Represents a process, which can be started and controlled (reading output, writing input, waiting for completion).
17
 */
18
final class Process
19
{
20
        private const PollInterval = 10_000;
21
        private const DefaultTimeout = 60;
22
        private const StdIn = 0;
23
        private const StdOut = 1;
24
        private const StdErr = 2;
25

26
        /** @var resource */
27
        private mixed $process;
28

29
        /** @var array<string, mixed>  result of proc_get_status() */
30
        private array $status = ['running' => true];
31

32
        /** @var resource */
33
        private mixed $inputPipe;
34

35
        /** @var array<int, resource|string[]>  pipe resources, or ['file', path, mode] descriptors for discarded output */
36
        private array $outputPipes = [];
37

38
        /** @var string[] */
39
        private array $outputBuffers = [];
40

41
        /** @var int[] Number of bytes already read from buffers. */
42
        private array $outputBufferOffsets = [];
43

44
        /** @var array<int, true> Output IDs whose target resource was supplied by the caller and must not be closed here. */
45
        private array $callerOutputs = [];
46

47
        /** @var array<int, true> Output IDs whose pipe is backed by a temporary file (Windows < 8.5 workaround). */
48
        private array $fileBackedOutputs = [];
49
        private float $startTime;
50
        private bool $detached = false;
51

52

53
        /**
54
         * Starts an executable with given arguments. Because the arguments are passed as an array, the shell is
55
         * never involved, so they need no escaping and there is no risk of shell injection.
56
         * @param  string         $executable Path to the executable binary.
57
         * @param  list<string>   $arguments  Arguments passed to the executable.
58
         * @param  string[]|null  $env        Environment variables or null to use the same environment as the current process.
59
         * @param  array<string, mixed>  $options  Options for proc_open(); on Windows the executable is launched directly, without cmd.exe.
60
         * @param  mixed          $stdin      Input: string, a readable resource (its content is copied to STDIN),
61
         *                                    a Process (its STDOUT is piped in), or null (STDIN stays open for writeStdInput()).
62
         * @param  mixed          $stdout     Output target: string filename, a writable resource backed by a real OS file descriptor
63
         *                                    (not php://memory etc.), false to discard, or null to capture into memory.
64
         * @param  mixed          $stderr     Error output target (same options as $stdout).
65
         * @param  string|null    $directory  Working directory.
66
         * @param  float|null     $timeout    Time limit in seconds, checked while waiting for or reading the process; null disables it.
67
         */
68
        public static function runExecutable(
69
                string $executable,
70
                array $arguments = [],
71
                ?array $env = null,
72
                array $options = [],
73
                mixed $stdin = '',
74
                mixed $stdout = null,
75
                mixed $stderr = null,
76
                ?string $directory = null,
77
                ?float $timeout = self::DefaultTimeout,
78
        ): self
79
        {
80
                return new self([$executable, ...$arguments], $env, $options, $directory, $stdin, $stdout, $stderr, $timeout);
1 ✔
81
        }
82

83

84
        /**
85
         * Starts a process from a command string interpreted by the shell (/bin/sh on POSIX, cmd.exe on Windows).
86
         * Because the shell parses the string, NEVER pass unescaped user input here - use runExecutable() for that.
87
         * @param  string         $command    Shell command to run.
88
         * @param  string[]|null  $env        Environment variables or null to use the same environment as the current process.
89
         * @param  array<string, mixed>  $options  Options for proc_open(), e.g. ['bypass_shell' => true] on Windows to skip cmd.exe.
90
         * @param  mixed          $stdin      Input: string, a readable resource (its content is copied to STDIN),
91
         *                                    a Process (its STDOUT is piped in), or null (STDIN stays open for writeStdInput()).
92
         * @param  mixed          $stdout     Output target: string filename, a writable resource backed by a real OS file descriptor
93
         *                                    (not php://memory etc.), false to discard, or null to capture into memory.
94
         * @param  mixed          $stderr     Error output target (same options as $stdout).
95
         * @param  string|null    $directory  Working directory.
96
         * @param  float|null     $timeout    Time limit in seconds, checked while waiting for or reading the process; null disables it.
97
         */
98
        public static function runCommand(
99
                string $command,
100
                ?array $env = null,
101
                array $options = [],
102
                mixed $stdin = '',
103
                mixed $stdout = null,
104
                mixed $stderr = null,
105
                ?string $directory = null,
106
                ?float $timeout = self::DefaultTimeout,
107
        ): self
108
        {
109
                return new self($command, $env, $options, $directory, $stdin, $stdout, $stderr, $timeout);
1 ✔
110
        }
111

112

113
        /**
114
         * @param  list<string>|string  $command
115
         * @param  array<string, string>|null  $env
116
         * @param  array<string, mixed>  $options
117
         */
118
        private function __construct(
1 ✔
119
                string|array $command,
120
                ?array $env,
121
                array $options,
122
                ?string $directory,
123
                mixed $stdin,
124
                mixed $stdout,
125
                mixed $stderr,
126
                private readonly ?float $timeout,
127
        ) {
128
                $descriptors = [
1 ✔
129
                        self::StdIn => $this->createInputDescriptor($stdin),
1 ✔
130
                        self::StdOut => $this->createOutputDescriptor(self::StdOut, $stdout),
1 ✔
131
                        self::StdErr => $this->createOutputDescriptor(self::StdErr, $stderr),
1 ✔
132
                ];
133

134
                $process = @proc_open($command, $descriptors, $pipes, $directory, $env, $options); // @ is escalated to exception
1 ✔
135
                if (!is_resource($process)) {
1 ✔
136
                        throw new ProcessFailedException('Failed to start process: ' . Helpers::getLastError());
×
137
                }
138

139
                $this->process = $process;
1 ✔
140
                [$this->inputPipe, $this->outputPipes[self::StdOut], $this->outputPipes[self::StdErr]] = $pipes + $descriptors;
1 ✔
141

142
                if ($stdin instanceof self) {
1 ✔
143
                        // the source process hands over its STDOUT pipe; from now on this process owns it
144
                        unset(
145
                                $stdin->outputBuffers[self::StdOut],
1 ✔
146
                                $stdin->outputBufferOffsets[self::StdOut],
1 ✔
147
                                $stdin->outputPipes[self::StdOut],
1 ✔
148
                        );
149
                }
150

151
                $this->writeInitialInput($stdin);
1 ✔
152
                $this->startTime = microtime(as_float: true);
1 ✔
153
        }
1 ✔
154

155

156
        public function __destruct()
157
        {
158
                if ($this->detached) {
1 ✔
159
                        return;
1 ✔
160
                }
161
                $this->outputBuffers = [];
1 ✔
162
                $this->terminate();
1 ✔
163
        }
1 ✔
164

165

166
        /**
167
         * Detaches the process: it keeps running in the background and is not terminated when the object
168
         * is destroyed. STDIN and output pipes are closed, so the output must not be captured in memory
169
         * (pass a file name, a resource or false as $stdout/$stderr). Only the destructor behavior changes:
170
         * wait() and getExitCode() still block ($timeout still applies) and terminate() still kills it.
171
         * On POSIX, a detached child that exits early stays a zombie until the script ends.
172
         */
173
        public function detach(): void
174
        {
175
                if ($this->outputBuffers !== []) {
1 ✔
176
                        throw new Nette\InvalidStateException('Cannot detach process: its output is captured in memory, pass a file name, a resource or false as $stdout/$stderr.');
1 ✔
177
                }
178
                $this->detached = true;
1 ✔
179
                $this->closeStdInput();
1 ✔
180
                $this->closeOutputPipes();
1 ✔
181
        }
1 ✔
182

183

184
        /**
185
         * Checks if the process is currently running.
186
         */
187
        public function isRunning(): bool
188
        {
189
                if (!$this->status['running']) {
1 ✔
190
                        return false;
1 ✔
191
                }
192

193
                $this->status = proc_get_status($this->process);
1 ✔
194
                if (!$this->status['running']) {
1 ✔
195
                        $this->close();
1 ✔
196
                }
197

198
                return $this->status['running'];
1 ✔
199
        }
200

201

202
        /**
203
         * Finishes the process by waiting for its completion. While waiting, the captured output is read
204
         * continuously and kept in memory; an optional callback is invoked with each new output/error chunk.
205
         *
206
         * @param  (\Closure(string, string): void)|null  $callback
207
         */
208
        public function wait(?\Closure $callback = null): void
209
        {
210
                while ($this->isRunning()) {
1 ✔
211
                        $this->enforceTimeout();
1 ✔
212
                        $this->drainPipes();
1 ✔
213
                        $this->dispatchCallback($callback);
1 ✔
214
                        usleep(self::PollInterval);
1 ✔
215
                }
216

217
                $this->dispatchCallback($callback);
1 ✔
218
        }
1 ✔
219

220

221
        /**
222
         * Reads any new data from the captured pipes into the buffers, so a process producing more output
223
         * than the OS pipe buffer holds does not block. With $final (process already finished) reads to EOF.
224
         */
225
        private function drainPipes(bool $final = false): void
226
        {
227
                foreach ([self::StdOut, self::StdErr] as $id) {
1 ✔
228
                        $this->readFromPipe($id, $final);
1 ✔
229
                }
230
        }
1 ✔
231

232

233
        /**
234
         * Terminates the running process if it is still running.
235
         */
236
        public function terminate(): void
237
        {
238
                if (!$this->isRunning()) {
1 ✔
239
                        return;
1 ✔
240
                } elseif (Helpers::IsWindows) {
1 ✔
241
                        exec("taskkill /F /T /PID {$this->getPid()} 2>&1");
×
242
                } else {
243
                        proc_terminate($this->process, 9); // 9 = SIGKILL: cannot be trapped, so the following proc_close() won't hang
1 ✔
244
                }
245
                $this->status['running'] = false;
1 ✔
246
                $this->close();
1 ✔
247
        }
1 ✔
248

249

250
        /**
251
         * Returns the process exit code. If the process is still running, waits until it finishes.
252
         */
253
        public function getExitCode(): int
254
        {
255
                $this->wait();
1 ✔
256
                return $this->status['exitcode'] ?? -1;
1 ✔
257
        }
258

259

260
        /**
261
         * Returns true if the process terminated with exit code 0.
262
         */
263
        public function isSuccess(): bool
264
        {
265
                return $this->getExitCode() === 0;
1 ✔
266
        }
267

268

269
        /**
270
         * Waits for the process to finish and throws ProcessFailedException if exit code is not zero.
271
         */
272
        public function ensureSuccess(): void
273
        {
274
                $code = $this->getExitCode();
1 ✔
275
                if ($code !== 0) {
1 ✔
276
                        throw new ProcessFailedException("Process failed with non-zero exit code: $code");
1 ✔
277
                }
278
        }
1 ✔
279

280

281
        /**
282
         * Returns the PID of the running process, or null if it is not running.
283
         */
284
        public function getPid(): ?int
285
        {
286
                return $this->isRunning() ? $this->status['pid'] : null;
1 ✔
287
        }
288

289

290
        /**
291
         * Waits for the process to finish and returns everything it wrote to STDOUT.
292
         */
293
        public function getStdOutput(): string
294
        {
295
                $this->wait();
1 ✔
296
                return $this->outputBuffers[self::StdOut] ?? throw new Nette\InvalidStateException('Cannot read output: it is not captured (it was redirected, discarded or piped).');
1 ✔
297
        }
298

299

300
        /**
301
         * Waits for the process to finish and returns everything it wrote to STDERR.
302
         */
303
        public function getStdError(): string
304
        {
305
                $this->wait();
1 ✔
306
                return $this->outputBuffers[self::StdErr] ?? throw new Nette\InvalidStateException('Cannot read output: it is not captured (it was redirected, discarded or piped).');
1 ✔
307
        }
308

309

310
        /**
311
         * Returns the STDOUT data produced since the previous consumeStdOutput() call.
312
         * To read everything incrementally, poll `while ($p->isRunning())` calling this, then call it once more
313
         * after the loop; that last call returns whatever the process wrote just before the loop noticed it had exited.
314
         */
315
        public function consumeStdOutput(): string
316
        {
317
                return $this->consumeBuffer(self::StdOut);
1 ✔
318
        }
319

320

321
        /**
322
         * Returns the STDERR data produced since the previous consumeStdError() call. See consumeStdOutput().
323
         */
324
        public function consumeStdError(): string
325
        {
326
                return $this->consumeBuffer(self::StdErr);
1 ✔
327
        }
328

329

330
        /**
331
         * Returns newly available data from the specified buffer and advances the read pointer.
332
         */
333
        private function consumeBuffer(int $id): string
334
        {
335
                if (!isset($this->outputBuffers[$id])) {
1 ✔
336
                        throw new Nette\InvalidStateException('Cannot read output: it is not captured (it was redirected, discarded or piped).');
1 ✔
337
                } elseif ($this->isRunning()) {
1 ✔
338
                        $this->enforceTimeout();
1 ✔
339
                        $this->readFromPipe($id);
1 ✔
340
                }
341
                return $this->extractNewData($id);
1 ✔
342
        }
343

344

345
        /**
346
         * Returns the buffered data not returned yet and advances the read pointer.
347
         */
348
        private function extractNewData(int $id): string
349
        {
350
                if (!isset($this->outputBuffers[$id])) {
1 ✔
351
                        return '';
1 ✔
352
                }
353
                $res = substr($this->outputBuffers[$id], $this->outputBufferOffsets[$id]);
1 ✔
354
                $this->outputBufferOffsets[$id] = strlen($this->outputBuffers[$id]);
1 ✔
355
                return $res;
1 ✔
356
        }
357

358

359
        /**
360
         * Writes data into the process' STDIN. If STDIN is closed, throws exception.
361
         */
362
        public function writeStdInput(string $string): void
363
        {
364
                if (!is_resource($this->inputPipe)) {
1 ✔
365
                        throw new Nette\InvalidStateException('Cannot write to process: STDIN pipe is closed');
1 ✔
366
                }
367
                $this->writeToPipe($string);
1 ✔
368
        }
1 ✔
369

370

371
        /**
372
         * Writes the whole string to STDIN, handling partial writes. Stops (and lets fwrite() warn) on a broken pipe,
373
         * i.e. when the process stopped reading its STDIN.
374
         */
375
        private function writeToPipe(string $string): void
376
        {
377
                $length = strlen($string);
1 ✔
378
                for ($written = 0; $written < $length; $written += $bytes) {
1 ✔
379
                        $bytes = fwrite($this->inputPipe, substr($string, $written));
1 ✔
380
                        if (!$bytes) {
1 ✔
381
                                break;
×
382
                        }
383
                }
384
        }
1 ✔
385

386

387
        /**
388
         * Closes the STDIN pipe, indicating no more data will be sent.
389
         */
390
        public function closeStdInput(): void
391
        {
392
                if (is_resource($this->inputPipe)) {
1 ✔
393
                        fclose($this->inputPipe);
1 ✔
394
                }
395
        }
1 ✔
396

397

398
        /**
399
         * If a callback is given, invokes it with the output/error produced since the previous call.
400
         * @param  (\Closure(string, string): void)|null  $callback
401
         */
402
        private function dispatchCallback(?\Closure $callback): void
403
        {
404
                if (!$callback) {
1 ✔
405
                        return;
1 ✔
406
                }
407
                $output = $this->extractNewData(self::StdOut);
1 ✔
408
                $error = $this->extractNewData(self::StdErr);
1 ✔
409
                if ($output !== '' || $error !== '') {
1 ✔
410
                        $callback($output, $error);
1 ✔
411
                }
412
        }
1 ✔
413

414

415
        /**
416
         * Checks if the timeout has expired. If yes, terminates the process.
417
         */
418
        private function enforceTimeout(): void
419
        {
420
                if ($this->timeout !== null && (microtime(as_float: true) - $this->startTime) >= $this->timeout) {
1 ✔
421
                        $this->terminate();
1 ✔
422
                        throw new ProcessTimeoutException('Process exceeded the time limit of ' . $this->timeout . ' seconds');
1 ✔
423
                }
424
        }
1 ✔
425

426

427
        /**
428
         * Reads any new data from the specified pipe and appends it to the buffer. Does nothing if the output
429
         * is not captured or the pipe is already closed (or handed over to another process).
430
         */
431
        private function readFromPipe(int $id, bool $final = false): void
432
        {
433
                $pipe = $this->outputPipes[$id] ?? null;
1 ✔
434
                if (!isset($this->outputBuffers[$id]) || !is_resource($pipe)) {
1 ✔
435
                        return;
1 ✔
436

437
                } elseif (isset($this->fileBackedOutputs[$id])) {
1 ✔
438
                        // Windows < 8.5: captured output is a temporary file; read whatever was appended since last time
439
                        fseek($pipe, strlen($this->outputBuffers[$id]));
×
440
                        $this->outputBuffers[$id] .= stream_get_contents($pipe);
×
441

442
                } elseif ($final) {
1 ✔
443
                        // the process has finished, everything is buffered in the pipe; non-blocking read on POSIX
444
                        // (cannot hang on a leaked descendant still holding the write end), blocking read to EOF on
445
                        // Windows, where non-blocking mode does not work and stream_select() may miss buffered data
446
                        stream_set_blocking($pipe, Helpers::IsWindows);
1 ✔
447
                        $this->outputBuffers[$id] .= stream_get_contents($pipe);
1 ✔
448

449
                } else {
450
                        // non-blocking drain: stream_set_blocking(false) works on POSIX only, so reads are also
451
                        // guarded by stream_select(), which works on Windows pipes since PHP 8.5 (PeekNamedPipe fix)
452
                        stream_set_blocking($pipe, false);
1 ✔
453
                        $read = [$pipe];
1 ✔
454
                        $write = $except = [];
1 ✔
455
                        while (@stream_select($read, $write, $except, 0, 0) > 0) { // @ an interrupting signal triggers a warning
1 ✔
456
                                $chunk = fread($pipe, 8192);
1 ✔
457
                                if ($chunk === false || $chunk === '') {
1 ✔
458
                                        break;
×
459
                                }
460
                                $this->outputBuffers[$id] .= $chunk;
1 ✔
461
                                $read = [$pipe];
1 ✔
462
                        }
463
                }
464
        }
1 ✔
465

466

467
        /**
468
         * Sends the initial input to the process: writes and closes a string or stream input,
469
         * or leaves STDIN open when input is null (until closeStdInput()) or another Process (fed by that process).
470
         * The input type was already validated by createInputDescriptor().
471
         *
472
         * Note: a string or stream input is written upfront, so if it is large and the process does not read it
473
         * while filling its own output, this can block; in that case pass null and feed STDIN via writeStdInput().
474
         */
475
        private function writeInitialInput(mixed $input): void
476
        {
477
                if ($input === null || $input instanceof self) {
1 ✔
478
                        // STDIN stays open
479

480
                } elseif (is_string($input)) {
1 ✔
481
                        $this->writeToPipe($input);
1 ✔
482
                        $this->closeStdInput();
1 ✔
483

484
                } elseif (is_resource($input)) {
1 ✔
485
                        stream_copy_to_stream($input, $this->inputPipe);
1 ✔
486
                        $this->closeStdInput();
1 ✔
487
                }
488
        }
1 ✔
489

490

491
        /**
492
         * Validates the input and determines the STDIN descriptor based on its type.
493
         */
494
        private function createInputDescriptor(mixed $input): mixed
495
        {
496
                if ($input === null || is_string($input) || is_resource($input)) {
1 ✔
497
                        return ['pipe', 'r'];
1 ✔
498
                } elseif (!$input instanceof self) {
1 ✔
499
                        throw new Nette\InvalidArgumentException('Input must be string, resource, Process or null, ' . get_debug_type($input) . ' given.');
1 ✔
500
                } elseif (Helpers::IsWindows) {
1 ✔
501
                        throw new Nette\NotSupportedException('Process piping is not supported on Windows.');
×
502
                } elseif (!isset($input->outputBuffers[self::StdOut]) || !is_resource($input->outputPipes[self::StdOut] ?? null)) {
1 ✔
503
                        throw new Nette\InvalidStateException('Cannot pipe from the given process: its STDOUT must be captured (it must not be redirected elsewhere).');
1 ✔
504
                }
505
                return $input->outputPipes[self::StdOut];
1 ✔
506
        }
507

508

509
        /**
510
         * Determines the descriptor for STDOUT or STDERR based on the specified output target.
511
         */
512
        private function createOutputDescriptor(int $id, mixed $output): mixed
513
        {
514
                if (is_resource($output)) {
1 ✔
515
                        $this->callerOutputs[$id] = true;
1 ✔
516
                        return $output;
1 ✔
517

518
                } elseif (is_string($output)) {
1 ✔
519
                        return FileSystem::open($output, 'w');
1 ✔
520

521
                } elseif ($output === false) {
1 ✔
522
                        return ['file', Helpers::IsWindows ? 'NUL' : '/dev/null', 'w'];
1 ✔
523

524
                } elseif ($output === null) {
1 ✔
525
                        $this->outputBuffers[$id] = '';
1 ✔
526
                        $this->outputBufferOffsets[$id] = 0;
1 ✔
527
                        if (Helpers::IsWindows && PHP_VERSION_ID < 80500) {
1 ✔
528
                                // Windows < 8.5: stream_select() doesn't work on pipes, capture into a temp file that reads non-blockingly
529
                                $this->fileBackedOutputs[$id] = true;
×
530
                                return tmpfile();
×
531
                        }
532
                        return ['pipe', 'w'];
1 ✔
533

534
                } else {
535
                        throw new Nette\InvalidArgumentException('Output must be string, resource, bool or null, ' . get_debug_type($output) . ' given.');
×
536
                }
537
        }
538

539

540
        /**
541
         * Closes all pipes and the process resource.
542
         */
543
        private function close(): void
544
        {
545
                $this->drainPipes(final: true);
1 ✔
546
                $this->closeStdInput();
1 ✔
547
                $this->closeOutputPipes();
1 ✔
548
                proc_close($this->process);
1 ✔
549
        }
1 ✔
550

551

552
        /**
553
         * Closes the output pipes that this class opened; resources supplied by the caller are left untouched.
554
         * (The temporary file backing captured output on Windows < 8.5 is removed by fclose() itself.)
555
         */
556
        private function closeOutputPipes(): void
557
        {
558
                foreach ($this->outputPipes as $id => $pipe) {
1 ✔
559
                        if (is_resource($pipe) && !isset($this->callerOutputs[$id])) {
1 ✔
560
                                fclose($pipe);
1 ✔
561
                        }
562
                }
563
        }
1 ✔
564
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc