You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
93 lines
1.7 KiB
93 lines
1.7 KiB
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\System;
|
|
|
|
class Command
|
|
{
|
|
protected $command;
|
|
|
|
protected $defaultArguments;
|
|
|
|
protected $path;
|
|
|
|
public function __construct(string $command, array $defaultArguments = [])
|
|
{
|
|
$this->command = $command;
|
|
$this->defaultArguments = $defaultArguments;
|
|
$this->path = static::find($command);
|
|
|
|
if (!isset($this->path))
|
|
{
|
|
throw new \Exception('Command not found: '.$command);
|
|
}
|
|
}
|
|
|
|
public function getPath()
|
|
{
|
|
return $this->path;
|
|
}
|
|
|
|
public function create(array $arguments)
|
|
{
|
|
$arguments = array_merge($this->defaultArguments, $arguments);
|
|
foreach ($arguments as &$argument)
|
|
{
|
|
if (!is_object($argument) || !($argument instanceof CommandArgument))
|
|
{
|
|
$argument = new CommandArgument($argument);
|
|
}
|
|
}
|
|
|
|
$command = [];
|
|
if (strpos($this->path, ' ') === false)
|
|
{
|
|
$command[] = '"'.$this->path.'"';
|
|
}
|
|
else
|
|
{
|
|
$command[] = $this->path;
|
|
}
|
|
$command = array_merge($command, $arguments);
|
|
|
|
$process = app()->make('App\\System\\Process', ['command' => $command]);
|
|
$process->setStartModeSync();
|
|
return $process;
|
|
}
|
|
|
|
public function __invoke(array $arguments)
|
|
{
|
|
return $this->create($arguments)->start()->getStdout();
|
|
}
|
|
|
|
protected static function find($command)
|
|
{
|
|
if (PHP_OS == 'WINNT')
|
|
{
|
|
$result = shell_exec('where '.escapeshellarg($command));
|
|
// No idea why Windows is using unix line endings here
|
|
// Trim the trailing newline, last result is always empty
|
|
$result = explode("\n", trim($result));
|
|
$result = end($result);
|
|
}
|
|
else
|
|
{
|
|
$result = shell_exec('command -v '.escapeshellarg($command));
|
|
}
|
|
|
|
if (!is_string($result))
|
|
{
|
|
return;
|
|
}
|
|
|
|
$result = trim($result);
|
|
|
|
if (empty($result))
|
|
{
|
|
return;
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
}
|
|
|