ProcessBuilder.php 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. /*
  3. * This file is part of the Assetic package, an OpenSky project.
  4. *
  5. * (c) 2010-2012 OpenSky Project Inc
  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 Assetic\Util;
  11. /**
  12. * Process builder.
  13. *
  14. * @author Kris Wallsmith <kris.wallsmith@gmail.com>
  15. */
  16. class ProcessBuilder
  17. {
  18. private $arguments;
  19. private $cwd;
  20. private $env;
  21. private $stdin;
  22. private $timeout = 60;
  23. private $options = array();
  24. private $inheritEnv = false;
  25. public function __construct(array $arguments = array())
  26. {
  27. $this->arguments = $arguments;
  28. }
  29. /**
  30. * Adds an unescaped argument to the command string.
  31. *
  32. * @param string $argument A command argument
  33. */
  34. public function add($argument)
  35. {
  36. $this->arguments[] = $argument;
  37. return $this;
  38. }
  39. public function setWorkingDirectory($cwd)
  40. {
  41. $this->cwd = $cwd;
  42. return $this;
  43. }
  44. public function inheritEnvironmentVariables($inheritEnv = true)
  45. {
  46. $this->inheritEnv = $inheritEnv;
  47. return $this;
  48. }
  49. public function setEnv($name, $value)
  50. {
  51. if (null === $this->env) {
  52. $this->env = array();
  53. }
  54. $this->env[$name] = $value;
  55. return $this;
  56. }
  57. public function setInput($stdin)
  58. {
  59. $this->stdin = $stdin;
  60. return $this;
  61. }
  62. public function setTimeout($timeout)
  63. {
  64. $this->timeout = $timeout;
  65. return $this;
  66. }
  67. public function setOption($name, $value)
  68. {
  69. $this->options[$name] = $value;
  70. return $this;
  71. }
  72. public function getProcess()
  73. {
  74. if (!count($this->arguments)) {
  75. throw new \LogicException('You must add() command arguments before calling getProcess().');
  76. }
  77. $options = $this->options;
  78. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  79. $options += array('bypass_shell' => true);
  80. $args = $this->arguments;
  81. $cmd = array_shift($args);
  82. $script = '"'.$cmd.'"';
  83. if ($args) {
  84. $script .= ' '.implode(' ', array_map('escapeshellarg', $args));
  85. }
  86. } else {
  87. $script = implode(' ', array_map('escapeshellarg', $this->arguments));
  88. }
  89. $env = $this->inheritEnv && $_ENV ? ($this->env ?: array()) + $_ENV : $this->env;
  90. return new Process($script, $this->cwd, $env, $this->stdin, $this->timeout, $options);
  91. }
  92. }