1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Process;
13
14/**
15 * An executable finder specifically designed for the PHP executable.
16 *
17 * @author Fabien Potencier <fabien@symfony.com>
18 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
19 */
20class PhpExecutableFinder
21{
22    private $executableFinder;
23
24    public function __construct()
25    {
26        $this->executableFinder = new ExecutableFinder();
27    }
28
29    /**
30     * Finds The PHP executable.
31     *
32     * @return string|false
33     */
34    public function find(bool $includeArgs = true)
35    {
36        if ($php = getenv('PHP_BINARY')) {
37            if (!is_executable($php)) {
38                $command = '\\' === \DIRECTORY_SEPARATOR ? 'where' : 'command -v';
39                if ($php = strtok(exec($command.' '.escapeshellarg($php)), \PHP_EOL)) {
40                    if (!is_executable($php)) {
41                        return false;
42                    }
43                } else {
44                    return false;
45                }
46            }
47
48            if (@is_dir($php)) {
49                return false;
50            }
51
52            return $php;
53        }
54
55        $args = $this->findArguments();
56        $args = $includeArgs && $args ? ' '.implode(' ', $args) : '';
57
58        // PHP_BINARY return the current sapi executable
59        if (\PHP_BINARY && \in_array(\PHP_SAPI, ['cgi-fcgi', 'cli', 'cli-server', 'phpdbg'], true)) {
60            return \PHP_BINARY.$args;
61        }
62
63        if ($php = getenv('PHP_PATH')) {
64            if (!@is_executable($php) || @is_dir($php)) {
65                return false;
66            }
67
68            return $php;
69        }
70
71        if ($php = getenv('PHP_PEAR_PHP_BIN')) {
72            if (@is_executable($php) && !@is_dir($php)) {
73                return $php;
74            }
75        }
76
77        if (@is_executable($php = \PHP_BINDIR.('\\' === \DIRECTORY_SEPARATOR ? '\\php.exe' : '/php')) && !@is_dir($php)) {
78            return $php;
79        }
80
81        $dirs = [\PHP_BINDIR];
82        if ('\\' === \DIRECTORY_SEPARATOR) {
83            $dirs[] = 'C:\xampp\php\\';
84        }
85
86        return $this->executableFinder->find('php', false, $dirs);
87    }
88
89    /**
90     * Finds the PHP executable arguments.
91     *
92     * @return array
93     */
94    public function findArguments()
95    {
96        $arguments = [];
97        if ('phpdbg' === \PHP_SAPI) {
98            $arguments[] = '-qrr';
99        }
100
101        return $arguments;
102    }
103}
104