ExecutableFinder.php 2.3 KB

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