ExecutableFinder.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. // Silencing against https://bugs.php.net/69240
  54. if (@is_dir($path)) {
  55. $dirs[] = $path;
  56. } else {
  57. if (basename($path) == $name && is_executable($path)) {
  58. return $path;
  59. }
  60. }
  61. }
  62. } else {
  63. $dirs = array_merge(
  64. explode(PATH_SEPARATOR, getenv('PATH') ?: getenv('Path')),
  65. $extraDirs
  66. );
  67. }
  68. $suffixes = array('');
  69. if ('\\' === DIRECTORY_SEPARATOR) {
  70. $pathExt = getenv('PATHEXT');
  71. $suffixes = $pathExt ? explode(PATH_SEPARATOR, $pathExt) : $this->suffixes;
  72. }
  73. foreach ($suffixes as $suffix) {
  74. foreach ($dirs as $dir) {
  75. if (is_file($file = $dir.DIRECTORY_SEPARATOR.$name.$suffix) && ('\\' === DIRECTORY_SEPARATOR || is_executable($file))) {
  76. return $file;
  77. }
  78. }
  79. }
  80. return $default;
  81. }
  82. }