ExecutableFinder.php 2.3 KB

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