ExecutableFinder.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 $suffixes = array('.exe', '.bat', '.cmd', '.com');
  20. /**
  21. * Replaces default suffixes of executable.
  22. *
  23. * @param array $suffixes
  24. */
  25. public function setSuffixes(array $suffixes)
  26. {
  27. $this->suffixes = $suffixes;
  28. }
  29. /**
  30. * Adds new possible suffix to check for executable.
  31. *
  32. * @param string $suffix
  33. */
  34. public function addSuffix($suffix)
  35. {
  36. $this->suffixes[] = $suffix;
  37. }
  38. /**
  39. * Finds an executable by name.
  40. *
  41. * @param string $name The executable name (without the extension)
  42. * @param string $default The default to return if no executable is found
  43. * @param array $extraDirs Additional dirs to check into
  44. *
  45. * @return string The executable path or default value
  46. */
  47. public function find($name, $default = null, array $extraDirs = array())
  48. {
  49. if (ini_get('open_basedir')) {
  50. $searchPath = explode(PATH_SEPARATOR, ini_get('open_basedir'));
  51. $dirs = array();
  52. foreach ($searchPath as $path) {
  53. if (is_dir($path)) {
  54. $dirs[] = $path;
  55. } else {
  56. if (basename($path) == $name && is_executable($path)) {
  57. return $path;
  58. }
  59. }
  60. }
  61. } else {
  62. $dirs = array_merge(
  63. explode(PATH_SEPARATOR, getenv('PATH') ?: getenv('Path')),
  64. $extraDirs
  65. );
  66. }
  67. $suffixes = array('');
  68. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  69. $pathExt = getenv('PATHEXT');
  70. $suffixes = $pathExt ? explode(PATH_SEPARATOR, $pathExt) : $this->suffixes;
  71. }
  72. foreach ($suffixes as $suffix) {
  73. foreach ($dirs as $dir) {
  74. if (is_file($file = $dir.DIRECTORY_SEPARATOR.$name.$suffix) && (defined('PHP_WINDOWS_VERSION_BUILD') || is_executable($file))) {
  75. return $file;
  76. }
  77. }
  78. }
  79. return $default;
  80. }
  81. }