PhpProcess.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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\RuntimeException;
  12. /**
  13. * PhpProcess runs a PHP script in an independent process.
  14. *
  15. * $p = new PhpProcess('<?php echo "foo"; ?>');
  16. * $p->run();
  17. * print $p->getOutput()."\n";
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class PhpProcess extends Process
  22. {
  23. /**
  24. * @param string $script The PHP script to run (as a string)
  25. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  26. * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  27. * @param int $timeout The timeout in seconds
  28. * @param array $options An array of options for proc_open
  29. */
  30. public function __construct($script, $cwd = null, array $env = null, $timeout = 60, array $options = array())
  31. {
  32. $executableFinder = new PhpExecutableFinder();
  33. if (false === $php = $executableFinder->find()) {
  34. $php = null;
  35. }
  36. if ('phpdbg' === \PHP_SAPI) {
  37. $file = tempnam(sys_get_temp_dir(), 'dbg');
  38. file_put_contents($file, $script);
  39. register_shutdown_function('unlink', $file);
  40. $php .= ' '.ProcessUtils::escapeArgument($file);
  41. $script = null;
  42. }
  43. if ('\\' !== \DIRECTORY_SEPARATOR && null !== $php) {
  44. // exec is mandatory to deal with sending a signal to the process
  45. // see https://github.com/symfony/symfony/issues/5030 about prepending
  46. // command with exec
  47. $php = 'exec '.$php;
  48. }
  49. parent::__construct($php, $cwd, $env, $script, $timeout, $options);
  50. }
  51. /**
  52. * Sets the path to the PHP binary to use.
  53. */
  54. public function setPhpBinary($php)
  55. {
  56. $this->setCommandLine($php);
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function start($callback = null)
  62. {
  63. if (null === $this->getCommandLine()) {
  64. throw new RuntimeException('Unable to find the PHP executable.');
  65. }
  66. parent::start($callback);
  67. }
  68. }