From f56a96251a17fbde2aa2b307215806a282224f70 Mon Sep 17 00:00:00 2001
From: phenaproxima <phenaproxima@205645.no-reply.drupal.org>
Date: Wed, 8 Jun 2022 14:45:50 +0000
Subject: [PATCH] Issue #3282677 by phenaproxima: In certain situations,
 Composer may run with a different PHP interpreter than the one running Drupal

---
 package_manager/src/ProcessFactory.php        |  5 ++-
 .../tests/src/Unit/ProcessFactoryTest.php     | 37 +++++++++++++++++++
 2 files changed, 40 insertions(+), 2 deletions(-)
 create mode 100644 package_manager/tests/src/Unit/ProcessFactoryTest.php

diff --git a/package_manager/src/ProcessFactory.php b/package_manager/src/ProcessFactory.php
index d7089d80dc..7530b37211 100644
--- a/package_manager/src/ProcessFactory.php
+++ b/package_manager/src/ProcessFactory.php
@@ -74,8 +74,9 @@ final class ProcessFactory implements ProcessFactoryInterface {
     if ($this->isComposerCommand($command)) {
       $env['COMPOSER_HOME'] = $this->getComposerHomePath();
     }
-    // Ensure that the PHP interpreter is in the PATH.
-    $env['PATH'] = $this->getEnv('PATH') . ':' . static::getPhpDirectory();
+    // Ensure that the current PHP installation is the first place that will be
+    // searched when looking for the PHP interpreter.
+    $env['PATH'] = static::getPhpDirectory() . ':' . $this->getEnv('PATH');
     return $process->setEnv($env);
   }
 
diff --git a/package_manager/tests/src/Unit/ProcessFactoryTest.php b/package_manager/tests/src/Unit/ProcessFactoryTest.php
new file mode 100644
index 0000000000..c2e8ddd308
--- /dev/null
+++ b/package_manager/tests/src/Unit/ProcessFactoryTest.php
@@ -0,0 +1,37 @@
+<?php
+
+namespace Drupal\Tests\package_manager\Unit;
+
+use Drupal\package_manager\ProcessFactory;
+use Drupal\Tests\UnitTestCase;
+
+/**
+ * @coversDefaultClass \Drupal\package_manager\ProcessFactory
+ *
+ * @group automatic_updates
+ */
+class ProcessFactoryTest extends UnitTestCase {
+
+  /**
+   * Tests that the process factory prepends the PHP directory to PATH.
+   */
+  public function testPhpDirectoryPrependedToPath(): void {
+    $factory = new ProcessFactory(
+      $this->prophesize('\Drupal\Core\File\FileSystemInterface')->reveal(),
+      $this->getConfigFactoryStub()
+    );
+
+    // Ensure that the directory of the PHP interpreter can be found.
+    $reflector = new \ReflectionObject($factory);
+    $method = $reflector->getMethod('getPhpDirectory');
+    $method->setAccessible(TRUE);
+    $php_dir = $method->invoke(NULL);
+    $this->assertNotEmpty($php_dir);
+
+    // The process factory should always put the PHP interpreter's directory
+    // at the beginning of the PATH environment variable.
+    $env = $factory->create(['whoami'])->getEnv();
+    $this->assertStringStartsWith("$php_dir:", $env['PATH']);
+  }
+
+}
-- 
GitLab