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
14use Symfony\Component\Process\Exception\LogicException;
15use Symfony\Component\Process\Exception\RuntimeException;
16
17/**
18 * PhpProcess runs a PHP script in an independent process.
19 *
20 *     $p = new PhpProcess('<?php echo "foo"; ?>');
21 *     $p->run();
22 *     print $p->getOutput()."\n";
23 *
24 * @author Fabien Potencier <fabien@symfony.com>
25 */
26class PhpProcess extends Process
27{
28    /**
29     * @param string      $script  The PHP script to run (as a string)
30     * @param string|null $cwd     The working directory or null to use the working dir of the current PHP process
31     * @param array|null  $env     The environment variables or null to use the same environment as the current PHP process
32     * @param int         $timeout The timeout in seconds
33     * @param array|null  $php     Path to the PHP binary to use with any additional arguments
34     */
35    public function __construct(string $script, string $cwd = null, array $env = null, int $timeout = 60, array $php = null)
36    {
37        if (null === $php) {
38            $executableFinder = new PhpExecutableFinder();
39            $php = $executableFinder->find(false);
40            $php = false === $php ? null : array_merge([$php], $executableFinder->findArguments());
41        }
42        if ('phpdbg' === \PHP_SAPI) {
43            $file = tempnam(sys_get_temp_dir(), 'dbg');
44            file_put_contents($file, $script);
45            register_shutdown_function('unlink', $file);
46            $php[] = $file;
47            $script = null;
48        }
49
50        parent::__construct($php, $cwd, $env, $script, $timeout);
51    }
52
53    /**
54     * {@inheritdoc}
55     */
56    public static function fromShellCommandline(string $command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
57    {
58        throw new LogicException(sprintf('The "%s()" method cannot be called when using "%s".', __METHOD__, self::class));
59    }
60
61    /**
62     * {@inheritdoc}
63     */
64    public function start(callable $callback = null, array $env = [])
65    {
66        if (null === $this->getCommandLine()) {
67            throw new RuntimeException('Unable to find the PHP executable.');
68        }
69
70        parent::start($callback, $env);
71    }
72}
73