PhpExecutableFinder example

use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;

class PhpSubprocessTest extends TestCase
{
    private static $phpBin;

    public static function setUpBeforeClass(): void
    {
        $phpBin = new PhpExecutableFinder();
        self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === \PHP_SAPI ? 'php' : $phpBin->find());
    }

    /** * @dataProvider subprocessProvider */
    public function testSubprocess(string $processClass, string $memoryLimit, string $expectedMemoryLimit)
    {
        $process = new Process([self::$phpBin,
            '-d',
            'memory_limit='.$memoryLimit,
            
/** * @author Robert Schönthal <seroscho@googlemail.com> */
class PhpExecutableFinderTest extends TestCase
{
    /** * tests find() with the constant PHP_BINARY. */
    public function testFind()
    {
        $f = new PhpExecutableFinder();

        $current = \PHP_BINARY;
        $args = 'phpdbg' === \PHP_SAPI ? ' -qrr' : '';

        $this->assertEquals($current.$args$f->find(), '::find() returns the executable PHP');
        $this->assertEquals($current$f->find(false), '::find() returns the executable PHP');
    }

    /** * tests find() with the env var PHP_PATH. */
    

  protected $php;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    $php_executable_finder = new PhpExecutableFinder();
    $this->php = $php_executable_finder->find();
    $this->root = dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__)), 2);
  }

  /** * @coversNothing */
  public function testInstallWithNonExistingFile() {

    // Create a connection to the DB configured in SIMPLETEST_DB.     $connection = Database::getConnection('default', $this->addTestDatabase(''));
    

        $workingDirectory = \func_get_args()[1] ?? __DIR__.'/Fixtures/web';

        if (isset(self::$process[$port])) {
            self::$process[$port]->stop();
        } else {
            register_shutdown_function(static function D) use ($port) {
                self::$process[$port]->stop();
            });
        }

        $finder = new PhpExecutableFinder();
        $process = new Process(array_merge([$finder->find(false)]$finder->findArguments()['-dopcache.enable=0', '-dvariables_order=EGPCS', '-S', '127.0.0.1:'.$port]));
        $process->setWorkingDirectory($workingDirectory);
        $process->start();
        self::$process[$port] = $process;

        do {
            usleep(50000);
        } while (!@fopen('http://127.0.0.1:'.$port, 'r'));

        return $process;
    }
}

  protected function start($host$port, DrupalKernelInterface $kernel, InputInterface $input, SymfonyStyle $io) {
    $finder = new PhpExecutableFinder();
    $binary = $finder->find();
    if ($binary === FALSE) {
      throw new \RuntimeException('Unable to find the PHP binary.');
    }

    $io->writeln("<info>Drupal development server started:</info> <http://{$host}:{$port}>");
    $io->writeln('<info>This server is not meant for production use.</info>');
    $one_time_login = "http://$host:$port{$this->getOneTimeLoginUrl()}/login";
    $io->writeln("<info>One time login url:</info> <$one_time_login>");
    $io->writeln('Press Ctrl-C to quit the Drupal development server.');

    
/** * Install a Drupal site using the quick start feature. * * @param string $profile * Drupal profile to install. * @param string $working_dir * (optional) A working directory relative to the workspace, within which to * execute the command. Defaults to the workspace directory. */
  public function installQuickStart($profile$working_dir = NULL) {
    $php_finder = new PhpExecutableFinder();
    $install_process = $this->executeCommand($php_finder->find() . ' ./core/scripts/drupal install ' . $profile$working_dir);
    $this->assertCommandOutputContains('Username:');
    preg_match('/Username: (.+)\vPassword: (.+)/', $install_process->getOutput()$matches);
    $this->assertNotEmpty($this->adminUsername = $matches[1]);
    $this->assertNotEmpty($this->adminPassword = $matches[2]);
  }

  /** * Helper that uses Drupal's user/login form to log in. * * @param string $username * Username. * @param string $password * Password. * @param string $working_dir * (optional) A working directory within which to login. Defaults to the * workspace directory. */
$fs = new Filesystem();
    $fs->chmod($this->getWorkspaceDirectory() . '/sites/default', 0700, 0000);

    // Composer tells you stuff in error output.     $this->executeCommand('COMPOSER_DISCARD_CHANGES=true composer install --no-interaction');
    $this->assertErrorOutputContains('Generating autoload files');

    // We have to stand up the server first so we can know the port number to     // pass along to the install command.     $this->standUpServer();

    $php_finder = new PhpExecutableFinder();
    $install_command = [
      $php_finder->find(),
      './core/scripts/test-site.php',
      'install',
      '--base-url=http://localhost:' . $this->getPortNumber(),
      '--db-url=sqlite://localhost/foo.sqlite',
      '--install-profile=minimal',
      '--json',
    ];
    $this->assertNotEmpty($output_json = $this->executeCommand(implode(' ', $install_command))->getOutput());
    $this->assertCommandSuccessful();
    
protected $php;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    $sqlite = (new \PDO('sqlite::memory:'))->query('select sqlite_version()')->fetch()[0];
    if (version_compare($sqlite, Tasks::SQLITE_MINIMUM_VERSION) < 0) {
      $this->markTestSkipped();
    }
    parent::setUp();
    $php_executable_finder = new PhpExecutableFinder();
    $this->php = $php_executable_finder->find();
    $this->copyCodebase();
    $this->executeCommand('COMPOSER_DISCARD_CHANGES=true composer install --no-dev --no-interaction');
    chdir($this->getWorkingPath());
  }

  /** * Generates PHP process to generate a theme from core's starterkit theme. * * @return \Symfony\Component\Process\Process * The PHP process */

    /** * @param string $script The PHP script to run (as a string) * @param string|null $cwd The working directory or null to use the working dir of the current PHP process * @param array|null $env The environment variables or null to use the same environment as the current PHP process * @param int $timeout The timeout in seconds * @param array|null $php Path to the PHP binary to use with any additional arguments */
    public function __construct(string $script, string $cwd = null, array $env = null, int $timeout = 60, array $php = null)
    {
        if (null === $php) {
            $executableFinder = new PhpExecutableFinder();
            $php = $executableFinder->find(false);
            $php = false === $php ? null : array_merge([$php]$executableFinder->findArguments());
        }
        if ('phpdbg' === \PHP_SAPI) {
            $file = tempnam(sys_get_temp_dir(), 'dbg');
            file_put_contents($file$script);
            register_shutdown_function('unlink', $file);
            $php[] = $file;
            $script = null;
        }

        
public static function setUpBeforeClass(): void {
    parent::setUpBeforeClass();
    static::checkClassCommandRequirements();
  }

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    static::checkMethodCommandRequirements($this->getName());
    $this->phpFinder = new PhpExecutableFinder();
    // Set up the workspace directory.     // @todo Glean working directory from env vars, etc.     $fs = new SymfonyFilesystem();
    $this->workspaceDir = $fs->tempnam(DrupalFilesystem::getOsTemporaryDirectory(), '/build_workspace_' . md5($this->getName() . microtime(TRUE)));
    $fs->remove($this->workspaceDir);
    $fs->mkdir($this->workspaceDir);
    $this->initMink();
  }

  /** * {@inheritdoc} */

    /** * @param string $script The PHP script to run (as a string) * @param string|null $cwd The working directory or null to use the working dir of the current PHP process * @param array|null $env The environment variables or null to use the same environment as the current PHP process * @param int $timeout The timeout in seconds * @param array|null $php Path to the PHP binary to use with any additional arguments */
    public function __construct(string $script, string $cwd = null, array $env = null, int $timeout = 60, array $php = null)
    {
        if (null === $php) {
            $executableFinder = new PhpExecutableFinder();
            $php = $executableFinder->find(false);
            $php = false === $php ? null : array_merge([$php]$executableFinder->findArguments());
        }
        if ('phpdbg' === \PHP_SAPI) {
            $file = tempnam(sys_get_temp_dir(), 'dbg');
            file_put_contents($file$script);
            register_shutdown_function('unlink', $file);
            $php[] = $file;
            $script = null;
        }

        
$process->start();
        $this->assertStringContainsString($commandLine$process->getCommandLine(), '::getCommandLine() returns the command line of PHP after start');

        $process->wait();
        $this->assertStringContainsString($commandLine$process->getCommandLine(), '::getCommandLine() returns the command line of PHP after wait');

        $this->assertSame(\PHP_VERSION.\PHP_SAPI, $process->getOutput());
    }

    public function testPassingPhpExplicitly()
    {
        $finder = new PhpExecutableFinder();
        $php = array_merge([$finder->find(false)]$finder->findArguments());

        $expected = 'hello world!';
        $script = <<<PHP <?php echo '$expected'; PHP;
        $process = new PhpProcess($script, null, null, 60, $php);
        $process->run();
        $this->assertEquals($expected$process->getOutput());
    }

    
// Load the actual autoloader being used and determine its filename using     // reflection. We can determine the vendor directory based on that filename.     $autoloader = require $this->appRoot . '/autoload.php';
    $reflector = new \ReflectionClass($autoloader);
    $vendor_dir = dirname($reflector->getFileName(), 2);

    // The file in Composer's bin dir is a *nix link, which does not work when     // extracted from a tarball and generally not on Windows.     $command = $vendor_dir . '/phpunit/phpunit/phpunit';
    if (substr(PHP_OS, 0, 3) == 'WIN') {
      // On Windows it is necessary to run the script using the PHP executable.       $php_executable_finder = new PhpExecutableFinder();
      $php = $php_executable_finder->find();
      $command = $php . ' -f ' . escapeshellarg($command) . ' --';
    }
    return $command;
  }

  /** * Executes the PHPUnit command. * * @param string[] $unescaped_test_classnames * An array of test class names, including full namespaces, to be passed as * a regular expression to PHPUnit's --filter option. * @param string $phpunit_file * A filepath to use for PHPUnit's --log-junit option. * @param int $status * (optional) The exit status code of the PHPUnit process will be assigned * to this variable. * @param string[] $output * (optional) The output by running the phpunit command. If provided, this * array will contain the lines output by the command. * * @return string * The results as returned by exec(). * * @internal */
/** * @author Robert Schönthal <seroscho@googlemail.com> */
class ProcessTest extends TestCase
{
    private static string $phpBin;
    private static ?Process $process = null;
    private static bool $sigchild;

    public static function setUpBeforeClass(): void
    {
        $phpBin = new PhpExecutableFinder();
        self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === \PHP_SAPI ? 'php' : $phpBin->find());

        ob_start();
        phpinfo(\INFO_GENERAL);
        self::$sigchild = str_contains(ob_get_clean(), '--enable-sigchild');
    }

    protected function tearDown(): void
    {
        if (self::$process) {
            self::$process->stop(0);
            
/** * @param array $command The command to run and its arguments listed as separate entries. They will automatically * get prefixed with the PHP binary * @param string|null $cwd The working directory or null to use the working dir of the current PHP process * @param array|null $env The environment variables or null to use the same environment as the current PHP process * @param int $timeout The timeout in seconds * @param array|null $php Path to the PHP binary to use with any additional arguments */
    public function __construct(array $command, string $cwd = null, array $env = null, int $timeout = 60, array $php = null)
    {
        if (null === $php) {
            $executableFinder = new PhpExecutableFinder();
            $php = $executableFinder->find(false);
            $php = false === $php ? null : array_merge([$php]$executableFinder->findArguments());
        }

        if (null === $php) {
            throw new RuntimeException('Unable to find PHP binary.');
        }

        $tmpIni = $this->writeTmpIni($this->getAllIniFiles()sys_get_temp_dir());

        $php = array_merge($php['-n', '-c', $tmpIni]);
        
Home | Imprint | This part of the site doesn't use cookies.