Files
rspade_system/app/RSpade/Commands/Migrate/PrivilegedCommandTrait.php
2025-12-23 10:12:49 +00:00

61 lines
1.5 KiB
PHP
Executable File

<?php
namespace App\RSpade\Commands\Migrate;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
/**
* Trait for commands that need to run privileged operations (supervisorctl, file ops on /var/lib/mysql, etc.)
*
* Automatically prepends sudo when not running as root.
*/
trait PrivilegedCommandTrait
{
/**
* Check if we're running as root
*/
protected function is_root(): bool
{
$whoami = trim(shell_exec('whoami') ?? '');
return $whoami === 'root';
}
/**
* Get sudo prefix if needed
*/
protected function sudo_prefix(): string
{
return $this->is_root() ? '' : 'sudo ';
}
/**
* Run a shell command string with sudo if needed
*/
protected function shell_exec_privileged(string $command): ?string
{
$full_command = $this->sudo_prefix() . $command;
return shell_exec($full_command);
}
/**
* Run a Process command array with sudo if needed
*/
protected function run_privileged_command(array $command, bool $throw_on_error = true): string
{
if (!$this->is_root()) {
array_unshift($command, 'sudo');
}
$process = new Process($command);
$process->setTimeout(60);
$process->run();
if ($throw_on_error && !$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
return $process->getOutput();
}
}