Process example

EOT;

        $PHP = '\\' === \DIRECTORY_SEPARATOR ? '"!PHP!"' : '"$PHP"';
        $successOutputPhp = <<<EOT RUN php -r $PHP OUT 42 RES Command ran successfully EOT;

        $errorMessage = 'An error occurred';
        $args = new Process(['php', '-r', 'echo 42;']);
        $args = $args->getCommandLine();
        $successOutputProcessDebug = str_replace("'php' '-r' 'echo 42;'", $args$successOutputProcessDebug);

        return [
            ['', 'php -r "echo 42;"', StreamOutput::VERBOSITY_VERBOSE, null],
            [$successOutputVerbose, 'php -r "echo 42;"', StreamOutput::VERBOSITY_VERY_VERBOSE, null],
            [$successOutputDebug, 'php -r "echo 42;"', StreamOutput::VERBOSITY_DEBUG, null],
            [$successOutputDebugWithTags, 'php -r "echo \'<info>42</info>\';"', StreamOutput::VERBOSITY_DEBUG, null],
            ['', 'php -r "syntax error"', StreamOutput::VERBOSITY_VERBOSE, null],
            [$syntaxErrorOutputVerbose, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, null],
            [$syntaxErrorOutputDebug, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, null],
            [
self::$process->stop(0);
            self::$process = null;
        }
    }

    public function testInvalidCwd()
    {
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessageMatches('/The provided cwd ".*" does not exist\./');
        try {
            // Check that it works fine if the CWD exists             $cmd = new Process(['echo', 'test'], __DIR__);
            $cmd->run();
        } catch (\Exception $e) {
            $this->fail($e);
        }

        $cmd = new Process(['echo', 'test'], __DIR__.'/notfound/');
        $cmd->run();
    }

    /** * @group transient-on-windows */
public static function setUpBeforeClass(): void
    {
        $phpBin = new PhpExecutableFinder();
        self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === \PHP_SAPI ? 'php' : $phpBin->find());
    }

    /** * @dataProvider subprocessProvider */
    public function testSubprocess(string $processClass, string $memoryLimit, string $expectedMemoryLimit)
    {
        $process = new Process([self::$phpBin,
            '-d',
            'memory_limit='.$memoryLimit,
            __DIR__.'/OutputMemoryLimitProcess.php',
            '-e', self::$phpBin,
            '-p', $processClass,
        ]);

        $process->mustRun();
        $this->assertEquals($expectedMemoryLimittrim($process->getOutput()));
    }

    
if ($output instanceof ConsoleOutputInterface) {
            $output = $output->getErrorOutput();
        }

        $formatter = $this->getHelperSet()->get('debug_formatter');

        if ($cmd instanceof Process) {
            $cmd = [$cmd];
        }

        if (\is_string($cmd[0] ?? null)) {
            $process = new Process($cmd);
            $cmd = [];
        } elseif (($cmd[0] ?? null) instanceof Process) {
            $process = $cmd[0];
            unset($cmd[0]);
        } else {
            throw new \InvalidArgumentException(sprintf('Invalid command provided to "%s()": the command should be an array whose first element is either the path to the binary to run or a "Process" object.', __METHOD__));
        }

        if ($verbosity <= $output->getVerbosity()) {
            $output->write($formatter->start(spl_object_hash($process)$this->escapeString($process->getCommandLine())));
        }

        
$working_path = $this->getWorkingPath($working_dir);
    $server = [
      $finder->find(),
      '-S',
      self::$hostName . ':' . $port,
      '-t',
      $working_path,
    ];
    if (file_exists($working_path . DIRECTORY_SEPARATOR . '.ht.router.php')) {
      $server[] = $working_path . DIRECTORY_SEPARATOR . '.ht.router.php';
    }
    $ps = new Process($server$working_path);
    $ps->setIdleTimeout(30)
      ->setTimeout(30)
      ->start();
    // Wait until the web server has started. It is started if the port is no     // longer available.     for ($i = 0; $i < 50; $i++) {
      usleep(100000);
      if (!$this->checkPortIsAvailable($port)) {
        return $ps;
      }
    }

    
private static function guessShell(): string
    {
        return basename($_SERVER['SHELL'] ?? '');
    }

    private function tailDebugLog(string $commandName, OutputInterface $output): void
    {
        $debugFile = sys_get_temp_dir().'/sf_'.$commandName.'.log';
        if (!file_exists($debugFile)) {
            touch($debugFile);
        }
        $process = new Process(['tail', '-f', $debugFile], null, null, null, 0);
        $process->run(function Dstring $type, string $line) use ($output): void {
            $output->write($line);
        });
    }

    /** * @return string[] */
    private function getSupportedShells(): array
    {
        if (isset($this->supportedShells)) {
            
private static function startVulcain(HttpClientInterface $client)
    {
        if (self::$vulcainStarted) {
            return;
        }

        if ('\\' === \DIRECTORY_SEPARATOR) {
            throw new SkippedTestSuiteError('Testing with the "vulcain" is not supported on Windows.');
        }

        $process = new Process(['vulcain'], null, [
            'DEBUG' => 1,
            'UPSTREAM' => 'http://127.0.0.1:8057',
            'ADDR' => ':3000',
            'KEY_FILE' => __DIR__.'/Fixtures/tls/server.key',
            'CERT_FILE' => __DIR__.'/Fixtures/tls/server.crt',
        ]);
        $process->start();

        register_shutdown_function($process->stop(...));
        sleep('\\' === \DIRECTORY_SEPARATOR ? 10 : 1);

        
$workingDirectory = \func_get_args()[1] ?? __DIR__.'/Fixtures/web';

        if (isset(self::$process[$port])) {
            self::$process[$port]->stop();
        } else {
            register_shutdown_function(static function D) use ($port) {
                self::$process[$port]->stop();
            });
        }

        $finder = new PhpExecutableFinder();
        $process = new Process(array_merge([$finder->find(false)]$finder->findArguments()['-dopcache.enable=0', '-dvariables_order=EGPCS', '-S', '127.0.0.1:'.$port]));
        $process->setWorkingDirectory($workingDirectory);
        $process->start();
        self::$process[$port] = $process;

        do {
            usleep(50000);
        } while (!@fopen('http://127.0.0.1:'.$port, 'r'));

        return $process;
    }
}
// Install a site using the standard profile to ensure the one time login     // link generation works.
    $install_command = [
      $this->php,
      'core/scripts/drupal',
      'quick-start',
      'standard',
      "--site-name='Test site {$this->testDb->getDatabasePrefix()}'",
      '--suppress-login',
    ];
    $process = new Process($install_command, NULL, ['DRUPAL_DEV_SITE_PATH' => $this->testDb->getTestSitePath()]);
    $process->setTimeout(500);
    $process->start();
    $guzzle = new Client();
    $port = FALSE;
    $process->waitUntil(function D$type$output) use (&$port) {
      if (preg_match('/127.0.0.1:(\d+)/', $output$match)) {
        $port = $match[1];
        return TRUE;
      }
    });
    // The progress bar uses STDERR to write messages.
$one_time_login = "http://$host:$port{$this->getOneTimeLoginUrl()}/login";
    $io->writeln("<info>One time login url:</info> <$one_time_login>");
    $io->writeln('Press Ctrl-C to quit the Drupal development server.');

    if (!$input->getOption('suppress-login')) {
      if ($this->openBrowser("$one_time_login?destination=" . urlencode("/")$io) === 1) {
        $io->error('Error while opening up a one time login URL');
      }
    }

    // Use the Process object to construct an escaped command line.     $process = new Process([
      $binary,
      '-S',
      $host . ':' . $port,
      '.ht.router.php',
    ]$kernel->getAppRoot()[], NULL, NULL);
    if ($io->isVerbose()) {
      $io->writeln("<info>Server command:</info> {$process->getCommandLine()}");
    }

    // Carefully manage output so we can display output only in verbose mode.     $descriptors = [];
    
namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\PhpSubprocess;
use Symfony\Component\Process\Process;

require is_file(\dirname(__DIR__).'/vendor/autoload.php') ? \dirname(__DIR__).'/vendor/autoload.php' : \dirname(__DIR__, 5).'/vendor/autoload.php';

['e' => $php, 'p' => $process] = getopt('e:p:') + ['e' => 'php', 'p' => 'Process'];

if ('Process' === $process) {
    $p = new Process([$php, __DIR__.'/Fixtures/memory.php']);
} else {
    $p = new PhpSubprocess([__DIR__.'/Fixtures/memory.php'], null, null, 60, [$php]);
}

$p->mustRun();
echo $p->getOutput();

  private function generateThemeFromStarterkit($env = NULL) : Process {
    $install_command = [
      $this->php,
      'core/scripts/drupal',
      'generate-theme',
      'test_custom_theme',
      '--name="Test custom starterkit theme"',
      '--description="Custom theme generated from a starterkit theme"',
    ];
    $process = new Process($install_command, NULL, $env);
    $process->setTimeout(60);
    return $process;
  }

  /** * Asserts the theme exists. Returns the parsed *.info.yml file. * * @param string $theme_path_relative * The core-relative path to the theme. * * @return array * The parsed *.info.yml file. */
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Exception\RunProcessFailedException;
use Symfony\Component\Process\Process;

/** * @author Kevin Bond <kevinbond@gmail.com> */
final class RunProcessMessageHandler
{
    public function __invoke(RunProcessMessage $message): RunProcessContext
    {
        $process = new Process($message->command, $message->cwd, $message->env, $message->input, $message->timeout);

        try {
            return new RunProcessContext($message$process->mustRun());
        } catch (ProcessFailedException $e) {
            throw new RunProcessFailedException($enew RunProcessContext($message$e->getProcess()));
        }
    }
}
namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Process;

require is_file(\dirname(__DIR__).'/vendor/autoload.php') ? \dirname(__DIR__).'/vendor/autoload.php' : \dirname(__DIR__, 5).'/vendor/autoload.php';

['e' => $php] = getopt('e:') + ['e' => 'php'];

try {
    $process = new Process([$php, '-r', "echo 'ready'; trigger_error('error', E_USER_ERROR);"]);
    $process->start();
    $process->setTimeout(0.5);
    while (!str_contains($process->getOutput(), 'ready')) {
        usleep(1000);
    }
    $process->signal(\SIGSTOP);
    $process->wait();

    return $process->getExitCode();
} catch (ProcessTimedOutException $t) {
    echo $t->getMessage().\PHP_EOL;

    
use Symfony\Component\Process\Process;

/** * @author Andrei Olteanu <andrei@flashsoft.eu> */
class CreateNewConsoleTest extends TestCase
{
    public function testOptionCreateNewConsole()
    {
        $this->expectNotToPerformAssertions();
        try {
            $process = new Process(['php', __DIR__.'/ThreeSecondProcess.php']);
            $process->setOptions(['create_new_console' => true]);
            $process->disableOutput();
            $process->start();
        } catch (\Exception $e) {
            $this->fail($e);
        }
    }

    public function testItReturnsFastAfterStart()
    {
        // The started process must run in background after the main has finished but that can't be tested with PHPUnit
Home | Imprint | This part of the site doesn't use cookies.