Repository: symfony/flex (php)

Issue:
Remove runtime check of the PHP version from autoload
These checks are now part of Composer (since https://github.com/composer/composer/pull/8546), so we can revert #576 from Flex.

For ref: https://github.com/composer/composer/issues/9967#issuecomment-858462117

Relates to #708 as well

Pull request:
removed unnecessary code
Fixes #775

Removed code that was implemented in #576 as this is no longer needed as per the issue reported.

First PR in this repository. Hoping to contribute to more! If there are any issues, let me know.

Patch:
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index eecf859..49a1605 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -11,22 +11,24 @@ env:
 
 jobs:
     tests:
-        name: "PHP ${{ matrix.php }} ${{ matrix.mode }}"
+        name: "PHP ${{ matrix.php-version }} + ${{ matrix.dependencies }}"
 
         runs-on: ubuntu-latest
 
         strategy:
             fail-fast: false
             matrix:
+                php-version:
+                    - '7.1'
+                    - '7.2'
+                    - '7.3'
+                    - '7.4'
+                    - '8.0'
+                dependencies:
+                    - 'highest'
                 include:
-                  - php: '7.1'
-                  - php: '7.2'
-                  - php: '7.3'
-                  - php: '7.4'
-                  - php: '8.0'
-                  - php: '8.1'
-                  - php: '7.4'
-                    mode: low-deps
+                    - php-version: '7.1'
+                      dependencies: 'lowest'
 
         steps:
             - name: "Checkout code"
@@ -36,37 +38,37 @@ jobs:
               uses: shivammathur/setup-php@2.7.0
               with:
                   coverage: "none"
-                  php-version: ${{ matrix.php }}
+                  php-version: ${{ matrix.php-version }}
                   tools: composer:v2
 
             - name: "Validate composer.json"
               run: "composer validate --strict --no-check-lock"
 
-            - run: |
-                composer require --no-update composer/composer:^1.0.2 --ansi
+            - name: "Add PHPUnit matcher"
+              run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
 
-                if [[ "${{ matrix.mode }}" = low-deps ]]; then
-                    composer u --prefer-lowest --prefer-stable --ansi
-                else
-                    composer u --ansi
-                fi
+            - run: composer require --no-update composer/composer:^1.0.2
+
+            - uses: "ramsey/composer-install@v1"
+              with:
+                  dependency-versions: "${{ matrix.dependencies }}"
 
             - name: "Install PHPUnit"
               run: vendor/bin/simple-phpunit install
 
+            - name: "PHPUnit version"
+              run: vendor/bin/simple-phpunit --version
+
             - run: vendor/bin/simple-phpunit
 
-            - run: |
-                composer require --no-update composer/composer:^2 --ansi
+            - run: composer require --no-update composer/composer:^2
 
-                if [[ "${{ matrix.mode }}" = low-deps ]]; then
-                    composer u --prefer-lowest --prefer-stable --ansi
-                else
-                    composer u --ansi
-                fi
+            - uses: "ramsey/composer-install@v1"
+              with:
+                  dependency-versions: "${{ matrix.dependencies }}"
 
             - run: vendor/bin/simple-phpunit
 
-            - if: matrix.php == '7.1'
+            - if: matrix.php-version == '7.1'
               name: "Lint PHP files"
               run: find src/ -name '*.php' | xargs -n1 php -l
diff --git a/composer.json b/composer.json
index 5c98fd1..81d16a1 100644
--- a/composer.json
+++ b/composer.json
@@ -18,7 +18,7 @@
         "composer/composer": "^1.0.2|^2.0",
         "symfony/dotenv": "^4.4|^5.0",
         "symfony/filesystem": "^4.4|^5.0",
-        "symfony/phpunit-bridge": "^4.4.12|^5.0",
+        "symfony/phpunit-bridge": "^4.4|^5.0",
         "symfony/process": "^3.4|^4.4|^5.0"
     },
     "autoload": {
diff --git a/src/Flex.php b/src/Flex.php
index 9388a2e..b402760 100644
--- a/src/Flex.php
+++ b/src/Flex.php
@@ -122,7 +122,7 @@ class Flex implements PluginInterface, EventSubscriberInterface
         $this->config = $composer->getConfig();
         $this->options = $this->initOptions();
 
-        $symfonyRequire = preg_replace('/\.x$/', '.x-dev', getenv('SYMFONY_REQUIRE') ?: ($composer->getPackage()->getExtra()['symfony']['require'] ?? ''));
+        $symfonyRequire = preg_replace('/\.x$/', '.x-dev', getenv('SYMFONY_REQUIRE') ?: ($composer->getPackage()->getExtra()['symfony']['require'] ?? null));
 
         if ($composer2 = version_compare('2.0.0', PluginInterface::PLUGIN_API_VERSION, '<=')) {
             $rfs = Factory::createHttpDownloader($this->io, $this->config);
@@ -307,17 +307,6 @@ class Flex implements PluginInterface, EventSubscriberInterface
         return $backtrace;
     }
 
-    public function lockPlatform()
-    {
-        if (!$this->downloader->isEnabled()) {
-            return; // "symfony/flex" not found in the root composer.json - don't create the symfony.lock file
-        }
-
-        $this->lock->set('php', [
-            'version' => $this->config->get('platform')['php'] ?? (\PHP_MAJOR_VERSION.'.'.\PHP_MINOR_VERSION),
-        ]);
-    }
-
     public function configureProject(Event $event)
     {
         if (!$this->downloader->isEnabled()) {
@@ -700,40 +689,6 @@ class Flex implements PluginInterface, EventSubscriberInterface
         }
     }
 
-    public function updateAutoloadFile()
-    {
-        if (!$platform = $this->lock->get('php')['version'] ?? null) {
-            return;
-        }
-
-        $autoloadFile = $this->config->get('vendor-dir').'/autoload.php';
-
-        if (!file_exists($autoloadFile)) {
-            return;
-        }
-
-        $code = file_get_contents($autoloadFile);
-        $code = substr($code, \strlen("<?php\n"));
-
-        if (false !== strpos($code, 'PHP_VERSION_ID')) {
-            return;
-        }
-
-        $platform = preg_replace('/[^-+.~_\w]/', '', $platform);
-        $version = sprintf('%d%02d00', ...explode('.', $platform.'.0'));
-
-        file_put_contents($autoloadFile, <<<EOPHP
-<?php
-
-if (PHP_VERSION_ID < $version) {
-    echo sprintf("Fatal Error: composer.lock was created for PHP version $platform or higher but the current PHP version is %d.%d.%s.\\n", PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION);
-    exit(1);
-}
-$code
-EOPHP
-        );
-    }
-
     /**
      * @return Recipe[]
      */
@@ -1010,14 +965,13 @@ EOPHP
             ScriptEvents::POST_INSTALL_CMD => 'install',
             ScriptEvents::PRE_UPDATE_CMD => 'configureInstaller',
             ScriptEvents::POST_UPDATE_CMD => 'update',
-            ScriptEvents::POST_AUTOLOAD_DUMP => 'updateAutoloadFile',
             'auto-scripts' => 'executeAutoScripts',
         ];
 
         if (version_compare('2.0.0', PluginInterface::PLUGIN_API_VERSION, '>')) {
             $events += [
                 InstallerEvents::PRE_DEPENDENCIES_SOLVING => [['populateProvidersCacheDir', \PHP_INT_MAX]],
-                InstallerEvents::POST_DEPENDENCIES_SOLVING => [['populateFilesCacheDir', \PHP_INT_MAX], ['lockPlatform']],
+                InstallerEvents::POST_DEPENDENCIES_SOLVING => [['populateFilesCacheDir', \PHP_INT_MAX]],
                 PackageEvents::PRE_PACKAGE_INSTALL => [['populateFilesCacheDir', ~\PHP_INT_MAX]],
                 PackageEvents::PRE_PACKAGE_UPDATE => [['populateFilesCacheDir', ~\PHP_INT_MAX]],
                 PluginEvents::PRE_FILE_DOWNLOAD => 'onFileDownload',
diff --git a/src/PackageResolver.php b/src/PackageResolver.php
index 985f009..12e2d6a 100644
--- a/src/PackageResolver.php
+++ b/src/PackageResolver.php
@@ -31,20 +31,46 @@ class PackageResolver
 
     public function resolve(array $arguments = [], bool $isRequire = false): array
     {
-        // first pass split on : and = to resolve package names
-        $packages = [];
-        foreach ($arguments as $i => $argument) {
+        $versionParser = new VersionParser();
+
+        // first pass split on : and = to separate package names and versions
+        $explodedArguments = [];
+        foreach ($arguments as $argument) {
             if ((false !== $pos = strpos($argument, ':')) || (false !== $pos = strpos($argument, '='))) {
-                $package = $this->resolvePackageName(substr($argument, 0, $pos), $i);
-                $version = substr($argument, $pos + 1);
-                $packages[] = $package.':'.$version;
+                $explodedArguments[] = substr($argument, 0, $pos);
+                $explodedArguments[] = substr($argument, $pos + 1);
             } else {
-                $packages[] = $this->resolvePackageName($argument, $i);
+                $explodedArguments[] = $argument;
             }
         }
 
-        // second pass to resolve versions
-        $versionParser = new VersionParser();
+        // second pass to resolve package names
+        $packages = [];
+        foreach ($explodedArguments as $i => $argument) {
+            if (false === strpos($argument, '/') && !preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $argument) && !preg_match('{(?<=[a-z0-9_/-])\*|\*(?=[a-z0-9_/-])}i', $argument) && !\in_array($argument, ['mirrors', 'nothing'])) {
+                if (null === self::$aliases) {
+                    self::$aliases = $this->downloader->get('/aliases.json')->getBody();
+                }
+
+                if (isset(self::$aliases[$argument])) {
+                    $argument = self::$aliases[$argument];
+                } else {
+                    // is it a version or an alias that does not exist?
+                    try {
+                        $versionParser->parseConstraints($argument);
+                    } catch (\UnexpectedValueException $e) {
+                        // is it a special Symfony version?
+                        if (!\in_array($argument, self::$SYMFONY_VERSIONS, true)) {
+                            $this->throwAlternatives($argument, $i);
+                        }
+                    }
+                }
+            }
+
+            $packages[] = $argument;
+        }
+
+        // third pass to resolve versions
         $requires = [];
         foreach ($versionParser->parseNameVersionPairs($packages) as $package) {
             $requires[] = $package['name'].$this->parseVersion($package['name'], $package['version'] ?? '', $isRequire);
@@ -85,34 +111,6 @@ class PackageResolver
         return ':'.$version;
     }
 
-    private function resolvePackageName(string $argument, int $position): string
-    {
-        if (false !== strpos($argument, '/') || preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $argument) || preg_match('{(?<=[a-z0-9_/-])\*|\*(?=[a-z0-9_/-])}i', $argument) || \in_array($argument, ['mirrors', 'nothing'])) {
-            return $argument;
-        }
-
-        if (null === self::$aliases) {
-            self::$aliases = $this->downloader->get('/aliases.json')->getBody();
-        }
-
-        if (isset(self::$aliases[$argument])) {
-            $argument = self::$aliases[$argument];
-        } else {
-            // is it a version or an alias that does not exist?
-            try {
-                $versionParser = new VersionParser();
-                $versionParser->parseConstraints($argument);
-            } catch (\UnexpectedValueException $e) {
-                // is it a special Symfony version?
-                if (!\in_array($argument, self::$SYMFONY_VERSIONS, true)) {
-                    $this->throwAlternatives($argument, $position);
-                }
-            }
-        }
-
-        return $argument;
-    }
-
     /**
      * @throws \UnexpectedValueException
      */


Test patch:
diff --git a/tests/Configurator/CopyDirectoryFromPackageConfiguratorTest.php b/tests/Configurator/CopyDirectoryFromPackageConfiguratorTest.php
index aa7e0e2..b09bc8c 100644
--- a/tests/Configurator/CopyDirectoryFromPackageConfiguratorTest.php
+++ b/tests/Configurator/CopyDirectoryFromPackageConfiguratorTest.php
@@ -44,7 +44,7 @@ class CopyDirectoryFromPackageConfiguratorTest extends TestCase
         }
 
         foreach ($this->targetFiles as $targetFile) {
-            $this->assertFileDoesNotExist($targetFile);
+            $this->assertFileNotExists($targetFile);
         }
         $lock = $this->getMockBuilder(Lock::class)->disableOriginalConstructor()->getMock();
         $this->createConfigurator()->configure($this->recipe, [
diff --git a/tests/Configurator/CopyFromPackageConfiguratorTest.php b/tests/Configurator/CopyFromPackageConfiguratorTest.php
index 8933121..d5fdccc 100644
--- a/tests/Configurator/CopyFromPackageConfiguratorTest.php
+++ b/tests/Configurator/CopyFromPackageConfiguratorTest.php
@@ -94,7 +94,7 @@ class CopyFromPackageConfiguratorTest extends TestCase
         $this->io->expects($this->at(1))->method('writeError')->with(['      Created <fg=green>"./public/"</>']);
         $this->io->expects($this->at(2))->method('writeError')->with(['      Created <fg=green>"./public/file"</>']);
 
-        $this->assertFileDoesNotExist($this->targetFile);
+        $this->assertFileNotExists($this->targetFile);
         $lock = $this->getMockBuilder(Lock::class)->disableOriginalConstructor()->getMock();
         $this->createConfigurator()->configure($this->recipe, [$this->sourceFileRelativePath => $this->targetFileRelativePath], $lock);
         $this->assertFileExists($this->targetFile);
@@ -112,12 +112,12 @@ class CopyFromPackageConfiguratorTest extends TestCase
         $this->assertFileExists($this->targetFile);
         $lock = $this->getMockBuilder(Lock::class)->disableOriginalConstructor()->getMock();
         $this->createConfigurator()->unconfigure($this->recipe, [$this->sourceFileRelativePath => $this->targetFileRelativePath], $lock);
-        $this->assertFileDoesNotExist($this->targetFile);
+        $this->assertFileNotExists($this->targetFile);
     }
 
     public function testNoFilesRemoved()
     {
-        $this->assertFileDoesNotExist($this->targetFile);
+        $this->assertFileNotExists($this->targetFile);
         $this->io->expects($this->exactly(1))->method('writeError')->with(['    Removing files from package']);
         $lock = $this->getMockBuilder(Lock::class)->disableOriginalConstructor()->getMock();
         $this->createConfigurator()->unconfigure($this->recipe, [$this->sourceFileRelativePath => $this->targetFileRelativePath], $lock);
diff --git a/tests/Configurator/CopyFromRecipeConfiguratorTest.php b/tests/Configurator/CopyFromRecipeConfiguratorTest.php
index 00518b3..6c811ed 100644
--- a/tests/Configurator/CopyFromRecipeConfiguratorTest.php
+++ b/tests/Configurator/CopyFromRecipeConfiguratorTest.php
@@ -85,7 +85,7 @@ class CopyFromRecipeConfiguratorTest extends TestCase
         $this->io->expects($this->at(0))->method('writeError')->with(['    Copying files from recipe']);
         $this->io->expects($this->at(1))->method('writeError')->with(['      Created <fg=green>"./config/file"</>']);
 
-        $this->assertFileDoesNotExist($this->targetFile);
+        $this->assertFileNotExists($this->targetFile);
         $lock = $this->getMockBuilder(Lock::class)->disableOriginalConstructor()->getMock();
         $this->createConfigurator()->configure(
             $this->recipe,
@@ -123,12 +123,12 @@ class CopyFromRecipeConfiguratorTest extends TestCase
         $this->assertFileExists($this->targetFile);
         $lock = $this->getMockBuilder(Lock::class)->disableOriginalConstructor()->getMock();
         $this->createConfigurator()->unconfigure($this->recipe, [$this->targetFileRelativePath], $lock);
-        $this->assertFileDoesNotExist($this->targetFile);
+        $this->assertFileNotExists($this->targetFile);
     }
 
     public function testNoFilesRemoved()
     {
-        $this->assertFileDoesNotExist($this->targetFile);
+        $this->assertFileNotExists($this->targetFile);
         $this->io->expects($this->exactly(1))->method('writeError')->with(['    Removing files from recipe']);
         $lock = $this->getMockBuilder(Lock::class)->disableOriginalConstructor()->getMock();
         $this->createConfigurator()->unconfigure($this->recipe, [$this->sourceFileRelativePath => $this->targetFileRelativePath], $lock);
diff --git a/tests/Configurator/EnvConfiguratorTest.php b/tests/Configurator/EnvConfiguratorTest.php
index f65ca5b..bc6fd79 100644
--- a/tests/Configurator/EnvConfiguratorTest.php
+++ b/tests/Configurator/EnvConfiguratorTest.php
@@ -181,19 +181,19 @@ EOF
         ], $lock);
 
         $envContents = file_get_contents($env);
-        $this->assertMatchesRegularExpression('/#TRUSTED_SECRET_1=[a-z0-9]{64}/', $envContents);
-        $this->assertMatchesRegularExpression('/#TRUSTED_SECRET_2=[a-z0-9]{64}/', $envContents);
-        $this->assertMatchesRegularExpression('/#TRUSTED_SECRET_3=[a-z0-9]{64}/', $envContents);
-        $this->assertMatchesRegularExpression('/APP_SECRET=[a-z0-9]{32}/', $envContents);
+        $this->assertRegExp('/#TRUSTED_SECRET_1=[a-z0-9]{64}/', $envContents);
+        $this->assertRegExp('/#TRUSTED_SECRET_2=[a-z0-9]{64}/', $envContents);
+        $this->assertRegExp('/#TRUSTED_SECRET_3=[a-z0-9]{64}/', $envContents);
+        $this->assertRegExp('/APP_SECRET=[a-z0-9]{32}/', $envContents);
         @unlink($env);
 
         foreach ([$phpunitDist, $phpunit] as $file) {
             $fileContents = file_get_contents($file);
 
-            $this->assertMatchesRegularExpression('/<!-- env name="TRUSTED_SECRET_1" value="[a-z0-9]{64}" -->/', $fileContents);
-            $this->assertMatchesRegularExpression('/<!-- env name="TRUSTED_SECRET_2" value="[a-z0-9]{64}" -->/', $fileContents);
-            $this->assertMatchesRegularExpression('/<!-- env name="TRUSTED_SECRET_3" value="[a-z0-9]{64}" -->/', $fileContents);
-            $this->assertMatchesRegularExpression('/<env name="APP_SECRET" value="[a-z0-9]{32}"\/>/', $fileContents);
+            $this->assertRegExp('/<!-- env name="TRUSTED_SECRET_1" value="[a-z0-9]{64}" -->/', $fileContents);
+            $this->assertRegExp('/<!-- env name="TRUSTED_SECRET_2" value="[a-z0-9]{64}" -->/', $fileContents);
+            $this->assertRegExp('/<!-- env name="TRUSTED_SECRET_3" value="[a-z0-9]{64}" -->/', $fileContents);
+            $this->assertRegExp('/<env name="APP_SECRET" value="[a-z0-9]{32}"\/>/', $fileContents);
         }
     }
 
diff --git a/tests/PackageResolverTest.php b/tests/PackageResolverTest.php
index 7926484..dc06709 100644
--- a/tests/PackageResolverTest.php
+++ b/tests/PackageResolverTest.php
@@ -31,10 +31,6 @@ class PackageResolverTest extends TestCase
                 ['cli'],
                 ['symfony/console'],
             ],
-            [
-                ['cli', 'symfony/workflow'],
-                ['symfony/console', 'symfony/workflow'],
-            ],
             [
                 ['console', 'validator', 'translation'],
                 ['symfony/console', 'symfony/validator', 'symfony/translation'],
@@ -47,10 +43,6 @@ class PackageResolverTest extends TestCase
                 ['cli:lts', 'validator=3.2', 'translation', 'next'],
                 ['symfony/console:^3.4', 'symfony/validator:3.2', 'symfony/translation:^4.0@dev'],
             ],
-            [
-                ['cli:dev-feature/abc'],
-                ['symfony/console:dev-feature/abc'],
-            ],
             [
                 ['php'],
                 ['php'],
@@ -91,6 +83,10 @@ class PackageResolverTest extends TestCase
                 ['qwerty'],
                 '"qwerty" is not a valid alias.',
             ],
+            [
+                ['lts:'],
+                'Could not parse version constraint "".',
+            ],
         ];
     }