Command.php
1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
declare(strict_types=1);
namespace ImageOptimizer;
use function function_exists;
use ImageOptimizer\Exception\CommandNotFound;
use ImageOptimizer\Exception\Exception;
use Symfony\Component\Process\Exception\RuntimeException;
use Symfony\Component\Process\Process;
final class Command
{
private $cmd;
private $args;
private $timeout;
public function __construct(string $bin, array $args = [], ?float $timeout = null)
{
if(!function_exists('exec')) {
throw new Exception('"exec" function is not available. Please check if it is not listed as "disable_functions" in your "php.ini" file.');
}
if(!function_exists('proc_open')) {
throw new RuntimeException('"proc_open" function is not available. Please check if it is not listed as "disable_functions" in your "php.ini" file.');
}
$this->cmd = $bin;
$this->args = $args;
$this->timeout = $timeout;
}
public function execute(array $customArgs = []): void
{
$process = new Process(array_merge([$this->cmd], $this->args, $customArgs));
$process->setTimeout($this->timeout);
try {
$exitCode = $process->run();
$commandLine = $process->getCommandLine();
$output = $process->getOutput().PHP_EOL.$process->getErrorOutput();
if($exitCode == 127) {
throw new CommandNotFound(sprintf('Command "%s" not found.', $this->cmd));
}
if($exitCode !== 0 || stripos($output, 'error') !== false || stripos($output, 'permission') !== false) {
throw new Exception(sprintf('Command failed, return code: %d, command: %s, stderr: %s', $exitCode, $commandLine, trim($output)));
}
} catch(RuntimeException $e) {
throw new Exception($e->getMessage(), $e->getCode(), $e);
}
}
}