3 * SPDX-License-Identifier: GPL-2.0-only
5 * This file is part of Nominatim. (https://nominatim.org)
7 * Copyright (C) 2022 by the Nominatim developer community.
8 * For a full list of authors see the git log.
15 public function __construct($sBaseCmd, ...$aParams)
18 throw new \Exception('Command missing in new() call');
20 $this->baseCmd = $sBaseCmd;
21 $this->aParams = array();
22 $this->aEnv = null; // null = use the same environment as the current PHP process
24 $this->stdoutString = null;
26 foreach ($aParams as $sParam) {
27 $this->addParams($sParam);
31 public function addParams(...$aParams)
33 foreach ($aParams as $sParam) {
34 if (isset($sParam) && $sParam !== null && $sParam !== '') {
35 array_push($this->aParams, $sParam);
41 public function addEnvPair($sKey, $sVal)
43 if (isset($sKey) && $sKey && isset($sVal)) {
44 if (!isset($this->aEnv)) {
47 $this->aEnv = array_merge($this->aEnv, array($sKey => $sVal), $_ENV);
52 public function escapedCmd()
54 $aEscaped = array_map(function ($sParam) {
55 return $this->escapeParam($sParam);
56 }, array_merge(array($this->baseCmd), $this->aParams));
58 return join(' ', $aEscaped);
61 public function run($bExitOnFail = false)
63 $sCmd = $this->escapedCmd();
64 // $aEnv does not need escaping, proc_open seems to handle it fine
67 0 => array('pipe', 'r'),
72 $hProc = @proc_open($sCmd, $aFDs, $aPipes, null, $this->aEnv);
73 if (!is_resource($hProc)) {
74 throw new \Exception('Unable to run command: ' . $sCmd);
77 fclose($aPipes[0]); // no stdin
79 $iStat = proc_close($hProc);
81 if ($iStat != 0 && $bExitOnFail) {
88 private function escapeParam($sParam)
90 return (preg_match('/^-*\w+$/', $sParam)) ? $sParam : escapeshellarg($sParam);