PhpProcess.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Symfony\Component\Process;
  3. /*
  4. * This file is part of the Symfony package.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. /**
  12. * PhpProcess runs a PHP script in an independent process.
  13. *
  14. * $p = new PhpProcess('<?php echo "foo"; ?>');
  15. * $p->run();
  16. * print $p->getOutput()."\n";
  17. *
  18. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  19. */
  20. class PhpProcess extends Process
  21. {
  22. /**
  23. * Constructor.
  24. *
  25. * @param string $script The PHP script to run (as a string)
  26. * @param string $cwd The working directory
  27. * @param array $env The environment variables
  28. * @param integer $timeout The timeout in seconds
  29. * @param array $options An array of options for proc_open
  30. */
  31. public function __construct($script, $cwd = null, array $env = array(), $timeout = 60, array $options = array())
  32. {
  33. parent::__construct(null, $cwd, $env, $script, $timeout, $options);
  34. }
  35. /**
  36. * Sets the path to the PHP binary to use.
  37. */
  38. public function setPhpBinary($php)
  39. {
  40. $this->commandline = $php;
  41. }
  42. /**
  43. * Runs the process.
  44. *
  45. * @param Closure|string|array $callback A PHP callback to run whenever there is some
  46. * output available on STDOUT or STDERR
  47. *
  48. * @return integer The exit status code
  49. */
  50. public function run($callback = null)
  51. {
  52. if (null === $this->commandline) {
  53. $this->commandline = $this->getPhpBinary();
  54. }
  55. return parent::run($callback);
  56. }
  57. /**
  58. * Returns the PHP binary path.
  59. *
  60. * @return string The PHP binary path
  61. *
  62. * @throws \RuntimeException When defined PHP_PATH is not executable or not found
  63. */
  64. static public function getPhpBinary()
  65. {
  66. if (getenv('PHP_PATH')) {
  67. if (!is_executable($php = getenv('PHP_PATH'))) {
  68. throw new \RuntimeException('The defined PHP_PATH environment variable is not a valid PHP executable.');
  69. }
  70. return $php;
  71. }
  72. $suffixes = DIRECTORY_SEPARATOR == '\\' ? (getenv('PATHEXT') ? explode(PATH_SEPARATOR, getenv('PATHEXT')) : array('.exe', '.bat', '.cmd', '.com')) : array('');
  73. foreach ($suffixes as $suffix) {
  74. if (is_executable($php = PHP_BINDIR.DIRECTORY_SEPARATOR.'php'.$suffix)) {
  75. return $php;
  76. }
  77. }
  78. throw new \RuntimeException('Unable to find the PHP executable.');
  79. }
  80. }