ExecutableFinder.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. /**
  12. * Generic executable finder.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  16. */
  17. class ExecutableFinder
  18. {
  19. private static $isWindows;
  20. private $suffixes = array('.exe', '.bat', '.cmd', '.com');
  21. public function __construct()
  22. {
  23. if (null === self::$isWindows) {
  24. self::$isWindows = 0 === stripos(PHP_OS, 'win');
  25. }
  26. }
  27. public function setSuffixes(array $suffixes)
  28. {
  29. $this->suffixes = $suffixes;
  30. }
  31. public function addSuffix($suffix)
  32. {
  33. $this->suffixes[] = $suffix;
  34. }
  35. /**
  36. * Finds an executable by name.
  37. *
  38. * @param string $name The executable name (without the extension)
  39. * @param string $default The default to return if no executable is found
  40. *
  41. * @return string The executable path or default value
  42. */
  43. public function find($name, $default = null)
  44. {
  45. if (ini_get('open_basedir')) {
  46. $searchPath = explode(PATH_SEPARATOR, getenv('open_basedir'));
  47. $dirs = array();
  48. foreach ($searchPath as $path) {
  49. if (is_dir($path)) {
  50. $dirs[] = $path;
  51. } else {
  52. $file = str_replace(dirname($path), '', $path);
  53. if ($file == $name && is_executable($path)) {
  54. return $path;
  55. }
  56. }
  57. }
  58. } else {
  59. $dirs = explode(PATH_SEPARATOR, getenv('PATH') ? getenv('PATH') : getenv('Path'));
  60. }
  61. $suffixes = DIRECTORY_SEPARATOR == '\\' ? (getenv('PATHEXT') ? explode(PATH_SEPARATOR, getenv('PATHEXT')) : $this->suffixes) : array('');
  62. foreach ($suffixes as $suffix) {
  63. foreach ($dirs as $dir) {
  64. if (is_file($file = $dir.DIRECTORY_SEPARATOR.$name.$suffix) && (self::$isWindows || is_executable($file))) {
  65. return $file;
  66. }
  67. }
  68. }
  69. return $default;
  70. }
  71. }