diff --git a/.github/workflows/requirement-checker.yaml b/.github/workflows/requirement-checker.yaml index 9b684435a..35a4ea0c2 100644 --- a/.github/workflows/requirement-checker.yaml +++ b/.github/workflows/requirement-checker.yaml @@ -195,6 +195,8 @@ jobs: docker-image: ghcr.io/box-project/box_php725 - command: _test_e2e_pass_complete_requirement_checker_not_disabled docker-image: ghcr.io/box-project/box_php725 + - command: _test_e2e_fail_conflict + docker-image: ghcr.io/box-project/box_php81 steps: - name: Checkout uses: actions/checkout@v3 diff --git a/requirement-checker/Makefile b/requirement-checker/Makefile index cb7528939..ae315cce1 100644 --- a/requirement-checker/Makefile +++ b/requirement-checker/Makefile @@ -167,7 +167,7 @@ terminal_copy: $(ACTUAL_TERMINAL_DIFF) include Makefile.e2e .PHONY: test_e2e -test_e2e: docker_images _test_e2e_pass_no_config_min_composer_php _test_e2e_pass_no_config_min_box_php _test_e2e_pass_complete_min_composer_php _test_e2e_pass_complete_min_box_php _test_e2e_fail_complete_min_composer_php _test_e2e_fail_complete_min_box_php _test_e2e_skip_min_composer_php _test_e2e_pass_complete_requirement_checker_not_disabled +test_e2e: docker_images _test_e2e_pass_no_config_min_composer_php _test_e2e_pass_no_config_min_box_php _test_e2e_pass_complete_min_composer_php _test_e2e_pass_complete_min_box_php _test_e2e_fail_complete_min_composer_php _test_e2e_fail_complete_min_box_php _test_e2e_skip_min_composer_php _test_e2e_pass_complete_requirement_checker_not_disabled _test_e2e_fail_conflict # diff --git a/requirement-checker/Makefile.e2e b/requirement-checker/Makefile.e2e index ab1ef9fc2..e95f6e48c 100644 --- a/requirement-checker/Makefile.e2e +++ b/requirement-checker/Makefile.e2e @@ -58,6 +58,17 @@ E2E_TEST_FAIL_COMPLETE_MIN_BOX_EXPECTED_STDERR_TEMPLATE := $(E2E_TEST_FAIL_COMPL E2E_TEST_FAIL_COMPLETE_ACTUAL_STDOUT := $(E2E_TEST_FAIL_COMPLETE_OUTPUT_DIR)/actual-stdout E2E_TEST_FAIL_COMPLETE_ACTUAL_STDERR := $(E2E_TEST_FAIL_COMPLETE_OUTPUT_DIR)/actual-stderr +E2E_TEST_FAIL_CONFLICT_DIR := fixtures/fail-conflict +E2E_TEST_FAIL_CONFLICT_OUTPUT_DIR := dist/fixtures/fail-conflict +E2E_TEST_FAIL_CONFLICT_VENDOR := $(E2E_TEST_FAIL_CONFLICT_DIR)/vendor +E2E_TEST_FAIL_CONFLICT_PHAR := $(E2E_TEST_FAIL_CONFLICT_OUTPUT_DIR)/index.phar +E2E_TEST_FAIL_CONFLICT_PHAR_SRC := $(shell find $(E2E_TEST_FAIL_CONFLICT_DIR)) +E2E_TEST_FAIL_CONFLICT_MIN_BOX_EXPECTED_STDOUT := $(E2E_TEST_FAIL_CONFLICT_DIR)/expected-stdout +E2E_TEST_FAIL_CONFLICT_MIN_BOX_EXPECTED_STDERR := $(E2E_TEST_FAIL_CONFLICT_OUTPUT_DIR)/expected-boxmin-stderr +E2E_TEST_FAIL_CONFLICT_MIN_BOX_EXPECTED_STDERR_TEMPLATE := $(E2E_TEST_FAIL_CONFLICT_DIR)/expected-boxmin-stderr.dist +E2E_TEST_FAIL_CONFLICT_ACTUAL_STDOUT := $(E2E_TEST_FAIL_CONFLICT_OUTPUT_DIR)/actual-stdout +E2E_TEST_FAIL_CONFLICT_ACTUAL_STDERR := $(E2E_TEST_FAIL_CONFLICT_OUTPUT_DIR)/actual-stderr + E2E_TEST_SKIP_DIR := fixtures/fail-complete E2E_TEST_SKIP_OUTPUT_DIR := dist/fixtures/skip E2E_TEST_SKIP_PHAR := $(E2E_TEST_SKIP_OUTPUT_DIR)/index.phar @@ -181,7 +192,7 @@ test_e2e_pass_complete_requirement_checker_not_disabled: docker_images _test_e2e .PHONY: _test_e2e_pass_complete_requirement_checker_not_disabled _test_e2e_pass_complete_requirement_checker_not_disabled: $(E2E_TEST_PASS_COMPLETE_PHAR) - @echo "$(YELLOW_COLOR)Test RequirementChecker with a project with satisfied requirements (min PHP version supported by Box).$(NO_COLOR)" + @echo "$(YELLOW_COLOR)Test RequirementChecker with a project with satisfied requirements with requirement checker not disabled.$(NO_COLOR)" @rm \ $(E2E_TEST_PASS_COMPLETE_ACTUAL_STDOUT) \ $(E2E_TEST_PASS_COMPLETE_ACTUAL_STDERR) \ @@ -256,6 +267,31 @@ _test_e2e_fail_complete_min_box_php: $(E2E_TEST_FAIL_COMPLETE_PHAR) $(E2E_TEST_FAIL_COMPLETE_ACTUAL_STDOUT) +.PHONY: test_e2e_fail_conflict +test_e2e_fail_conflict: docker_images _test_e2e_fail_conflict + +.PHONY: _test_e2e_fail_conflict +_test_e2e_fail_conflict: $(E2E_TEST_FAIL_CONFLICT_PHAR) + @echo "$(YELLOW_COLOR)Test RequirementChecker with a project with non-satisfied requirements (conflicting extension loaded).$(NO_COLOR)" + @rm \ + $(E2E_TEST_FAIL_CONFLICT_ACTUAL_STDOUT) \ + $(E2E_TEST_FAIL_CONFLICT_ACTUAL_STDERR) \ + $(E2E_TEST_FAIL_CONFLICT_MIN_BOX_EXPECTED_STDERR) || true + @$(MAKE) $(E2E_TEST_FAIL_CONFLICT_MIN_BOX_EXPECTED_STDERR) + + $(DOCKER_RUN) \ + --volume="$$PWD/$(E2E_TEST_FAIL_CONFLICT_OUTPUT_DIR)":/opt/box \ + $(DOCKER_MIN_BOX_PHP_VERSION_RUN_COMMAND) 1>$(E2E_TEST_FAIL_CONFLICT_ACTUAL_STDOUT) 2>$(E2E_TEST_FAIL_CONFLICT_ACTUAL_STDERR) \ + || true + + $(DIFF) \ + $(E2E_TEST_FAIL_CONFLICT_MIN_BOX_EXPECTED_STDERR) \ + $(E2E_TEST_FAIL_CONFLICT_ACTUAL_STDERR) + $(DIFF) \ + $(E2E_TEST_FAIL_CONFLICT_MIN_BOX_EXPECTED_STDOUT) \ + $(E2E_TEST_FAIL_CONFLICT_ACTUAL_STDOUT) + + # # Skip the requirement check #--------------------------------------------------------------------------- @@ -345,6 +381,18 @@ $(E2E_TEST_FAIL_COMPLETE_MIN_BOX_EXPECTED_STDERR): $(E2E_TEST_FAIL_COMPLETE_OUTP $(E2E_TEST_FAIL_COMPLETE_MIN_BOX_EXPECTED_STDERR_TEMPLATE) \ > $@ +$(E2E_TEST_FAIL_CONFLICT_PHAR): $(SCOPED_BOX_BIN) $(E2E_TEST_FAIL_CONFLICT_PHAR_SRC) + $(SCOPED_BOX) compile --ansi --working-dir=$(E2E_TEST_FAIL_CONFLICT_DIR) --no-parallel + mkdir -p $(E2E_TEST_FAIL_CONFLICT_OUTPUT_DIR) + mv $(E2E_TEST_FAIL_CONFLICT_DIR)/index.phar $(E2E_TEST_FAIL_CONFLICT_PHAR) + touch -c $(E2E_TEST_FAIL_CONFLICT_PHAR) +$(E2E_TEST_FAIL_CONFLICT_VENDOR): $(E2E_TEST_FAIL_CONFLICT_DIR)/composer.lock +$(E2E_TEST_FAIL_CONFLICT_DIR)/composer.lock: $(E2E_TEST_FAIL_CONFLICT_DIR)/composer.json +$(E2E_TEST_FAIL_CONFLICT_MIN_BOX_EXPECTED_STDERR): $(E2E_TEST_FAIL_CONFLICT_OUTPUT_DIR) $(E2E_TEST_FAIL_CONFLICT_MIN_BOX_EXPECTED_STDERR_TEMPLATE) + sed "s/PHP_VERSION/$$($(DOCKER_RUN) $(DOCKER_MIN_BOX_PHP_VERSION_IMAGE_TAG) php -r 'echo PHP_VERSION;')/" \ + $(E2E_TEST_FAIL_CONFLICT_MIN_BOX_EXPECTED_STDERR_TEMPLATE) \ + > $@ + $(E2E_TEST_SKIP_OUTPUT_DIR): mkdir -p $@ touch -c $@ diff --git a/requirement-checker/fixtures/fail-conflict/composer.json b/requirement-checker/fixtures/fail-conflict/composer.json new file mode 100644 index 000000000..bebc027fb --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/composer.json @@ -0,0 +1,8 @@ +{ + "require": { + "ext-phar": "*" + }, + "conflict": { + "ext-pdo" : "*" + } +} diff --git a/requirement-checker/fixtures/fail-conflict/composer.lock b/requirement-checker/fixtures/fail-conflict/composer.lock new file mode 100644 index 000000000..62a613f22 --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/composer.lock @@ -0,0 +1,20 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "93756b503a85907c1d008537b4f0373b", + "packages": [], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "ext-phar": "*" + }, + "platform-dev": [], + "plugin-api-version": "2.3.0" +} diff --git a/requirement-checker/fixtures/fail-conflict/expected-boxmin-stderr.dist b/requirement-checker/fixtures/fail-conflict/expected-boxmin-stderr.dist new file mode 100644 index 000000000..f7a4200ac --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/expected-boxmin-stderr.dist @@ -0,0 +1,21 @@ + +Box Requirements Checker +======================== + +> Using PHP PHP_VERSION +> PHP is using the following php.ini file: + WARNING: No configuration file (php.ini) used by PHP! + +> Checking Box requirements: + ✔ The application requires the extension "phar". + ✘ The application conflicts with the extension "pdo". + + + [ERROR] Your system is not ready to run the application. + + +Fix the following mandatory requirements: +========================================= + + * The application conflicts with the extension "pdo". + diff --git a/requirement-checker/fixtures/fail-conflict/expected-stdout b/requirement-checker/fixtures/fail-conflict/expected-stdout new file mode 100644 index 000000000..e69de29bb diff --git a/requirement-checker/fixtures/fail-conflict/index.php b/requirement-checker/fixtures/fail-conflict/index.php new file mode 100644 index 000000000..a20ea3fa5 --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/index.php @@ -0,0 +1,13 @@ + + * Théo Fidry + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +throw new Exception('Should not be executed!'); diff --git a/requirement-checker/fixtures/fail-conflict/vendor/autoload.php b/requirement-checker/fixtures/fail-conflict/vendor/autoload.php new file mode 100644 index 000000000..b1162d2a1 --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/vendor/autoload.php @@ -0,0 +1,25 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var ?string */ + private $vendorDir; + + // PSR-4 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array[] + * @psalm-var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixesPsr0 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var string[] + * @psalm-var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var bool[] + * @psalm-var array + */ + private $missingClasses = array(); + + /** @var ?string */ + private $apcuPrefix; + + /** + * @var self[] + */ + private static $registeredLoaders = array(); + + /** + * @param ?string $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return string[] + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array[] + * @psalm-return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return string[] Array of classname => path + * @psalm-return array + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param string[] $classMap Class to filename map + * @psalm-param array $classMap + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + $includeFile = self::$includeFile; + $includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders indexed by their corresponding vendor directories. + * + * @return self[] + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } + + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } +} diff --git a/requirement-checker/fixtures/fail-conflict/vendor/composer/InstalledVersions.php b/requirement-checker/fixtures/fail-conflict/vendor/composer/InstalledVersions.php new file mode 100644 index 000000000..c6b54af7b --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/vendor/composer/InstalledVersions.php @@ -0,0 +1,352 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']); + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints($constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php'; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = require __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + $installed[] = self::$installed; + + return $installed; + } +} diff --git a/requirement-checker/fixtures/fail-conflict/vendor/composer/LICENSE b/requirement-checker/fixtures/fail-conflict/vendor/composer/LICENSE new file mode 100644 index 000000000..f27399a04 --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/requirement-checker/fixtures/fail-conflict/vendor/composer/autoload_classmap.php b/requirement-checker/fixtures/fail-conflict/vendor/composer/autoload_classmap.php new file mode 100644 index 000000000..0fb0a2c19 --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/vendor/composer/autoload_classmap.php @@ -0,0 +1,10 @@ + $vendorDir . '/composer/InstalledVersions.php', +); diff --git a/requirement-checker/fixtures/fail-conflict/vendor/composer/autoload_namespaces.php b/requirement-checker/fixtures/fail-conflict/vendor/composer/autoload_namespaces.php new file mode 100644 index 000000000..15a2ff3ad --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ +register(true); + + return $loader; + } +} diff --git a/requirement-checker/fixtures/fail-conflict/vendor/composer/autoload_static.php b/requirement-checker/fixtures/fail-conflict/vendor/composer/autoload_static.php new file mode 100644 index 000000000..c68c8cbb4 --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/vendor/composer/autoload_static.php @@ -0,0 +1,20 @@ + __DIR__ . '/..' . '/composer/InstalledVersions.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->classMap = ComposerStaticInitb25b42e01280328343dc4cbf40125bce::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/requirement-checker/fixtures/fail-conflict/vendor/composer/installed.json b/requirement-checker/fixtures/fail-conflict/vendor/composer/installed.json new file mode 100644 index 000000000..87fda747e --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/vendor/composer/installed.json @@ -0,0 +1,5 @@ +{ + "packages": [], + "dev": true, + "dev-package-names": [] +} diff --git a/requirement-checker/fixtures/fail-conflict/vendor/composer/installed.php b/requirement-checker/fixtures/fail-conflict/vendor/composer/installed.php new file mode 100644 index 000000000..24662a379 --- /dev/null +++ b/requirement-checker/fixtures/fail-conflict/vendor/composer/installed.php @@ -0,0 +1,23 @@ + array( + 'name' => '__root__', + 'pretty_version' => 'dev-main', + 'version' => 'dev-main', + 'reference' => '987a52d0faa2499d395b2516de4dc803e9794f9a', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => true, + ), + 'versions' => array( + '__root__' => array( + 'pretty_version' => 'dev-main', + 'version' => 'dev-main', + 'reference' => '987a52d0faa2499d395b2516de4dc803e9794f9a', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/requirement-checker/src/Checker.php b/requirement-checker/src/Checker.php index 038fcea27..9b51d8168 100644 --- a/requirement-checker/src/Checker.php +++ b/requirement-checker/src/Checker.php @@ -16,6 +16,7 @@ use InvalidArgumentException; use function count; +use function sprintf; /** * @private @@ -163,6 +164,9 @@ private static function createCondition($type, $condition): IsFulfilled case 'extension': return new IsExtensionFulfilled($condition); + case 'extension-conflict': + return new IsExtensionConflictFulfilled($condition); + default: throw new InvalidArgumentException( sprintf( diff --git a/requirement-checker/src/IsExtensionConflictFulfilled.php b/requirement-checker/src/IsExtensionConflictFulfilled.php new file mode 100644 index 000000000..494b1e261 --- /dev/null +++ b/requirement-checker/src/IsExtensionConflictFulfilled.php @@ -0,0 +1,35 @@ + + * Théo Fidry + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace KevinGH\RequirementChecker; + +use function extension_loaded; + +/** + * @private + */ +final class IsExtensionConflictFulfilled implements IsFulfilled +{ + private $conflictingExtension; + + public function __construct(string $requiredExtension) + { + $this->conflictingExtension = $requiredExtension; + } + + public function __invoke(): bool + { + return !extension_loaded($this->conflictingExtension); + } +} diff --git a/res/requirement-checker/src/Checker.php b/res/requirement-checker/src/Checker.php index a8c2914c3..5a905b5bc 100644 --- a/res/requirement-checker/src/Checker.php +++ b/res/requirement-checker/src/Checker.php @@ -5,6 +5,7 @@ use InvalidArgumentException; use function count; +use function sprintf; final class Checker { private static $requirementsConfig; @@ -92,8 +93,10 @@ private static function createCondition($type, $condition) : IsFulfilled return new IsPhpVersionFulfilled($condition); case 'extension': return new IsExtensionFulfilled($condition); + case 'extension-conflict': + return new IsExtensionConflictFulfilled($condition); default: - throw new InvalidArgumentException(\sprintf('Unknown requirement type "%s".', $type)); + throw new InvalidArgumentException(sprintf('Unknown requirement type "%s".', $type)); } } } diff --git a/res/requirement-checker/src/IsExtensionConflictFulfilled.php b/res/requirement-checker/src/IsExtensionConflictFulfilled.php new file mode 100644 index 000000000..fda9e22d1 --- /dev/null +++ b/res/requirement-checker/src/IsExtensionConflictFulfilled.php @@ -0,0 +1,18 @@ +conflictingExtension = $requiredExtension; + } + public function __invoke() : bool + { + return !extension_loaded($this->conflictingExtension); + } +} diff --git a/res/requirement-checker/vendor/composer/ClassLoader.php b/res/requirement-checker/vendor/composer/ClassLoader.php index fd56bd7d8..a72151c77 100644 --- a/res/requirement-checker/vendor/composer/ClassLoader.php +++ b/res/requirement-checker/vendor/composer/ClassLoader.php @@ -429,7 +429,8 @@ public function unregister() public function loadClass($class) { if ($file = $this->findFile($class)) { - (self::$includeFile)($file); + $includeFile = self::$includeFile; + $includeFile($file); return true; } @@ -560,7 +561,10 @@ private function findFileWithExtension($class, $ext) return false; } - private static function initializeIncludeClosure(): void + /** + * @return void + */ + private static function initializeIncludeClosure() { if (self::$includeFile !== null) { return; @@ -574,8 +578,8 @@ private static function initializeIncludeClosure(): void * @param string $file * @return void */ - self::$includeFile = static function($file) { + self::$includeFile = \Closure::bind(static function($file) { include $file; - }; + }, null, null); } } diff --git a/res/requirement-checker/vendor/composer/autoload_classmap.php b/res/requirement-checker/vendor/composer/autoload_classmap.php index a9e8aa097..3a598f91c 100644 --- a/res/requirement-checker/vendor/composer/autoload_classmap.php +++ b/res/requirement-checker/vendor/composer/autoload_classmap.php @@ -21,6 +21,7 @@ 'HumbugBox420\\Composer\\Semver\\VersionParser' => $vendorDir . '/composer/semver/src/VersionParser.php', 'HumbugBox420\\KevinGH\\RequirementChecker\\Checker' => $baseDir . '/src/Checker.php', 'HumbugBox420\\KevinGH\\RequirementChecker\\IO' => $baseDir . '/src/IO.php', + 'HumbugBox420\\KevinGH\\RequirementChecker\\IsExtensionConflictFulfilled' => $baseDir . '/src/IsExtensionConflictFulfilled.php', 'HumbugBox420\\KevinGH\\RequirementChecker\\IsExtensionFulfilled' => $baseDir . '/src/IsExtensionFulfilled.php', 'HumbugBox420\\KevinGH\\RequirementChecker\\IsFulfilled' => $baseDir . '/src/IsFulfilled.php', 'HumbugBox420\\KevinGH\\RequirementChecker\\IsPhpVersionFulfilled' => $baseDir . '/src/IsPhpVersionFulfilled.php', diff --git a/res/requirement-checker/vendor/composer/autoload_static.php b/res/requirement-checker/vendor/composer/autoload_static.php index 7acdaacf0..e3856d509 100644 --- a/res/requirement-checker/vendor/composer/autoload_static.php +++ b/res/requirement-checker/vendor/composer/autoload_static.php @@ -41,6 +41,7 @@ class ComposerStaticInitHumbugBox420 'HumbugBox420\\Composer\\Semver\\VersionParser' => __DIR__ . '/..' . '/composer/semver/src/VersionParser.php', 'HumbugBox420\\KevinGH\\RequirementChecker\\Checker' => __DIR__ . '/../..' . '/src/Checker.php', 'HumbugBox420\\KevinGH\\RequirementChecker\\IO' => __DIR__ . '/../..' . '/src/IO.php', + 'HumbugBox420\\KevinGH\\RequirementChecker\\IsExtensionConflictFulfilled' => __DIR__ . '/../..' . '/src/IsExtensionConflictFulfilled.php', 'HumbugBox420\\KevinGH\\RequirementChecker\\IsExtensionFulfilled' => __DIR__ . '/../..' . '/src/IsExtensionFulfilled.php', 'HumbugBox420\\KevinGH\\RequirementChecker\\IsFulfilled' => __DIR__ . '/../..' . '/src/IsFulfilled.php', 'HumbugBox420\\KevinGH\\RequirementChecker\\IsPhpVersionFulfilled' => __DIR__ . '/../..' . '/src/IsPhpVersionFulfilled.php', diff --git a/src/RequirementChecker/AppRequirementsFactory.php b/src/RequirementChecker/AppRequirementsFactory.php index 743674cc5..283672ad0 100644 --- a/src/RequirementChecker/AppRequirementsFactory.php +++ b/src/RequirementChecker/AppRequirementsFactory.php @@ -18,6 +18,7 @@ use function array_diff_key; use function array_filter; use function array_map; +use function array_merge_recursive; use function array_values; /** @@ -45,6 +46,9 @@ public static function create( ); } + /** + * @return list + */ private static function retrievePhpVersionRequirements( DecodedComposerJson $composerJson, DecodedComposerLock $composerLock, @@ -95,7 +99,7 @@ private static function configureExtensionRequirements( DecodedComposerLock $composerLock, CompressionAlgorithm $compressionAlgorithm, ): array { - $extensionRequirements = self::collectExtensionRequirements( + [$extensionRequirements, $extensionConflicts] = self::collectExtensionRequirements( $composerJson, $composerLock, $compressionAlgorithm, @@ -110,6 +114,15 @@ private static function configureExtensionRequirements( } } + foreach ($extensionConflicts as $extension => $packages) { + foreach ($packages as $package) { + $requirements[] = Requirement::forConflictingExtension( + $extension, + self::SELF_PACKAGE === $package ? null : $package, + ); + } + } + return $requirements; } @@ -117,7 +130,7 @@ private static function configureExtensionRequirements( * Collects the extension required. It also accounts for the polyfills, i.e. if the polyfill * `symfony/polyfill-mbstring` is provided then the extension `ext-mbstring` will not be required. * - * @return array> Associative array containing the list of extensions required + * @return array{array>, array>} */ private static function collectExtensionRequirements( DecodedComposerJson $composerJson, @@ -138,23 +151,29 @@ private static function collectExtensionRequirements( // If the lock is present it is the authority. If not fallback on the .json. It is pointless to check both // since they will contain redundant information. - [$polyfills, $requirements] = $composerLock->isEmpty() + [$polyfills, $requirements, $conflicts] = $composerLock->isEmpty() ? self::collectComposerJsonExtensionRequirements($composerJson, $requirements) : self::collectComposerLockExtensionRequirements($composerLock, $requirements); - return array_diff_key($requirements, $polyfills); + $jsonConflicts = self::collectComposerJsonExtensionRequirements($composerJson, $requirements)[2]; + + return [ + array_diff_key($requirements, $polyfills), + array_merge_recursive($conflicts, $jsonConflicts), + ]; } /** * @param array> $requirements The key is the extension name and the value the list of sources (app literal string or the package name). * - * @return array{array, array>} + * @return array{array, array>, array>} */ private static function collectComposerJsonExtensionRequirements( DecodedComposerJson $composerJson, array $requirements, ): array { $polyfills = []; + $conflicts = []; foreach ($composerJson->getRequiredItems() as $packageInfo) { $polyfilledExtension = $packageInfo->getPolyfilledExtension(); @@ -170,19 +189,28 @@ private static function collectComposerJsonExtensionRequirements( } } - return [$polyfills, $requirements]; + foreach ($composerJson->getConflictingExtensions() as $extension) { + $conflicts[$extension] = [self::SELF_PACKAGE]; + } + + return [ + $polyfills, + $requirements, + $conflicts, + ]; } /** * @param array> $requirements The key is the extension name and the value the list of sources (app literal string or the package name). * - * @return array{array, array>} + * @return array{array, array>, array>} */ private static function collectComposerLockExtensionRequirements( DecodedComposerLock $composerLock, array $requirements, ): array { $polyfills = []; + $conflicts = []; foreach ($composerLock->getPackages() as $packageInfo) { foreach ($packageInfo->getPolyfilledExtensions() as $polyfilledExtension) { @@ -192,8 +220,12 @@ private static function collectComposerLockExtensionRequirements( foreach ($packageInfo->getRequiredExtensions() as $extension) { $requirements[$extension][] = $packageInfo->getName(); } + + foreach ($packageInfo->getConflictingExtensions() as $extension) { + $conflicts[$extension][] = $packageInfo->getName(); + } } - return [$polyfills, $requirements]; + return [$polyfills, $requirements, $conflicts]; } } diff --git a/src/RequirementChecker/DecodedComposerJson.php b/src/RequirementChecker/DecodedComposerJson.php index d96bc751e..01e0fb953 100644 --- a/src/RequirementChecker/DecodedComposerJson.php +++ b/src/RequirementChecker/DecodedComposerJson.php @@ -50,4 +50,14 @@ public function getRequiredItems(): array array_keys($require), ); } + + /** + * @return list + */ + public function getConflictingExtensions(): array + { + return PackageInfo::parseExtensions( + $this->composerJsonDecodedContents['conflict'] ?? [], + ); + } } diff --git a/src/RequirementChecker/PackageInfo.php b/src/RequirementChecker/PackageInfo.php index e9c3735c1..3ff05aa25 100644 --- a/src/RequirementChecker/PackageInfo.php +++ b/src/RequirementChecker/PackageInfo.php @@ -89,6 +89,16 @@ public function getPolyfilledExtensions(): array return str_starts_with($extension, 'php') ? [] : [$extension]; } + /** + * @return list + */ + public function getConflictingExtensions(): array + { + return array_key_exists('conflict', $this->packageInfo) + ? self::parseExtensions($this->packageInfo['conflict']) + : []; + } + /** * @param array $constraints * diff --git a/src/RequirementChecker/Requirement.php b/src/RequirementChecker/Requirement.php index e57c1c33b..f25b7b187 100644 --- a/src/RequirementChecker/Requirement.php +++ b/src/RequirementChecker/Requirement.php @@ -84,6 +84,35 @@ public static function forRequiredExtension(string $extension, ?string $packageN ); } + public static function forConflictingExtension(string $extension, ?string $packageName): self + { + // TODO: review the message & help message + return new self( + 'extension-conflict', + $extension, + null === $packageName + ? sprintf( + 'The application conflicts with the extension "%s".', + $extension, + ) + : sprintf( + 'The package "%s" conflicts with the extension "%s".', + $packageName, + $extension, + ), + null === $packageName + ? sprintf( + 'The application conflicts with the extension "%s". Disable it.', + $extension, + ) + : sprintf( + 'The package "%s" conflicts with the extension "%s". Disable it.', + $packageName, + $extension, + ), + ); + } + public function toArray(): array { return [ diff --git a/tests/Console/Command/CompileTest.php b/tests/Console/Command/CompileTest.php index 69519b758..1928560c8 100644 --- a/tests/Console/Command/CompileTest.php +++ b/tests/Console/Command/CompileTest.php @@ -85,6 +85,67 @@ class CompileTest extends FileSystemTestCase { use RequiresPharReadonlyOff; + private const NUMBER_OF_FILES = 48; + + private const BOX_FILES = [ + '/.box/', + '/.box/.requirements.php', + '/.box/bin/', + '/.box/bin/check-requirements.php', + '/.box/src/', + '/.box/src/Checker.php', + '/.box/src/IO.php', + '/.box/src/IsExtensionConflictFulfilled.php', + '/.box/src/IsExtensionFulfilled.php', + '/.box/src/IsFulfilled.php', + '/.box/src/IsPhpVersionFulfilled.php', + '/.box/src/Printer.php', + '/.box/src/Requirement.php', + '/.box/src/RequirementCollection.php', + '/.box/src/Terminal.php', + '/.box/vendor/', + '/.box/vendor/autoload.php', + '/.box/vendor/composer/', + '/.box/vendor/composer/ClassLoader.php', + '/.box/vendor/composer/InstalledVersions.php', + '/.box/vendor/composer/installed.php', + '/.box/vendor/composer/LICENSE', + '/.box/vendor/composer/autoload_classmap.php', + '/.box/vendor/composer/autoload_namespaces.php', + '/.box/vendor/composer/autoload_psr4.php', + '/.box/vendor/composer/autoload_real.php', + '/.box/vendor/composer/autoload_static.php', + '/.box/vendor/composer/semver/', + '/.box/vendor/composer/semver/LICENSE', + '/.box/vendor/composer/semver/src/', + '/.box/vendor/composer/semver/src/Comparator.php', + '/.box/vendor/composer/semver/src/CompilingMatcher.php', + '/.box/vendor/composer/semver/src/Constraint/', + '/.box/vendor/composer/semver/src/Constraint/Bound.php', + '/.box/vendor/composer/semver/src/Constraint/Constraint.php', + '/.box/vendor/composer/semver/src/Constraint/ConstraintInterface.php', + '/.box/vendor/composer/semver/src/Constraint/MatchAllConstraint.php', + '/.box/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php', + '/.box/vendor/composer/semver/src/Constraint/MultiConstraint.php', + '/.box/vendor/composer/semver/src/Interval.php', + '/.box/vendor/composer/semver/src/Intervals.php', + '/.box/vendor/composer/semver/src/Semver.php', + '/.box/vendor/composer/semver/src/VersionParser.php', + ]; + + private const COMPOSER_FILES = [ + '/vendor/', + '/vendor/autoload.php', + '/vendor/composer/', + '/vendor/composer/ClassLoader.php', + '/vendor/composer/LICENSE', + '/vendor/composer/autoload_classmap.php', + '/vendor/composer/autoload_namespaces.php', + '/vendor/composer/autoload_psr4.php', + '/vendor/composer/autoload_real.php', + '/vendor/composer/autoload_static.php', + ]; + private const FIXTURES_DIR = __DIR__.'/../../../fixtures/build'; private const DEFAULT_STUB_PATH = __DIR__.'/../../../dist/default_stub.php'; @@ -138,7 +199,7 @@ public function test_it_can_build_a_phar_file(): void $shebang = sprintf('#!%s', (new PhpExecutableFinder())->find()); - $numberOfFiles = 47; + $numberOfFiles = self::NUMBER_OF_FILES; dump_file( 'box.json', @@ -275,48 +336,8 @@ public function test_it_can_build_a_phar_file(): void ); $expectedFiles = [ - '/.box/', - '/.box/.requirements.php', - '/.box/bin/', - '/.box/bin/check-requirements.php', - '/.box/src/', - '/.box/src/Checker.php', - '/.box/src/IO.php', - '/.box/src/IsExtensionFulfilled.php', - '/.box/src/IsFulfilled.php', - '/.box/src/IsPhpVersionFulfilled.php', - '/.box/src/Printer.php', - '/.box/src/Requirement.php', - '/.box/src/RequirementCollection.php', - '/.box/src/Terminal.php', - '/.box/vendor/', - '/.box/vendor/autoload.php', - '/.box/vendor/composer/', - '/.box/vendor/composer/ClassLoader.php', - '/.box/vendor/composer/InstalledVersions.php', - '/.box/vendor/composer/installed.php', - '/.box/vendor/composer/LICENSE', - '/.box/vendor/composer/autoload_classmap.php', - '/.box/vendor/composer/autoload_namespaces.php', - '/.box/vendor/composer/autoload_psr4.php', - '/.box/vendor/composer/autoload_real.php', - '/.box/vendor/composer/autoload_static.php', - '/.box/vendor/composer/semver/', - '/.box/vendor/composer/semver/LICENSE', - '/.box/vendor/composer/semver/src/', - '/.box/vendor/composer/semver/src/Comparator.php', - '/.box/vendor/composer/semver/src/CompilingMatcher.php', - '/.box/vendor/composer/semver/src/Constraint/', - '/.box/vendor/composer/semver/src/Constraint/Bound.php', - '/.box/vendor/composer/semver/src/Constraint/Constraint.php', - '/.box/vendor/composer/semver/src/Constraint/ConstraintInterface.php', - '/.box/vendor/composer/semver/src/Constraint/MatchAllConstraint.php', - '/.box/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php', - '/.box/vendor/composer/semver/src/Constraint/MultiConstraint.php', - '/.box/vendor/composer/semver/src/Interval.php', - '/.box/vendor/composer/semver/src/Intervals.php', - '/.box/vendor/composer/semver/src/Semver.php', - '/.box/vendor/composer/semver/src/VersionParser.php', + ...self::BOX_FILES, + ...self::COMPOSER_FILES, '/one/', '/one/test.php', '/run.php', @@ -325,16 +346,6 @@ public function test_it_can_build_a_phar_file(): void '/test.php', '/two/', '/two/test.png', - '/vendor/', - '/vendor/autoload.php', - '/vendor/composer/', - '/vendor/composer/ClassLoader.php', - '/vendor/composer/LICENSE', - '/vendor/composer/autoload_classmap.php', - '/vendor/composer/autoload_namespaces.php', - '/vendor/composer/autoload_psr4.php', - '/vendor/composer/autoload_real.php', - '/vendor/composer/autoload_static.php', ]; $actualFiles = $this->retrievePharFiles($phar); @@ -409,7 +420,7 @@ public function test_it_can_build_a_phar_without_any_configuration(): void ); $version = get_box_version(); - $expectedNumberOfFiles = 51; + $expectedNumberOfFiles = self::NUMBER_OF_FILES + 4; $expected = <<retrievePharFiles($phar); @@ -834,7 +795,7 @@ public function test_it_can_build_a_phar_file_in_verbose_mode(): void $shebang = sprintf('#!%s', (new PhpExecutableFinder())->find()); $expectedNumberOfClasses = 1; - $expectedNumberOfFiles = 47; + $expectedNumberOfFiles = self::NUMBER_OF_FILES; dump_file( 'box.json', @@ -955,7 +916,7 @@ public function test_it_can_build_a_phar_file_in_very_verbose_mode(): void $shebang = sprintf('#!%s', (new PhpExecutableFinder())->find()); $expectedNumberOfClasses = 1; - $expectedNumberOfFiles = 47; + $expectedNumberOfFiles = self::NUMBER_OF_FILES; dump_file( 'box.json', @@ -2943,7 +2904,7 @@ public function test_it_can_generate_a_phar_with_docker(): void ); $version = get_box_version(); - $expectedNumberOfFiles = 43; + $expectedNumberOfFiles = self::NUMBER_OF_FILES - 4; $expected = << [ + <<<'JSON' + { + "require": { + "php": ">=5.3" + }, + "require-dev": [], + "conflict": { + "ext-psr": "*", + "ext-phar": "*", + "laminas/laminas-code": "<3.3.1" + } + } + JSON, + <<<'JSON' + { + "platform": { + "php": ">=5.4" + }, + "packages": [ + { + "name": "beberlei/assert", + "version": "v2.9.2", + "require": { + "php": ">=5.3" + }, + "require-dev": [], + "conflict": { + "ext-http": "*", + "ext-psr": "*" + } + }, + { + "name": "composer/ca-bundle", + "version": "1.1.0", + "require": {}, + "require-dev": { + "ext-pdo_sqlite3": "*" + }, + "conflict": { + "ext-zlib": "*" + } + } + ] + } + JSON, + CompressionAlgorithm::NONE, + [ + Requirement::forPHP('>=5.4', null), + Requirement::forConflictingExtension('http', 'beberlei/assert'), + Requirement::forConflictingExtension('psr', 'beberlei/assert'), + Requirement::forConflictingExtension('psr', null), + Requirement::forConflictingExtension('zlib', 'composer/ca-bundle'), + Requirement::forConflictingExtension('phar', null), + ], + ]; + yield 'json & lock file packages requirements' => [ <<<'JSON' { diff --git a/tests/RequirementChecker/DecodedComposerJsonTest.php b/tests/RequirementChecker/DecodedComposerJsonTest.php index ac8dee87d..af63d04ed 100644 --- a/tests/RequirementChecker/DecodedComposerJsonTest.php +++ b/tests/RequirementChecker/DecodedComposerJsonTest.php @@ -32,6 +32,7 @@ public function test_it_can_interpret_a_decoded_composer_json_file( ?string $expectedRequiredPhpVersion, bool $expectedHasRequiredPhpVersion, array $expectedRequiredItems, + array $expectedConflictingExtensions, ): void { $actual = new DecodedComposerJson(json_decode($composerJsonContents, true)); @@ -40,6 +41,7 @@ public function test_it_can_interpret_a_decoded_composer_json_file( $expectedRequiredPhpVersion, $expectedHasRequiredPhpVersion, $expectedRequiredItems, + $expectedConflictingExtensions, ); } @@ -50,6 +52,7 @@ public static function composerJsonProvider(): iterable null, false, [], + [], ]; yield 'PHP platform requirements' => [ @@ -68,6 +71,7 @@ public static function composerJsonProvider(): iterable new RequiredItem(['php' => '^7.1']), new RequiredItem(['ext-phar' => '*']), ], + [], ]; yield 'PHP platform-dev requirements' => [ @@ -83,6 +87,7 @@ public static function composerJsonProvider(): iterable null, false, [], + [], ]; yield 'packages required' => [ @@ -103,6 +108,22 @@ public static function composerJsonProvider(): iterable new RequiredItem(['beberlei/assert' => '^2.9']), new RequiredItem(['composer/ca-bundle' => '^1.1']), ], + [], + ]; + + yield 'conflicts' => [ + <<<'JSON' + { + "conflict": { + "psr/logger": ">=7.1", + "ext-phar": "*" + } + } + JSON, + null, + false, + [], + ['phar'], ]; yield 'nominal' => [ @@ -116,6 +137,9 @@ public static function composerJsonProvider(): iterable }, "require-dev": { "webmozarts/assert": "^3.2" + }, + "conflict": { + "ext-http": "*" } } JSON, @@ -127,6 +151,7 @@ public static function composerJsonProvider(): iterable new RequiredItem(['ext-http' => '*']), new RequiredItem(['composer/ca-bundle' => '^1.1']), ], + ['http'], ]; } @@ -135,9 +160,11 @@ private static function assertStateIs( ?string $expectedRequiredPhpVersion, bool $expectedHasRequiredPhpVersion, array $expectedRequiredItems, + array $expectedConflictingExtensions, ): void { self::assertSame($expectedRequiredPhpVersion, $composerJson->getRequiredPhpVersion()); self::assertSame($expectedHasRequiredPhpVersion, $composerJson->hasRequiredPhpVersion()); self::assertEquals($expectedRequiredItems, $composerJson->getRequiredItems()); + self::assertSame($expectedConflictingExtensions, $composerJson->getConflictingExtensions()); } } diff --git a/tests/RequirementChecker/PackageInfoTest.php b/tests/RequirementChecker/PackageInfoTest.php index 387529d57..20f134087 100644 --- a/tests/RequirementChecker/PackageInfoTest.php +++ b/tests/RequirementChecker/PackageInfoTest.php @@ -33,7 +33,8 @@ public function test_it_can_parse_the_decoded_data( ?string $expectedRequiredPhpVersion, bool $expectedHasRequiredPhpVersion, array $expectedRequiredExtensions, - array $expectedPolyfilledExtension, + array $expectedPolyfilledExtensions, + array $expectedConflictingExtensions, ): void { $packageInfo = new PackageInfo($rawPackageInfo); @@ -43,7 +44,8 @@ public function test_it_can_parse_the_decoded_data( $expectedRequiredPhpVersion, $expectedHasRequiredPhpVersion, $expectedRequiredExtensions, - $expectedPolyfilledExtension, + $expectedPolyfilledExtensions, + $expectedConflictingExtensions, ); } @@ -58,6 +60,7 @@ public static function packageInfoProvider(): iterable false, [], [], + [], ]; yield 'has a PHP version required' => [ @@ -72,6 +75,7 @@ public static function packageInfoProvider(): iterable true, [], [], + [], ]; yield 'has a PHP version required as a dev dep' => [ @@ -86,6 +90,7 @@ public static function packageInfoProvider(): iterable false, [], [], + [], ]; yield 'has PHP extensions required' => [ @@ -111,6 +116,7 @@ public static function packageInfoProvider(): iterable 'zend opcache', ], [], + [], ]; yield 'polyfills extensions' => [ @@ -130,6 +136,7 @@ public static function packageInfoProvider(): iterable 'mbstring', 'ctype', ], + [], ]; yield 'Symfony mbstring polyfill' => [ @@ -141,6 +148,7 @@ public static function packageInfoProvider(): iterable false, [], ['mbstring'], + [], ]; yield 'Symfony PHP polyfill' => [ @@ -152,6 +160,7 @@ public static function packageInfoProvider(): iterable false, [], [], + [], ]; yield 'phpseclib/mcrypt_compat' => [ @@ -163,6 +172,26 @@ public static function packageInfoProvider(): iterable false, [], ['mcrypt'], + [], + ]; + + yield 'package with conflicts' => [ + [ + 'name' => 'laminas/laminas-servicemanager', + 'conflict' => [ + 'ext-psr' => '*', + 'ext-http' => '*', + 'laminas/laminas-code' => '<3.3.1', + 'zendframework/zend-code' => '<3.3.1', + 'zendframework/zend-servicemanager' => '*', + ], + ], + 'laminas/laminas-servicemanager', + null, + false, + [], + [], + ['psr', 'http'], ]; yield 'nominal' => [ @@ -265,6 +294,7 @@ public static function packageInfoProvider(): iterable true, [], [], + [], ]; } @@ -274,12 +304,14 @@ private static function assertStateIs( ?string $expectedRequiredPhpVersion, bool $expectedHasRequiredPhpVersion, array $expectedRequiredExtensions, - array $expectedPolyfilledExtension, + array $expectedPolyfilledExtensions, + array $expectedConflictingExtensions, ): void { self::assertSame($expectedName, $actual->getName()); self::assertSame($expectedRequiredPhpVersion, $actual->getRequiredPhpVersion()); self::assertSame($expectedHasRequiredPhpVersion, $actual->hasRequiredPhpVersion()); self::assertSame($expectedRequiredExtensions, $actual->getRequiredExtensions()); - self::assertSame($expectedPolyfilledExtension, $actual->getPolyfilledExtensions()); + self::assertSame($expectedPolyfilledExtensions, $actual->getPolyfilledExtensions()); + self::assertSame($expectedConflictingExtensions, $actual->getConflictingExtensions()); } } diff --git a/tests/RequirementChecker/RequirementTest.php b/tests/RequirementChecker/RequirementTest.php index 011327dde..04b80bae4 100644 --- a/tests/RequirementChecker/RequirementTest.php +++ b/tests/RequirementChecker/RequirementTest.php @@ -78,4 +78,32 @@ public function test_it_can_be_created_for_an_extension_constraint_for_a_package self::assertSame($expected, $requirement->toArray()); } + + public function test_it_can_be_created_for_a_conflicting_extension_constraint(): void + { + $requirement = Requirement::forConflictingExtension('mbstring', null); + + $expected = [ + 'type' => 'extension-conflict', + 'condition' => 'mbstring', + 'message' => 'The application conflicts with the extension "mbstring".', + 'helpMessage' => 'The application conflicts with the extension "mbstring". Disable it.', + ]; + + self::assertSame($expected, $requirement->toArray()); + } + + public function test_it_can_be_created_for_a_conflicting_extension_constraint_for_a_package(): void + { + $requirement = Requirement::forConflictingExtension('mbstring', 'box/test'); + + $expected = [ + 'type' => 'extension-conflict', + 'condition' => 'mbstring', + 'message' => 'The package "box/test" conflicts with the extension "mbstring".', + 'helpMessage' => 'The package "box/test" conflicts with the extension "mbstring". Disable it.', + ]; + + self::assertSame($expected, $requirement->toArray()); + } } diff --git a/tests/RequirementChecker/RequirementsDumperTest.php b/tests/RequirementChecker/RequirementsDumperTest.php index 4284f7f17..712b3d777 100644 --- a/tests/RequirementChecker/RequirementsDumperTest.php +++ b/tests/RequirementChecker/RequirementsDumperTest.php @@ -49,6 +49,7 @@ public function test_it_dumps_the_requirement_checker_files( 'bin/check-requirements.php', 'src/Checker.php', 'src/IO.php', + 'src/IsExtensionConflictFulfilled.php', 'src/IsExtensionFulfilled.php', 'src/IsFulfilled.php', 'src/IsPhpVersionFulfilled.php',