PhpProcess.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Process;
  11. use Symfony\Component\Process\Exception\LogicException;
  12. use Symfony\Component\Process\Exception\RuntimeException;
  13. /**
  14. * PhpProcess runs a PHP script in an independent process.
  15. *
  16. * $p = new PhpProcess('<?php echo "foo"; ?>');
  17. * $p->run();
  18. * print $p->getOutput()."\n";
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class PhpProcess extends Process
  23. {
  24. /**
  25. * @param string $script The PHP script to run (as a string)
  26. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  27. * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  28. * @param int $timeout The timeout in seconds
  29. * @param array|null $php Path to the PHP binary to use with any additional arguments
  30. */
  31. public function __construct(string $script, ?string $cwd = null, ?array $env = null, int $timeout = 60, ?array $php = null)
  32. {
  33. if (null === $php) {
  34. $executableFinder = new PhpExecutableFinder();
  35. $php = $executableFinder->find(false);
  36. $php = false === $php ? null : array_merge([$php], $executableFinder->findArguments());
  37. }
  38. if ('phpdbg' === \PHP_SAPI) {
  39. $file = tempnam(sys_get_temp_dir(), 'dbg');
  40. file_put_contents($file, $script);
  41. register_shutdown_function('unlink', $file);
  42. $php[] = $file;
  43. $script = null;
  44. }
  45. parent::__construct($php, $cwd, $env, $script, $timeout);
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public static function fromShellCommandline(string $command, ?string $cwd = null, ?array $env = null, $input = null, ?float $timeout = 60)
  51. {
  52. throw new LogicException(sprintf('The "%s()" method cannot be called when using "%s".', __METHOD__, self::class));
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function start(?callable $callback = null, array $env = [])
  58. {
  59. if (null === $this->getCommandLine()) {
  60. throw new RuntimeException('Unable to find the PHP executable.');
  61. }
  62. parent::start($callback, $env);
  63. }
  64. }