Skip to content
Snippets Groups Projects
Select Git revision
  • master
  • 1.0.0
2 results

ShellCommandRunnerTrait.php

Blame
  • Code owners
    Assign users and groups as approvers for specific file changes. Learn more.
    ShellCommandRunnerTrait.php 2.33 KiB
    <?php
    
    namespace UnicaenShell\Command;
    
    use RuntimeException;
    use UnicaenShell\Command\Exception\ShellCommandException;
    
    trait ShellCommandRunnerTrait
    {
        /**
         * Lance une commande.
         *
         * Si un temps d'exécution max (timeout) est spécifié et s'il est atteint, l'exécution de la commande est interrompue
         * et une {@see \UnicaenShell\Command\Exception\TimedOutCommandException} est levée.
         *
         * @throws \UnicaenShell\Command\Exception\TimedOutCommandException
         */
        protected function runShellCommand(ShellCommandInterface $command, string $timeout = null)
        {
            $runner = new ShellCommandRunner();
            $runner->setCommand($command);
            try {
                if ($timeout) {
                    $result = $runner->runCommandWithTimeout($timeout);
                } else {
                    $result = $runner->runCommand();
                }
    
                if (!$result->isSuccessfull()) {
                    $message = sprintf("La commande '%s' a échoué (code retour = %s) : %s",
                        $command->getName(),
                        $result->getReturnCode(),
                        $command->getCommandLine()
                    );
                    if ($output = $result->getOutput()) {
                        $message .= "Voici le log d'exécution : " . implode(PHP_EOL, $output);
                    }
                    throw new RuntimeException($message);
                }
            }
            catch (RuntimeException | ShellCommandException $rte) {
                throw new RuntimeException(
                    "Une erreur est survenue lors de l'exécution de la commande " . $command->getName(),
                    0,
                    $rte);
            }
        }
    
        /**
         * Lance une commande en arrière-plan (nohup + &).
         * Du coup, pas de collecte de log ni de code de retour.
         *
         * @param \UnicaenShell\Command\ShellCommandInterface $command
         */
        protected function runShellCommandInBackground(ShellCommandInterface $command)
        {
            $runner = new ShellCommandRunner();
            $runner->setCommand($command);
            try {
                $runner->runCommandInBackground();
            }
            catch (ShellCommandException $rte) {
                throw new RuntimeException(
                    "Une erreur est survenue lors de l'exécution en tâche de fond de la commande " . $command->getName(),
                    0,
                    $rte);
            }
        }
    }