| 1 |
<?php |
| 2 |
/** |
| 3 |
* Copyright 2024 Google Inc. All Rights Reserved. |
| 4 |
* |
| 5 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
* you may not use this file except in compliance with the License. |
| 7 |
* You may obtain a copy of the License at |
| 8 |
* |
| 9 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
* |
| 11 |
* Unless required by applicable law or agreed to in writing, software |
| 12 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 13 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 |
* See the License for the specific language governing permissions and |
| 15 |
* limitations under the License. |
| 16 |
*/ |
| 17 |
namespace Google\Auth\ExecutableHandler; |
| 18 |
|
| 19 |
use RuntimeException; |
| 20 |
use Symfony\Component\Process\Exception\ProcessTimedOutException; |
| 21 |
use Symfony\Component\Process\Process; |
| 22 |
|
| 23 |
class ExecutableHandler |
| 24 |
{ |
| 25 |
private const DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000; |
| 26 |
|
| 27 |
private int $timeoutMs; |
| 28 |
|
| 29 |
/** @var array<string|\Stringable> */ |
| 30 |
private array $env = []; |
| 31 |
|
| 32 |
private ?string $output = null; |
| 33 |
|
| 34 |
/** |
| 35 |
* @param array<string|\Stringable> $env |
| 36 |
*/ |
| 37 |
public function __construct( |
| 38 |
array $env = [], |
| 39 |
int $timeoutMs = self::DEFAULT_EXECUTABLE_TIMEOUT_MILLIS, |
| 40 |
) { |
| 41 |
if (!class_exists(Process::class)) { |
| 42 |
throw new RuntimeException(sprintf( |
| 43 |
'The "symfony/process" package is required to use %s.', |
| 44 |
self::class |
| 45 |
)); |
| 46 |
} |
| 47 |
$this->env = $env; |
| 48 |
$this->timeoutMs = $timeoutMs; |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* @param string $command |
| 53 |
* @return int |
| 54 |
*/ |
| 55 |
public function __invoke(string $command): int |
| 56 |
{ |
| 57 |
$process = Process::fromShellCommandline( |
| 58 |
$command, |
| 59 |
null, |
| 60 |
$this->env, |
| 61 |
null, |
| 62 |
($this->timeoutMs / 1000) |
| 63 |
); |
| 64 |
|
| 65 |
try { |
| 66 |
$process->run(); |
| 67 |
} catch (ProcessTimedOutException $e) { |
| 68 |
throw new ExecutableResponseError( |
| 69 |
'The executable failed to finish within the timeout specified.', |
| 70 |
'TIMEOUT_EXCEEDED' |
| 71 |
); |
| 72 |
} |
| 73 |
|
| 74 |
$this->output = $process->getOutput() . $process->getErrorOutput(); |
| 75 |
|
| 76 |
return $process->getExitCode(); |
| 77 |
} |
| 78 |
|
| 79 |
public function getOutput(): ?string |
| 80 |
{ |
| 81 |
return $this->output; |
| 82 |
} |
| 83 |
} |
| 84 |
|