diff --git a/cmd/ddev/cmd/composer-create.go b/cmd/ddev/cmd/composer-create.go index 9d53fb2ef2e..81a0d08d026 100644 --- a/cmd/ddev/cmd/composer-create.go +++ b/cmd/ddev/cmd/composer-create.go @@ -300,6 +300,8 @@ ddev composer create --preserve-flags --no-interaction psr/log util.Warning("Failed to restart project after composer create: %v", err) } + util.Success("\nddev composer create was successful.\nConsider using `ddev config --update` to autodetect configuration for your project") + if runtime.GOOS == "windows" { fileutil.ReplaceSimulatedLinks(app.AppRoot) } diff --git a/cmd/ddev/cmd/config.go b/cmd/ddev/cmd/config.go index ca0e467509b..955f6f1e375 100644 --- a/cmd/ddev/cmd/config.go +++ b/cmd/ddev/cmd/config.go @@ -309,6 +309,7 @@ func init() { ConfigCommand.Flags().Bool("disable-upload-dirs-warning", true, `Disable warnings about upload-dirs not being set when using performance-mode=mutagen.`) ConfigCommand.Flags().StringVar(&ddevVersionConstraint, "ddev-version-constraint", "", `Specify a ddev version constraint to validate ddev against.`) ConfigCommand.Flags().Bool("corepack-enable", true, `Do 'corepack enable' to enable latest yarn/pnpm'`) + ConfigCommand.Flags().Bool("update", false, `Update project settings based on detection and project-type overrides`) RootCmd.AddCommand(ConfigCommand) @@ -423,10 +424,21 @@ func handleMainConfigArgs(cmd *cobra.Command, _ []string, app *ddevapp.DdevApp) util.Failed("Failed to get absolute path to Docroot %s: %v", app.Docroot, pathErr) } + doUpdate, _ := cmd.Flags().GetBool("update") switch { + case doUpdate: + if projectTypeArg == "" { + projectTypeArg = detectedApptype + } + + app.Type = projectTypeArg + util.Success("Auto-updating project configuration because update is requested.\nConfiguring a '%s' project with docroot '%s' at %s", app.Type, app.Docroot, fullPath) + err = app.ConfigFileOverrideAction(true) + if err != nil { + util.Warning("ConfigOverrideAction failed: %v") + } case app.Type != nodeps.AppTypeNone && projectTypeArg == "" && detectedApptype != app.Type: // apptype was not passed, but we found an app of a different type util.Warning("A project of type '%s' was found in %s, but the project is configured with type '%s'", detectedApptype, fullPath, app.Type) - break default: if projectTypeArg == "" { projectTypeArg = detectedApptype @@ -438,7 +450,7 @@ func handleMainConfigArgs(cmd *cobra.Command, _ []string, app *ddevapp.DdevApp) // App overrides are done after app type is detected, but // before user-defined flags are set. - err = app.ConfigFileOverrideAction() + err = app.ConfigFileOverrideAction(false) if err != nil { util.Failed("Failed to run ConfigFileOverrideAction: %v", err) } diff --git a/cmd/ddev/cmd/config_test.go b/cmd/ddev/cmd/config_test.go index 5a7a7a4f4fa..8ce718b0526 100644 --- a/cmd/ddev/cmd/config_test.go +++ b/cmd/ddev/cmd/config_test.go @@ -2,8 +2,10 @@ package cmd import ( "fmt" + copy2 "github.com/otiai10/copy" "os" "path/filepath" + "reflect" "strconv" "strings" "testing" @@ -155,8 +157,8 @@ func TestConfigSetValues(t *testing.T) { projectName := t.Name() projectType := nodeps.AppTypeTYPO3 phpVersion := nodeps.PHP71 - httpPort := "81" - httpsPort := "444" + routerHTTPPort := "81" + routerHTTPSPort := "444" hostDBPort := "60001" hostWebserverPort := "60002" hostHTTPSPort := "60003" @@ -196,8 +198,8 @@ func TestConfigSetValues(t *testing.T) { "--php-version", phpVersion, "--composer-root", composerRoot, "--composer-version", composerVersion, - "--http-port", httpPort, - "--https-port", httpsPort, + "--router-http-port", routerHTTPPort, + "--router-https-port", routerHTTPSPort, fmt.Sprintf("--xdebug-enabled=%t", xdebugEnabled), fmt.Sprintf("--no-project-mount=%t", noProjectMount), "--additional-hostnames", additionalHostnames, @@ -223,6 +225,7 @@ func TestConfigSetValues(t *testing.T) { "--disable-upload-dirs-warning", } + t.Logf("command=\n%s", strings.Join(args, " ")) out, err := exec.RunHostCommand(DdevBin, args...) assert.NoError(err, "error running ddev %v: %v, output=%s", args, err, out) @@ -248,8 +251,8 @@ func TestConfigSetValues(t *testing.T) { assert.Equal(phpVersion, app.PHPVersion) assert.Equal(composerRoot, app.ComposerRoot) assert.Equal(composerVersion, app.ComposerVersion) - assert.Equal(httpPort, app.RouterHTTPPort) - assert.Equal(httpsPort, app.RouterHTTPSPort) + assert.Equal(routerHTTPPort, app.RouterHTTPPort) + assert.Equal(routerHTTPSPort, app.RouterHTTPSPort) assert.Equal(hostWebserverPort, app.HostWebserverPort) assert.Equal(hostDBPort, app.HostDBPort) assert.Equal(xdebugEnabled, app.XdebugEnabled) @@ -546,6 +549,102 @@ func TestConfigDatabaseVersion(t *testing.T) { } } +// TestConfigUpdate verifies that ddev config --update does the right things updating default +// config, and does not do the wrong things. +func TestConfigUpdate(t *testing.T) { + var err error + origDir, _ := os.Getwd() + + // Create a temporary directory and switch to it. + testDir := testcommon.CreateTmpDir(t.Name()) + + t.Cleanup(func() { + app, _ := ddevapp.NewApp(testDir, false) + _ = app.Stop(true, false) + _ = os.Chdir(origDir) + _ = os.RemoveAll(testDir) + }) + tests := map[string]struct { + input string + baseExpectation ddevapp.DdevApp + configExpectation ddevapp.DdevApp + }{ + "drupal11-composer": { + baseExpectation: ddevapp.DdevApp{Type: nodeps.AppTypePHP, PHPVersion: nodeps.PHPDefault, Docroot: "", CorepackEnable: false, Database: ddevapp.DatabaseDesc{Type: nodeps.MariaDB, Version: nodeps.MariaDBDefaultVersion}}, + configExpectation: ddevapp.DdevApp{Type: nodeps.AppTypeDrupal, PHPVersion: nodeps.PHP83, Docroot: "web", CorepackEnable: true, Database: ddevapp.DatabaseDesc{Type: nodeps.MariaDB, Version: nodeps.MariaDBDefaultVersion}}, + }, + "drupal11-git": { + baseExpectation: ddevapp.DdevApp{Type: nodeps.AppTypePHP, PHPVersion: nodeps.PHPDefault, Docroot: "", CorepackEnable: false, Database: ddevapp.DatabaseDesc{Type: nodeps.MariaDB, Version: nodeps.MariaDBDefaultVersion}}, + configExpectation: ddevapp.DdevApp{Type: nodeps.AppTypeDrupal, PHPVersion: nodeps.PHP83, Docroot: "", CorepackEnable: true, Database: ddevapp.DatabaseDesc{Type: nodeps.MariaDB, Version: nodeps.MariaDBDefaultVersion}}, + }, + "drupal10-composer": { + baseExpectation: ddevapp.DdevApp{Type: nodeps.AppTypePHP, PHPVersion: nodeps.PHPDefault, Docroot: "", CorepackEnable: false, Database: ddevapp.DatabaseDesc{Type: nodeps.MariaDB, Version: nodeps.MariaDBDefaultVersion}}, + configExpectation: ddevapp.DdevApp{Type: nodeps.AppTypeDrupal, PHPVersion: nodeps.PHP83, Docroot: "web", CorepackEnable: false, Database: ddevapp.DatabaseDesc{Type: nodeps.MariaDB, Version: nodeps.MariaDBDefaultVersion}}, + }, + "craftcms": { + baseExpectation: ddevapp.DdevApp{Type: nodeps.AppTypePHP, PHPVersion: nodeps.PHPDefault, Docroot: "", CorepackEnable: false, Database: ddevapp.DatabaseDesc{Type: nodeps.MariaDB, Version: nodeps.MariaDBDefaultVersion}}, + configExpectation: ddevapp.DdevApp{Type: nodeps.AppTypeCraftCms, PHPVersion: nodeps.PHPDefault, Docroot: "web", CorepackEnable: false, Database: ddevapp.DatabaseDesc{Type: nodeps.MySQL, Version: "8.0"}}, + }, + } + + for testName, expectation := range tests { + t.Run(testName, func(t *testing.T) { + // Delete existing + _ = globalconfig.RemoveProjectInfo(t.Name()) + // Delete filesystem from existing + _ = os.RemoveAll(testDir) + + err = os.MkdirAll(testDir, 0755) + require.NoError(t, err) + _ = os.Chdir(testDir) + require.NoError(t, err) + + // Copy testdata in from source + testSource := filepath.Join(origDir, "testdata", t.Name()) + err = copy2.Copy(testSource, testDir) + require.NoError(t, err) + + // Start with an existing config.yaml and verify + app, err := ddevapp.NewApp("", false) + require.NoError(t, err) + _ = app.Stop(true, false) + + // Original values should match + checkValues(t, testName, expectation.baseExpectation, app) + + // ddev config --update and verify + out, err := exec.RunHostCommand(DdevBin, "config", "--update") + require.NoError(t, err, "failed to run ddev config --update: %v output=%s", err, out) + + // Load the newly-created app to inspect it + app, err = ddevapp.NewApp("", false) + require.NoError(t, err) + + // Updated values should match + checkValues(t, testName, expectation.configExpectation, app) + + }) + } +} + +// checkValues compares several values of the expected and actual apps to make sure they're the same +func checkValues(t *testing.T, name string, expectation ddevapp.DdevApp, app *ddevapp.DdevApp) { + assert := asrt.New(t) + + reflectedExpectation := reflect.ValueOf(expectation) + reflectedApp := reflect.ValueOf(*app) + + for _, member := range []string{"Type", "PHPVersion", "Docroot", "CorepackEnable", "Database"} { + + fieldExpectation := reflectedExpectation.FieldByName(member) + if fieldExpectation.IsValid() { + fieldValueExpectation := fieldExpectation.Interface() + fieldValueApp := reflectedApp.FieldByName(member).Interface() + assert.Equal(fieldValueExpectation, fieldValueApp, "%s: field %s does not match", name, member) + } + } +} + // TestConfigGitignore checks that our gitignore is ignoring the right things. func TestConfigGitignore(t *testing.T) { assert := asrt.New(t) diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/craftcms/.ddev/config.yaml b/cmd/ddev/cmd/testdata/TestConfigUpdate/craftcms/.ddev/config.yaml new file mode 100644 index 00000000000..cf3cc4200f9 --- /dev/null +++ b/cmd/ddev/cmd/testdata/TestConfigUpdate/craftcms/.ddev/config.yaml @@ -0,0 +1 @@ +type: php diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/craftcms/craft b/cmd/ddev/cmd/testdata/TestConfigUpdate/craftcms/craft new file mode 100755 index 00000000000..547e5089039 --- /dev/null +++ b/cmd/ddev/cmd/testdata/TestConfigUpdate/craftcms/craft @@ -0,0 +1,14 @@ +#!/usr/bin/env php +run(); +exit($exitCode); diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/craftcms/vendor/craftcms/cms/src/Craft.php b/cmd/ddev/cmd/testdata/TestConfigUpdate/craftcms/vendor/craftcms/cms/src/Craft.php new file mode 100644 index 00000000000..5f45106c119 --- /dev/null +++ b/cmd/ddev/cmd/testdata/TestConfigUpdate/craftcms/vendor/craftcms/cms/src/Craft.php @@ -0,0 +1,392 @@ + + * @since 3.0.0 + */ +class Craft extends Yii +{ + // Edition constants + public const Solo = 0; + public const Pro = 1; + + /** + * @var array The default cookie configuration. + */ + private static array $_baseCookieConfig; + + /** + * @inheritdoc + * @template T + * @param string|array|callable $type + * @phpstan-param class-string|array{class:class-string}|callable():T $type + * @param array $params + * @return T + */ + public static function createObject($type, array $params = []) + { + return parent::createObject($type, $params); + } + + /** + * Checks if a string references an environment variable (`$VARIABLE_NAME`) + * and/or an alias (`@aliasName`), and returns the referenced value. + * + * If the string references an environment variable with a value of `true` + * or `false`, a boolean value will be returned. + * + * --- + * + * ```php + * $value1 = Craft::parseEnv('$SMTP_PASSWORD'); + * $value2 = Craft::parseEnv('@webroot'); + * ``` + * + * @param string|null $str + * @return string|null|false The parsed value, or the original value if it didn’t + * reference an environment variable or alias. + * @since 3.1.0 + * @deprecated in 3.7.29. [[App::parseEnv()]] should be used instead. + */ + public static function parseEnv(?string $str = null): string|null|false + { + return App::parseEnv($str); + } + + /** + * Checks if a string references an environment variable (`$VARIABLE_NAME`) and returns the referenced + * boolean value, or `null` if a boolean value can’t be determined. + * + * --- + * + * ```php + * $status = Craft::parseBooleanEnv('$SYSTEM_STATUS') ?? false; + * ``` + * + * @param mixed $value + * @return bool|null + * @since 3.7.22 + * @deprecated in 3.7.29. [[App::parseBooleanEnv()]] should be used instead. + */ + public static function parseBooleanEnv(mixed $value): ?bool + { + return App::parseBooleanEnv($value); + } + + /** + * Displays a variable. + * + * @param mixed $var The variable to be dumped. + * @param int $depth The maximum depth that the dumper should go into the variable. Defaults to 10. + * @param bool $highlight Whether the result should be syntax-highlighted. Defaults to true. + */ + public static function dump(mixed $var, int $depth = 10, bool $highlight = true): void + { + VarDumper::dump($var, $depth, $highlight); + } + + /** + * Displays a variable and ends the request. (“Dump and die”) + * + * @param mixed $var The variable to be dumped. + * @param int $depth The maximum depth that the dumper should go into the variable. Defaults to 10. + * @param bool|null $highlight Whether the result should be syntax-highlighted. + * Defaults to `true` for web requests and `false` for console requests. + * @throws ExitException if the application is in testing mode + */ + public static function dd(mixed $var, int $depth = 10, ?bool $highlight = null): void + { + // Turn off output buffering and discard OB contents + while (ob_get_length() !== false) { + // If ob_start() didn't have the PHP_OUTPUT_HANDLER_CLEANABLE flag, ob_get_clean() will cause a PHP notice + // and return false. + if (@ob_get_clean() === false) { + break; + } + } + + if ($highlight === null) { + $highlight = !static::$app->getRequest()->getIsConsoleRequest(); + } + + VarDumper::dump($var, $depth, $highlight); + exit(); + } + + /** + * Generates and returns a cookie config. + * + * @param array $config Any config options that should be included in the config. + * @param Request|null $request The request object + * @return array The cookie config array. + */ + public static function cookieConfig(array $config = [], ?Request $request = null): array + { + if (!isset(self::$_baseCookieConfig)) { + $generalConfig = static::$app->getConfig()->getGeneral(); + + if ($generalConfig->useSecureCookies === 'auto') { + if ($request === null) { + $request = static::$app->getRequest(); + } + + $generalConfig->useSecureCookies = $request->getIsSecureConnection(); + } + + self::$_baseCookieConfig = [ + 'domain' => $generalConfig->defaultCookieDomain, + 'secure' => $generalConfig->useSecureCookies, + 'httpOnly' => true, + 'sameSite' => $generalConfig->sameSiteCookieValue, + ]; + } + + return array_merge(self::$_baseCookieConfig, $config); + } + + /** + * Class autoloader. + * + * @param string $className + * @phpstan-param class-string $className + */ + public static function autoload($className): void + { + if ($className === CustomFieldBehavior::class) { + self::_autoloadCustomFieldBehavior(); + } + } + + /** + * Autoloads (and possibly generates) `CustomFieldBehavior.php` + */ + private static function _autoloadCustomFieldBehavior(): void + { + if (!isset(static::$app)) { + // Nothing we can do about it yet + return; + } + + if (!static::$app->getIsInstalled()) { + // Just load an empty CustomFieldBehavior into memory + self::_generateCustomFieldBehavior([], null, false, true); + return; + } + + $fieldsService = Craft::$app->getFields(); + $storedFieldVersion = $fieldsService->getFieldVersion(); + $compiledClassesPath = static::$app->getPath()->getCompiledClassesPath(); + $fieldVersionExists = $storedFieldVersion !== null; + + if (!$fieldVersionExists) { + // Just make up a temporary one + $storedFieldVersion = StringHelper::randomString(12); + } + + $filePath = $compiledClassesPath . DIRECTORY_SEPARATOR . "CustomFieldBehavior_$storedFieldVersion.php"; + + if ($fieldVersionExists && file_exists($filePath)) { + include $filePath; + return; + } + + $fields = self::_fields(); + + if (empty($fields)) { + // Write and load it simultaneously since there are no custom fields to worry about + self::_generateCustomFieldBehavior([], $filePath, true, true); + } else { + // First generate a basic version without real field value types, and load it into memory + $fieldHandles = []; + foreach ($fields as $field) { + $fieldHandles[$field['handle']]['mixed'] = true; + } + self::_generateCustomFieldBehavior($fieldHandles, $filePath, false, true); + + // Now generate it again, this time with the correct field value types + $fieldHandles = []; + foreach ($fields as $field) { + /** @var FieldInterface|string $fieldClass */ + $fieldClass = $field['type']; + if (Component::validateComponentClass($fieldClass, FieldInterface::class)) { + $types = explode('|', $fieldClass::valueType()); + } else { + $types = ['mixed']; + } + foreach ($types as $type) { + $type = trim($type, ' \\'); + // Add a leading `\` if it’s not a variable, self-reference, or primitive type + if (!preg_match('/^(\$.*|(self|static|bool|boolean|int|integer|float|double|string|array|object|callable|callback|iterable|resource|null|mixed|number|void)(\[\])?)$/i', $type)) { + $type = '\\' . $type; + } + $fieldHandles[$field['handle']][$type] = true; + } + } + self::_generateCustomFieldBehavior($fieldHandles, $filePath, true, false); + } + + // Generate a new field version if we need one + if (!$fieldVersionExists) { + try { + $fieldsService->updateFieldVersion(); + } catch (Throwable) { + // Craft probably isn't installed yet. + } + } + } + + /** + * @param array $fieldHandles + * @param string|null $filePath + * @param bool $write + * @param bool $load + * @throws \yii\base\ErrorException + */ + private static function _generateCustomFieldBehavior(array $fieldHandles, ?string $filePath, bool $write, bool $load): void + { + $methods = []; + $handles = []; + $properties = []; + + foreach ($fieldHandles as $handle => $types) { + $methods[] = << true, +EOD; + + $phpDocTypes = implode('|', array_keys($types)); + $properties[] = <<getBasePath() . DIRECTORY_SEPARATOR . 'behaviors' . DIRECTORY_SEPARATOR . 'CustomFieldBehavior.php.template'; + FileHelper::invalidate($templatePath); + $fileContents = file_get_contents($templatePath); + + // Replace placeholders with generated code + $fileContents = str_replace( + [ + '{METHOD_DOCS}', + '/* HANDLES */', + '/* PROPERTIES */', + ], + [ + implode("\n", $methods), + implode("\n", $handles), + implode("\n\n", $properties), + ], + $fileContents); + + if ($write) { + $dir = dirname($filePath); + $tmpFile = $dir . DIRECTORY_SEPARATOR . uniqid(pathinfo($filePath, PATHINFO_FILENAME), true) . '.php'; + FileHelper::writeToFile($tmpFile, $fileContents); + rename($tmpFile, $filePath); + FileHelper::invalidate($filePath); + if ($load) { + include $filePath; + } + + // Delete any CustomFieldBehavior files that are over 10 seconds old + $basename = basename($filePath); + $time = time() - 10; + FileHelper::clearDirectory($dir, [ + 'filter' => function(string $path) use ($basename, $time): bool { + $b = basename($path); + return ( + $b !== $basename && + str_starts_with($b, 'CustomFieldBehavior') && + filemtime($path) < $time + ); + }, + ]); + } elseif ($load) { + // Just evaluate the code + eval(preg_replace('/^<\?php\s*/', '', $fileContents)); + } + } + + /** + * @return array + */ + private static function _fields(): array + { + // Properties are case-sensitive, so get all the binary-unique field handles + if (static::$app->getDb()->getIsMysql()) { + $handleColumn = new Expression('binary [[handle]] as [[handle]]'); + } else { + $handleColumn = 'handle'; + } + + // Create an array of field handles and their types + return (new Query()) + ->from([Table::FIELDS]) + ->select([$handleColumn, 'type']) + ->all(); + } + + /** + * Creates a Guzzle client configured with the given array merged with any default values in config/guzzle.php. + * + * @param array $config Guzzle client config settings + * @return Client + */ + public static function createGuzzleClient(array $config = []): Client + { + // Set the Craft header by default. + $defaultConfig = [ + 'headers' => [ + 'User-Agent' => 'Craft/' . static::$app->getVersion() . ' ' . default_user_agent(), + ], + ]; + + // Grab the config from config/guzzle.php that is used on every Guzzle request. + $configService = static::$app->getConfig(); + $guzzleConfig = $configService->getConfigFromFile('guzzle'); + $generalConfig = $configService->getGeneral(); + + // Merge everything together + $guzzleConfig = ArrayHelper::merge($defaultConfig, $guzzleConfig, $config); + + if ($generalConfig->httpProxy) { + $guzzleConfig['proxy'] = $generalConfig->httpProxy; + } + + return new Client($guzzleConfig); + } +} + +spl_autoload_register([Craft::class, 'autoload'], true, true); diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/craftcms/web/index.php b/cmd/ddev/cmd/testdata/TestConfigUpdate/craftcms/web/index.php new file mode 100644 index 00000000000..e69de29bb2d diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal10-composer/.ddev/config.yaml b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal10-composer/.ddev/config.yaml new file mode 100644 index 00000000000..288879ad974 --- /dev/null +++ b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal10-composer/.ddev/config.yaml @@ -0,0 +1,2 @@ +# assume that drupal11-composer has been set up with no existing configuration +type: php diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal10-composer/web/core/lib/Drupal.php b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal10-composer/web/core/lib/Drupal.php new file mode 100644 index 00000000000..6e690b665af --- /dev/null +++ b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal10-composer/web/core/lib/Drupal.php @@ -0,0 +1,748 @@ +acquire('stuff_lock'); + * // ... + * } + * + * // Correct procedural code. + * function hook_do_stuff() { + * $lock = \Drupal::lock()->acquire('stuff_lock'); + * // ... + * } + * + * // The preferred way: dependency injected code. + * function hook_do_stuff() { + * // Move the actual implementation to a class and instantiate it. + * $instance = new StuffDoingClass(\Drupal::lock()); + * $instance->doStuff(); + * + * // Or, even better, rely on the service container to avoid hard coding a + * // specific interface implementation, so that the actual logic can be + * // swapped. This might not always make sense, but in general it is a good + * // practice. + * \Drupal::service('stuff.doing')->doStuff(); + * } + * + * interface StuffDoingInterface { + * public function doStuff(); + * } + * + * class StuffDoingClass implements StuffDoingInterface { + * protected $lockBackend; + * + * public function __construct(LockBackendInterface $lock_backend) { + * $this->lockBackend = $lock_backend; + * } + * + * public function doStuff() { + * $lock = $this->lockBackend->acquire('stuff_lock'); + * // ... + * } + * } + * @endcode + * + * @see \Drupal\Core\DrupalKernel + */ +class Drupal { + + /** + * The current system version. + */ + const VERSION = '10.2.5'; + + /** + * Core API compatibility. + * + * This constant is set to '8.x' to provide legacy compatibility with + * extensions that use the '8.x-' prefix to denote Drupal core major version + * compatibility, for example '8.x-1.0'. These extensions can specify + * compatibility with multiple major versions of Drupal core by setting the + * version constraint in 'core_version_requirement'. Drupal does not support + * using this core major version number prefix with versions greater than 8. + * For example '9.x-' prefixed extensions are not supported. + * + * @todo Remove or rename this constant in https://www.drupal.org/i/3085662 + */ + const CORE_COMPATIBILITY = '8.x'; + + /** + * Core minimum schema version. + */ + const CORE_MINIMUM_SCHEMA_VERSION = 8000; + + /** + * Minimum allowed version of PHP for Drupal to be bootstrapped. + * + * Below this version: + * - The installer cannot be run. + * - Updates cannot be run. + * - Modules and themes cannot be enabled. + * - If a site managed to bypass all of the above, then an error is shown in + * the status report and various fatal errors occur on various pages. + * + * Note: To prevent the installer from having fatal errors on older versions + * of PHP, the value of this constant is hardcoded twice in core/install.php: + * - Once as a parameter of version_compare() + * - Once in the error message printed to the user immediately after. + * Remember to update both whenever this constant is updated. + */ + const MINIMUM_PHP = '8.3.0'; + + /** + * Minimum recommended value of PHP memory_limit. + * + * 64M was chosen as a minimum requirement in order to allow for additional + * contributed modules to be installed prior to hitting the limit. However, + * 40M is the target for the Standard installation profile. + */ + const MINIMUM_PHP_MEMORY_LIMIT = '64M'; + + /** + * Minimum recommended version of PHP. + * + * Sites installing Drupal on PHP versions lower than this will see a warning + * message, but Drupal can still be installed. Used for (e.g.) PHP versions + * that have reached their EOL or will in the near future. + */ + const RECOMMENDED_PHP = '8.3.0'; + + /** + * The currently active container object, or NULL if not initialized yet. + * + * @var \Drupal\Component\DependencyInjection\ContainerInterface|null + */ + protected static $container; + + /** + * Sets a new global container. + * + * @param \Symfony\Component\DependencyInjection\ContainerInterface $container + * A new container instance to replace the current. + */ + public static function setContainer(ContainerInterface $container) { + static::$container = $container; + } + + /** + * Unsets the global container. + */ + public static function unsetContainer() { + static::$container = NULL; + } + + /** + * Returns the currently active global container. + * + * @return \Drupal\Component\DependencyInjection\ContainerInterface + * + * @throws \Drupal\Core\DependencyInjection\ContainerNotInitializedException + */ + public static function getContainer() { + if (static::$container === NULL) { + throw new ContainerNotInitializedException('\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.'); + } + return static::$container; + } + + /** + * Returns TRUE if the container has been initialized, FALSE otherwise. + * + * @return bool + */ + public static function hasContainer() { + return static::$container !== NULL; + } + + /** + * Retrieves a service from the container. + * + * Use this method if the desired service is not one of those with a dedicated + * accessor method below. If it is listed below, those methods are preferred + * as they can return useful type hints. + * + * @param string $id + * The ID of the service to retrieve. + * + * @return mixed + * The specified service. + */ + public static function service($id) { + return static::getContainer()->get($id); + } + + /** + * Indicates if a service is defined in the container. + * + * @param string $id + * The ID of the service to check. + * + * @return bool + * TRUE if the specified service exists, FALSE otherwise. + */ + public static function hasService($id) { + // Check hasContainer() first in order to always return a Boolean. + return static::hasContainer() && static::getContainer()->has($id); + } + + /** + * Gets the app root. + * + * @return string + */ + public static function root() { + return static::getContainer()->getParameter('app.root'); + } + + /** + * Gets the active install profile. + * + * @return string|false|null + * The name of the active install profile. FALSE indicates that the site is + * not using an install profile. NULL indicates that the site has not yet + * been installed. + */ + public static function installProfile() { + return static::getContainer()->getParameter('install_profile'); + } + + /** + * Indicates if there is a currently active request object. + * + * @return bool + * TRUE if there is a currently active request object, FALSE otherwise. + */ + public static function hasRequest() { + // Check hasContainer() first in order to always return a Boolean. + return static::hasContainer() && static::getContainer()->has('request_stack') && static::getContainer()->get('request_stack')->getCurrentRequest() !== NULL; + } + + /** + * Retrieves the currently active request object. + * + * Note: The use of this wrapper in particular is especially discouraged. Most + * code should not need to access the request directly. Doing so means it + * will only function when handling an HTTP request, and will require special + * modification or wrapping when run from a command line tool, from certain + * queue processors, or from automated tests. + * + * If code must access the request, it is considerably better to register + * an object with the Service Container and give it a setRequest() method + * that is configured to run when the service is created. That way, the + * correct request object can always be provided by the container and the + * service can still be unit tested. + * + * If this method must be used, never save the request object that is + * returned. Doing so may lead to inconsistencies as the request object is + * volatile and may change at various times, such as during a subrequest. + * + * @return \Symfony\Component\HttpFoundation\Request + * The currently active request object. + */ + public static function request() { + return static::getContainer()->get('request_stack')->getCurrentRequest(); + } + + /** + * Retrieves the request stack. + * + * @return \Symfony\Component\HttpFoundation\RequestStack + * The request stack + */ + public static function requestStack() { + return static::getContainer()->get('request_stack'); + } + + /** + * Retrieves the currently active route match object. + * + * @return \Drupal\Core\Routing\RouteMatchInterface + * The currently active route match object. + */ + public static function routeMatch() { + return static::getContainer()->get('current_route_match'); + } + + /** + * Gets the current active user. + * + * This method will return the \Drupal\Core\Session\AccountProxy object of the + * current user. You can use the \Drupal\user\Entity\User::load() method to + * load the full user entity object. For example: + * @code + * $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); + * @endcode + * + * @return \Drupal\Core\Session\AccountProxyInterface + */ + public static function currentUser() { + return static::getContainer()->get('current_user'); + } + + /** + * Retrieves the entity type manager. + * + * @return \Drupal\Core\Entity\EntityTypeManagerInterface + * The entity type manager. + */ + public static function entityTypeManager() { + return static::getContainer()->get('entity_type.manager'); + } + + /** + * Returns the current primary database. + * + * @return \Drupal\Core\Database\Connection + * The current active database's master connection. + */ + public static function database() { + return static::getContainer()->get('database'); + } + + /** + * Returns the requested cache bin. + * + * @param string $bin + * (optional) The cache bin for which the cache object should be returned, + * defaults to 'default'. + * + * @return \Drupal\Core\Cache\CacheBackendInterface + * The cache object associated with the specified bin. + * + * @ingroup cache + */ + public static function cache($bin = 'default') { + return static::getContainer()->get('cache.' . $bin); + } + + /** + * Retrieves the class resolver. + * + * This is to be used in procedural code such as module files to instantiate + * an object of a class that implements + * \Drupal\Core\DependencyInjection\ContainerInjectionInterface. + * + * One common use case is to provide a class which contains the actual code + * of a hook implementation, without having to create a service. + * + * @param string $class + * (optional) A class name to instantiate. + * + * @return \Drupal\Core\DependencyInjection\ClassResolverInterface|object + * The class resolver or if $class is provided, a class instance with a + * given class definition. + * + * @throws \InvalidArgumentException + * If $class does not exist. + */ + public static function classResolver($class = NULL) { + if ($class) { + return static::getContainer()->get('class_resolver')->getInstanceFromDefinition($class); + } + return static::getContainer()->get('class_resolver'); + } + + /** + * Returns an expirable key value store collection. + * + * @param string $collection + * The name of the collection holding key and value pairs. + * + * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface + * An expirable key value store collection. + */ + public static function keyValueExpirable($collection) { + return static::getContainer()->get('keyvalue.expirable')->get($collection); + } + + /** + * Returns the locking layer instance. + * + * @return \Drupal\Core\Lock\LockBackendInterface + * + * @ingroup lock + */ + public static function lock() { + return static::getContainer()->get('lock'); + } + + /** + * Retrieves a configuration object. + * + * This is the main entry point to the configuration API. Calling + * @code \Drupal::config('my_module.admin') @endcode will return a + * configuration object the my_module module can use to read its + * administrative settings. + * + * @param string $name + * The name of the configuration object to retrieve, which typically + * corresponds to a configuration file. For + * @code \Drupal::config('my_module.admin') @endcode, the configuration + * object returned will contain the content of the my_module.admin + * configuration file. + * + * @return \Drupal\Core\Config\ImmutableConfig + * An immutable configuration object. + */ + public static function config($name) { + return static::getContainer()->get('config.factory')->get($name); + } + + /** + * Retrieves the configuration factory. + * + * This is mostly used to change the override settings on the configuration + * factory. For example, changing the language, or turning all overrides on + * or off. + * + * @return \Drupal\Core\Config\ConfigFactoryInterface + * The configuration factory service. + */ + public static function configFactory() { + return static::getContainer()->get('config.factory'); + } + + /** + * Returns a queue for the given queue name. + * + * The following values can be set in your settings.php file's $settings + * array to define which services are used for queues: + * - queue_reliable_service_$name: The container service to use for the + * reliable queue $name. + * - queue_service_$name: The container service to use for the + * queue $name. + * - queue_default: The container service to use by default for queues + * without overrides. This defaults to 'queue.database'. + * + * @param string $name + * The name of the queue to work with. + * @param bool $reliable + * (optional) TRUE if the ordering of items and guaranteeing every item + * executes at least once is important, FALSE if scalability is the main + * concern. Defaults to FALSE. + * + * @return \Drupal\Core\Queue\QueueInterface + * The queue object for a given name. + */ + public static function queue($name, $reliable = FALSE) { + return static::getContainer()->get('queue')->get($name, $reliable); + } + + /** + * Returns a key/value storage collection. + * + * @param string $collection + * Name of the key/value collection to return. + * + * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface + */ + public static function keyValue($collection) { + return static::getContainer()->get('keyvalue')->get($collection); + } + + /** + * Returns the state storage service. + * + * Use this to store machine-generated data, local to a specific environment + * that does not need deploying and does not need human editing; for example, + * the last time cron was run. Data which needs to be edited by humans and + * needs to be the same across development, production, etc. environments + * (for example, the system maintenance message) should use \Drupal::config() instead. + * + * @return \Drupal\Core\State\StateInterface + */ + public static function state() { + return static::getContainer()->get('state'); + } + + /** + * Returns the default http client. + * + * @return \GuzzleHttp\Client + * A guzzle http client instance. + */ + public static function httpClient() { + return static::getContainer()->get('http_client'); + } + + /** + * Returns the entity query object for this entity type. + * + * @param string $entity_type + * The entity type (for example, node) for which the query object should be + * returned. + * @param string $conjunction + * (optional) Either 'AND' if all conditions in the query need to apply, or + * 'OR' if any of them is sufficient. Defaults to 'AND'. + * + * @return \Drupal\Core\Entity\Query\QueryInterface + * The query object that can query the given entity type. + */ + public static function entityQuery($entity_type, $conjunction = 'AND') { + return static::entityTypeManager()->getStorage($entity_type)->getQuery($conjunction); + } + + /** + * Returns the entity query aggregate object for this entity type. + * + * @param string $entity_type + * The entity type (for example, node) for which the query object should be + * returned. + * @param string $conjunction + * (optional) Either 'AND' if all conditions in the query need to apply, or + * 'OR' if any of them is sufficient. Defaults to 'AND'. + * + * @return \Drupal\Core\Entity\Query\QueryAggregateInterface + * The query object that can query the given entity type. + */ + public static function entityQueryAggregate($entity_type, $conjunction = 'AND') { + return static::entityTypeManager()->getStorage($entity_type)->getAggregateQuery($conjunction); + } + + /** + * Returns the flood instance. + * + * @return \Drupal\Core\Flood\FloodInterface + */ + public static function flood() { + return static::getContainer()->get('flood'); + } + + /** + * Returns the module handler. + * + * @return \Drupal\Core\Extension\ModuleHandlerInterface + */ + public static function moduleHandler() { + return static::getContainer()->get('module_handler'); + } + + /** + * Returns the typed data manager service. + * + * Use the typed data manager service for creating typed data objects. + * + * @return \Drupal\Core\TypedData\TypedDataManagerInterface + * The typed data manager. + * + * @see \Drupal\Core\TypedData\TypedDataManager::create() + */ + public static function typedDataManager() { + return static::getContainer()->get('typed_data_manager'); + } + + /** + * Returns the token service. + * + * @return \Drupal\Core\Utility\Token + * The token service. + */ + public static function token() { + return static::getContainer()->get('token'); + } + + /** + * Returns the URL generator service. + * + * @return \Drupal\Core\Routing\UrlGeneratorInterface + * The URL generator service. + */ + public static function urlGenerator() { + return static::getContainer()->get('url_generator'); + } + + /** + * Returns the link generator service. + * + * @return \Drupal\Core\Utility\LinkGeneratorInterface + */ + public static function linkGenerator() { + return static::getContainer()->get('link_generator'); + } + + /** + * Returns the string translation service. + * + * @return \Drupal\Core\StringTranslation\TranslationManager + * The string translation manager. + */ + public static function translation() { + return static::getContainer()->get('string_translation'); + } + + /** + * Returns the language manager service. + * + * @return \Drupal\Core\Language\LanguageManagerInterface + * The language manager. + */ + public static function languageManager() { + return static::getContainer()->get('language_manager'); + } + + /** + * Returns the CSRF token manager service. + * + * The generated token is based on the session ID of the current user. Normally, + * anonymous users do not have a session, so the generated token will be + * different on every page request. To generate a token for users without a + * session, manually start a session prior to calling this function. + * + * @return \Drupal\Core\Access\CsrfTokenGenerator + * The CSRF token manager. + * + * @see \Drupal\Core\Session\SessionManager::start() + */ + public static function csrfToken() { + return static::getContainer()->get('csrf_token'); + } + + /** + * Returns the transliteration service. + * + * @return \Drupal\Core\Transliteration\PhpTransliteration + * The transliteration manager. + */ + public static function transliteration() { + return static::getContainer()->get('transliteration'); + } + + /** + * Returns the form builder service. + * + * @return \Drupal\Core\Form\FormBuilderInterface + * The form builder. + */ + public static function formBuilder() { + return static::getContainer()->get('form_builder'); + } + + /** + * Gets the theme service. + * + * @return \Drupal\Core\Theme\ThemeManagerInterface + */ + public static function theme() { + return static::getContainer()->get('theme.manager'); + } + + /** + * Gets the syncing state. + * + * @return bool + * Returns TRUE is syncing flag set. + */ + public static function isConfigSyncing() { + return static::getContainer()->get('config.installer')->isSyncing(); + } + + /** + * Returns a channel logger object. + * + * @param string $channel + * The name of the channel. Can be any string, but the general practice is + * to use the name of the subsystem calling this. + * + * @return \Psr\Log\LoggerInterface + * The logger for this channel. + */ + public static function logger($channel) { + return static::getContainer()->get('logger.factory')->get($channel); + } + + /** + * Returns the menu tree. + * + * @return \Drupal\Core\Menu\MenuLinkTreeInterface + * The menu tree. + */ + public static function menuTree() { + return static::getContainer()->get('menu.link_tree'); + } + + /** + * Returns the path validator. + * + * @return \Drupal\Core\Path\PathValidatorInterface + */ + public static function pathValidator() { + return static::getContainer()->get('path.validator'); + } + + /** + * Returns the access manager service. + * + * @return \Drupal\Core\Access\AccessManagerInterface + * The access manager service. + */ + public static function accessManager() { + return static::getContainer()->get('access_manager'); + } + + /** + * Returns the redirect destination helper. + * + * @return \Drupal\Core\Routing\RedirectDestinationInterface + * The redirect destination helper. + */ + public static function destination() { + return static::getContainer()->get('redirect.destination'); + } + + /** + * Returns the entity definition update manager. + * + * @return \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface + * The entity definition update manager. + */ + public static function entityDefinitionUpdateManager() { + return static::getContainer()->get('entity.definition_update_manager'); + } + + /** + * Returns the time service. + * + * @return \Drupal\Component\Datetime\TimeInterface + * The time service. + */ + public static function time() { + return static::getContainer()->get('datetime.time'); + } + + /** + * Returns the messenger. + * + * @return \Drupal\Core\Messenger\MessengerInterface + * The messenger. + */ + public static function messenger() { + return static::getContainer()->get('messenger'); + } + +} diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal10-composer/web/index.php b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal10-composer/web/index.php new file mode 100644 index 00000000000..e69de29bb2d diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-composer/.ddev/config.yaml b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-composer/.ddev/config.yaml new file mode 100644 index 00000000000..288879ad974 --- /dev/null +++ b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-composer/.ddev/config.yaml @@ -0,0 +1,2 @@ +# assume that drupal11-composer has been set up with no existing configuration +type: php diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-composer/web/core/lib/Drupal.php b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-composer/web/core/lib/Drupal.php new file mode 100644 index 00000000000..ceb4c53d5ec --- /dev/null +++ b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-composer/web/core/lib/Drupal.php @@ -0,0 +1,748 @@ +acquire('stuff_lock'); + * // ... + * } + * + * // Correct procedural code. + * function hook_do_stuff() { + * $lock = \Drupal::lock()->acquire('stuff_lock'); + * // ... + * } + * + * // The preferred way: dependency injected code. + * function hook_do_stuff() { + * // Move the actual implementation to a class and instantiate it. + * $instance = new StuffDoingClass(\Drupal::lock()); + * $instance->doStuff(); + * + * // Or, even better, rely on the service container to avoid hard coding a + * // specific interface implementation, so that the actual logic can be + * // swapped. This might not always make sense, but in general it is a good + * // practice. + * \Drupal::service('stuff.doing')->doStuff(); + * } + * + * interface StuffDoingInterface { + * public function doStuff(); + * } + * + * class StuffDoingClass implements StuffDoingInterface { + * protected $lockBackend; + * + * public function __construct(LockBackendInterface $lock_backend) { + * $this->lockBackend = $lock_backend; + * } + * + * public function doStuff() { + * $lock = $this->lockBackend->acquire('stuff_lock'); + * // ... + * } + * } + * @endcode + * + * @see \Drupal\Core\DrupalKernel + */ +class Drupal { + + /** + * The current system version. + */ + const VERSION = '11.0-dev'; + + /** + * Core API compatibility. + * + * This constant is set to '8.x' to provide legacy compatibility with + * extensions that use the '8.x-' prefix to denote Drupal core major version + * compatibility, for example '8.x-1.0'. These extensions can specify + * compatibility with multiple major versions of Drupal core by setting the + * version constraint in 'core_version_requirement'. Drupal does not support + * using this core major version number prefix with versions greater than 8. + * For example '9.x-' prefixed extensions are not supported. + * + * @todo Remove or rename this constant in https://www.drupal.org/i/3085662 + */ + const CORE_COMPATIBILITY = '8.x'; + + /** + * Core minimum schema version. + */ + const CORE_MINIMUM_SCHEMA_VERSION = 8000; + + /** + * Minimum allowed version of PHP for Drupal to be bootstrapped. + * + * Below this version: + * - The installer cannot be run. + * - Updates cannot be run. + * - Modules and themes cannot be enabled. + * - If a site managed to bypass all of the above, then an error is shown in + * the status report and various fatal errors occur on various pages. + * + * Note: To prevent the installer from having fatal errors on older versions + * of PHP, the value of this constant is hardcoded twice in core/install.php: + * - Once as a parameter of version_compare() + * - Once in the error message printed to the user immediately after. + * Remember to update both whenever this constant is updated. + */ + const MINIMUM_PHP = '8.3.0'; + + /** + * Minimum recommended value of PHP memory_limit. + * + * 64M was chosen as a minimum requirement in order to allow for additional + * contributed modules to be installed prior to hitting the limit. However, + * 40M is the target for the Standard installation profile. + */ + const MINIMUM_PHP_MEMORY_LIMIT = '64M'; + + /** + * Minimum recommended version of PHP. + * + * Sites installing Drupal on PHP versions lower than this will see a warning + * message, but Drupal can still be installed. Used for (e.g.) PHP versions + * that have reached their EOL or will in the near future. + */ + const RECOMMENDED_PHP = '8.3.0'; + + /** + * The currently active container object, or NULL if not initialized yet. + * + * @var \Drupal\Component\DependencyInjection\ContainerInterface|null + */ + protected static $container; + + /** + * Sets a new global container. + * + * @param \Symfony\Component\DependencyInjection\ContainerInterface $container + * A new container instance to replace the current. + */ + public static function setContainer(ContainerInterface $container) { + static::$container = $container; + } + + /** + * Unsets the global container. + */ + public static function unsetContainer() { + static::$container = NULL; + } + + /** + * Returns the currently active global container. + * + * @return \Drupal\Component\DependencyInjection\ContainerInterface + * + * @throws \Drupal\Core\DependencyInjection\ContainerNotInitializedException + */ + public static function getContainer() { + if (static::$container === NULL) { + throw new ContainerNotInitializedException('\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.'); + } + return static::$container; + } + + /** + * Returns TRUE if the container has been initialized, FALSE otherwise. + * + * @return bool + */ + public static function hasContainer() { + return static::$container !== NULL; + } + + /** + * Retrieves a service from the container. + * + * Use this method if the desired service is not one of those with a dedicated + * accessor method below. If it is listed below, those methods are preferred + * as they can return useful type hints. + * + * @param string $id + * The ID of the service to retrieve. + * + * @return mixed + * The specified service. + */ + public static function service($id) { + return static::getContainer()->get($id); + } + + /** + * Indicates if a service is defined in the container. + * + * @param string $id + * The ID of the service to check. + * + * @return bool + * TRUE if the specified service exists, FALSE otherwise. + */ + public static function hasService($id) { + // Check hasContainer() first in order to always return a Boolean. + return static::hasContainer() && static::getContainer()->has($id); + } + + /** + * Gets the app root. + * + * @return string + */ + public static function root() { + return static::getContainer()->getParameter('app.root'); + } + + /** + * Gets the active install profile. + * + * @return string|false|null + * The name of the active install profile. FALSE indicates that the site is + * not using an install profile. NULL indicates that the site has not yet + * been installed. + */ + public static function installProfile() { + return static::getContainer()->getParameter('install_profile'); + } + + /** + * Indicates if there is a currently active request object. + * + * @return bool + * TRUE if there is a currently active request object, FALSE otherwise. + */ + public static function hasRequest() { + // Check hasContainer() first in order to always return a Boolean. + return static::hasContainer() && static::getContainer()->has('request_stack') && static::getContainer()->get('request_stack')->getCurrentRequest() !== NULL; + } + + /** + * Retrieves the currently active request object. + * + * Note: The use of this wrapper in particular is especially discouraged. Most + * code should not need to access the request directly. Doing so means it + * will only function when handling an HTTP request, and will require special + * modification or wrapping when run from a command line tool, from certain + * queue processors, or from automated tests. + * + * If code must access the request, it is considerably better to register + * an object with the Service Container and give it a setRequest() method + * that is configured to run when the service is created. That way, the + * correct request object can always be provided by the container and the + * service can still be unit tested. + * + * If this method must be used, never save the request object that is + * returned. Doing so may lead to inconsistencies as the request object is + * volatile and may change at various times, such as during a subrequest. + * + * @return \Symfony\Component\HttpFoundation\Request + * The currently active request object. + */ + public static function request() { + return static::getContainer()->get('request_stack')->getCurrentRequest(); + } + + /** + * Retrieves the request stack. + * + * @return \Symfony\Component\HttpFoundation\RequestStack + * The request stack + */ + public static function requestStack() { + return static::getContainer()->get('request_stack'); + } + + /** + * Retrieves the currently active route match object. + * + * @return \Drupal\Core\Routing\RouteMatchInterface + * The currently active route match object. + */ + public static function routeMatch() { + return static::getContainer()->get('current_route_match'); + } + + /** + * Gets the current active user. + * + * This method will return the \Drupal\Core\Session\AccountProxy object of the + * current user. You can use the \Drupal\user\Entity\User::load() method to + * load the full user entity object. For example: + * @code + * $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); + * @endcode + * + * @return \Drupal\Core\Session\AccountProxyInterface + */ + public static function currentUser() { + return static::getContainer()->get('current_user'); + } + + /** + * Retrieves the entity type manager. + * + * @return \Drupal\Core\Entity\EntityTypeManagerInterface + * The entity type manager. + */ + public static function entityTypeManager() { + return static::getContainer()->get('entity_type.manager'); + } + + /** + * Returns the current primary database. + * + * @return \Drupal\Core\Database\Connection + * The current active database's master connection. + */ + public static function database() { + return static::getContainer()->get('database'); + } + + /** + * Returns the requested cache bin. + * + * @param string $bin + * (optional) The cache bin for which the cache object should be returned, + * defaults to 'default'. + * + * @return \Drupal\Core\Cache\CacheBackendInterface + * The cache object associated with the specified bin. + * + * @ingroup cache + */ + public static function cache($bin = 'default') { + return static::getContainer()->get('cache.' . $bin); + } + + /** + * Retrieves the class resolver. + * + * This is to be used in procedural code such as module files to instantiate + * an object of a class that implements + * \Drupal\Core\DependencyInjection\ContainerInjectionInterface. + * + * One common use case is to provide a class which contains the actual code + * of a hook implementation, without having to create a service. + * + * @param string $class + * (optional) A class name to instantiate. + * + * @return \Drupal\Core\DependencyInjection\ClassResolverInterface|object + * The class resolver or if $class is provided, a class instance with a + * given class definition. + * + * @throws \InvalidArgumentException + * If $class does not exist. + */ + public static function classResolver($class = NULL) { + if ($class) { + return static::getContainer()->get('class_resolver')->getInstanceFromDefinition($class); + } + return static::getContainer()->get('class_resolver'); + } + + /** + * Returns an expirable key value store collection. + * + * @param string $collection + * The name of the collection holding key and value pairs. + * + * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface + * An expirable key value store collection. + */ + public static function keyValueExpirable($collection) { + return static::getContainer()->get('keyvalue.expirable')->get($collection); + } + + /** + * Returns the locking layer instance. + * + * @return \Drupal\Core\Lock\LockBackendInterface + * + * @ingroup lock + */ + public static function lock() { + return static::getContainer()->get('lock'); + } + + /** + * Retrieves a configuration object. + * + * This is the main entry point to the configuration API. Calling + * @code \Drupal::config('my_module.admin') @endcode will return a + * configuration object the my_module module can use to read its + * administrative settings. + * + * @param string $name + * The name of the configuration object to retrieve, which typically + * corresponds to a configuration file. For + * @code \Drupal::config('my_module.admin') @endcode, the configuration + * object returned will contain the content of the my_module.admin + * configuration file. + * + * @return \Drupal\Core\Config\ImmutableConfig + * An immutable configuration object. + */ + public static function config($name) { + return static::getContainer()->get('config.factory')->get($name); + } + + /** + * Retrieves the configuration factory. + * + * This is mostly used to change the override settings on the configuration + * factory. For example, changing the language, or turning all overrides on + * or off. + * + * @return \Drupal\Core\Config\ConfigFactoryInterface + * The configuration factory service. + */ + public static function configFactory() { + return static::getContainer()->get('config.factory'); + } + + /** + * Returns a queue for the given queue name. + * + * The following values can be set in your settings.php file's $settings + * array to define which services are used for queues: + * - queue_reliable_service_$name: The container service to use for the + * reliable queue $name. + * - queue_service_$name: The container service to use for the + * queue $name. + * - queue_default: The container service to use by default for queues + * without overrides. This defaults to 'queue.database'. + * + * @param string $name + * The name of the queue to work with. + * @param bool $reliable + * (optional) TRUE if the ordering of items and guaranteeing every item + * executes at least once is important, FALSE if scalability is the main + * concern. Defaults to FALSE. + * + * @return \Drupal\Core\Queue\QueueInterface + * The queue object for a given name. + */ + public static function queue($name, $reliable = FALSE) { + return static::getContainer()->get('queue')->get($name, $reliable); + } + + /** + * Returns a key/value storage collection. + * + * @param string $collection + * Name of the key/value collection to return. + * + * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface + */ + public static function keyValue($collection) { + return static::getContainer()->get('keyvalue')->get($collection); + } + + /** + * Returns the state storage service. + * + * Use this to store machine-generated data, local to a specific environment + * that does not need deploying and does not need human editing; for example, + * the last time cron was run. Data which needs to be edited by humans and + * needs to be the same across development, production, etc. environments + * (for example, the system maintenance message) should use \Drupal::config() instead. + * + * @return \Drupal\Core\State\StateInterface + */ + public static function state() { + return static::getContainer()->get('state'); + } + + /** + * Returns the default http client. + * + * @return \GuzzleHttp\Client + * A guzzle http client instance. + */ + public static function httpClient() { + return static::getContainer()->get('http_client'); + } + + /** + * Returns the entity query object for this entity type. + * + * @param string $entity_type + * The entity type (for example, node) for which the query object should be + * returned. + * @param string $conjunction + * (optional) Either 'AND' if all conditions in the query need to apply, or + * 'OR' if any of them is sufficient. Defaults to 'AND'. + * + * @return \Drupal\Core\Entity\Query\QueryInterface + * The query object that can query the given entity type. + */ + public static function entityQuery($entity_type, $conjunction = 'AND') { + return static::entityTypeManager()->getStorage($entity_type)->getQuery($conjunction); + } + + /** + * Returns the entity query aggregate object for this entity type. + * + * @param string $entity_type + * The entity type (for example, node) for which the query object should be + * returned. + * @param string $conjunction + * (optional) Either 'AND' if all conditions in the query need to apply, or + * 'OR' if any of them is sufficient. Defaults to 'AND'. + * + * @return \Drupal\Core\Entity\Query\QueryAggregateInterface + * The query object that can query the given entity type. + */ + public static function entityQueryAggregate($entity_type, $conjunction = 'AND') { + return static::entityTypeManager()->getStorage($entity_type)->getAggregateQuery($conjunction); + } + + /** + * Returns the flood instance. + * + * @return \Drupal\Core\Flood\FloodInterface + */ + public static function flood() { + return static::getContainer()->get('flood'); + } + + /** + * Returns the module handler. + * + * @return \Drupal\Core\Extension\ModuleHandlerInterface + */ + public static function moduleHandler() { + return static::getContainer()->get('module_handler'); + } + + /** + * Returns the typed data manager service. + * + * Use the typed data manager service for creating typed data objects. + * + * @return \Drupal\Core\TypedData\TypedDataManagerInterface + * The typed data manager. + * + * @see \Drupal\Core\TypedData\TypedDataManager::create() + */ + public static function typedDataManager() { + return static::getContainer()->get('typed_data_manager'); + } + + /** + * Returns the token service. + * + * @return \Drupal\Core\Utility\Token + * The token service. + */ + public static function token() { + return static::getContainer()->get('token'); + } + + /** + * Returns the URL generator service. + * + * @return \Drupal\Core\Routing\UrlGeneratorInterface + * The URL generator service. + */ + public static function urlGenerator() { + return static::getContainer()->get('url_generator'); + } + + /** + * Returns the link generator service. + * + * @return \Drupal\Core\Utility\LinkGeneratorInterface + */ + public static function linkGenerator() { + return static::getContainer()->get('link_generator'); + } + + /** + * Returns the string translation service. + * + * @return \Drupal\Core\StringTranslation\TranslationManager + * The string translation manager. + */ + public static function translation() { + return static::getContainer()->get('string_translation'); + } + + /** + * Returns the language manager service. + * + * @return \Drupal\Core\Language\LanguageManagerInterface + * The language manager. + */ + public static function languageManager() { + return static::getContainer()->get('language_manager'); + } + + /** + * Returns the CSRF token manager service. + * + * The generated token is based on the session ID of the current user. Normally, + * anonymous users do not have a session, so the generated token will be + * different on every page request. To generate a token for users without a + * session, manually start a session prior to calling this function. + * + * @return \Drupal\Core\Access\CsrfTokenGenerator + * The CSRF token manager. + * + * @see \Drupal\Core\Session\SessionManager::start() + */ + public static function csrfToken() { + return static::getContainer()->get('csrf_token'); + } + + /** + * Returns the transliteration service. + * + * @return \Drupal\Core\Transliteration\PhpTransliteration + * The transliteration manager. + */ + public static function transliteration() { + return static::getContainer()->get('transliteration'); + } + + /** + * Returns the form builder service. + * + * @return \Drupal\Core\Form\FormBuilderInterface + * The form builder. + */ + public static function formBuilder() { + return static::getContainer()->get('form_builder'); + } + + /** + * Gets the theme service. + * + * @return \Drupal\Core\Theme\ThemeManagerInterface + */ + public static function theme() { + return static::getContainer()->get('theme.manager'); + } + + /** + * Gets the syncing state. + * + * @return bool + * Returns TRUE is syncing flag set. + */ + public static function isConfigSyncing() { + return static::getContainer()->get('config.installer')->isSyncing(); + } + + /** + * Returns a channel logger object. + * + * @param string $channel + * The name of the channel. Can be any string, but the general practice is + * to use the name of the subsystem calling this. + * + * @return \Psr\Log\LoggerInterface + * The logger for this channel. + */ + public static function logger($channel) { + return static::getContainer()->get('logger.factory')->get($channel); + } + + /** + * Returns the menu tree. + * + * @return \Drupal\Core\Menu\MenuLinkTreeInterface + * The menu tree. + */ + public static function menuTree() { + return static::getContainer()->get('menu.link_tree'); + } + + /** + * Returns the path validator. + * + * @return \Drupal\Core\Path\PathValidatorInterface + */ + public static function pathValidator() { + return static::getContainer()->get('path.validator'); + } + + /** + * Returns the access manager service. + * + * @return \Drupal\Core\Access\AccessManagerInterface + * The access manager service. + */ + public static function accessManager() { + return static::getContainer()->get('access_manager'); + } + + /** + * Returns the redirect destination helper. + * + * @return \Drupal\Core\Routing\RedirectDestinationInterface + * The redirect destination helper. + */ + public static function destination() { + return static::getContainer()->get('redirect.destination'); + } + + /** + * Returns the entity definition update manager. + * + * @return \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface + * The entity definition update manager. + */ + public static function entityDefinitionUpdateManager() { + return static::getContainer()->get('entity.definition_update_manager'); + } + + /** + * Returns the time service. + * + * @return \Drupal\Component\Datetime\TimeInterface + * The time service. + */ + public static function time() { + return static::getContainer()->get('datetime.time'); + } + + /** + * Returns the messenger. + * + * @return \Drupal\Core\Messenger\MessengerInterface + * The messenger. + */ + public static function messenger() { + return static::getContainer()->get('messenger'); + } + +} diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-composer/web/index.php b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-composer/web/index.php new file mode 100644 index 00000000000..e69de29bb2d diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-git/.ddev/config.yaml b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-git/.ddev/config.yaml new file mode 100644 index 00000000000..288879ad974 --- /dev/null +++ b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-git/.ddev/config.yaml @@ -0,0 +1,2 @@ +# assume that drupal11-composer has been set up with no existing configuration +type: php diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-git/core/lib/Drupal.php b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-git/core/lib/Drupal.php new file mode 100644 index 00000000000..ceb4c53d5ec --- /dev/null +++ b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-git/core/lib/Drupal.php @@ -0,0 +1,748 @@ +acquire('stuff_lock'); + * // ... + * } + * + * // Correct procedural code. + * function hook_do_stuff() { + * $lock = \Drupal::lock()->acquire('stuff_lock'); + * // ... + * } + * + * // The preferred way: dependency injected code. + * function hook_do_stuff() { + * // Move the actual implementation to a class and instantiate it. + * $instance = new StuffDoingClass(\Drupal::lock()); + * $instance->doStuff(); + * + * // Or, even better, rely on the service container to avoid hard coding a + * // specific interface implementation, so that the actual logic can be + * // swapped. This might not always make sense, but in general it is a good + * // practice. + * \Drupal::service('stuff.doing')->doStuff(); + * } + * + * interface StuffDoingInterface { + * public function doStuff(); + * } + * + * class StuffDoingClass implements StuffDoingInterface { + * protected $lockBackend; + * + * public function __construct(LockBackendInterface $lock_backend) { + * $this->lockBackend = $lock_backend; + * } + * + * public function doStuff() { + * $lock = $this->lockBackend->acquire('stuff_lock'); + * // ... + * } + * } + * @endcode + * + * @see \Drupal\Core\DrupalKernel + */ +class Drupal { + + /** + * The current system version. + */ + const VERSION = '11.0-dev'; + + /** + * Core API compatibility. + * + * This constant is set to '8.x' to provide legacy compatibility with + * extensions that use the '8.x-' prefix to denote Drupal core major version + * compatibility, for example '8.x-1.0'. These extensions can specify + * compatibility with multiple major versions of Drupal core by setting the + * version constraint in 'core_version_requirement'. Drupal does not support + * using this core major version number prefix with versions greater than 8. + * For example '9.x-' prefixed extensions are not supported. + * + * @todo Remove or rename this constant in https://www.drupal.org/i/3085662 + */ + const CORE_COMPATIBILITY = '8.x'; + + /** + * Core minimum schema version. + */ + const CORE_MINIMUM_SCHEMA_VERSION = 8000; + + /** + * Minimum allowed version of PHP for Drupal to be bootstrapped. + * + * Below this version: + * - The installer cannot be run. + * - Updates cannot be run. + * - Modules and themes cannot be enabled. + * - If a site managed to bypass all of the above, then an error is shown in + * the status report and various fatal errors occur on various pages. + * + * Note: To prevent the installer from having fatal errors on older versions + * of PHP, the value of this constant is hardcoded twice in core/install.php: + * - Once as a parameter of version_compare() + * - Once in the error message printed to the user immediately after. + * Remember to update both whenever this constant is updated. + */ + const MINIMUM_PHP = '8.3.0'; + + /** + * Minimum recommended value of PHP memory_limit. + * + * 64M was chosen as a minimum requirement in order to allow for additional + * contributed modules to be installed prior to hitting the limit. However, + * 40M is the target for the Standard installation profile. + */ + const MINIMUM_PHP_MEMORY_LIMIT = '64M'; + + /** + * Minimum recommended version of PHP. + * + * Sites installing Drupal on PHP versions lower than this will see a warning + * message, but Drupal can still be installed. Used for (e.g.) PHP versions + * that have reached their EOL or will in the near future. + */ + const RECOMMENDED_PHP = '8.3.0'; + + /** + * The currently active container object, or NULL if not initialized yet. + * + * @var \Drupal\Component\DependencyInjection\ContainerInterface|null + */ + protected static $container; + + /** + * Sets a new global container. + * + * @param \Symfony\Component\DependencyInjection\ContainerInterface $container + * A new container instance to replace the current. + */ + public static function setContainer(ContainerInterface $container) { + static::$container = $container; + } + + /** + * Unsets the global container. + */ + public static function unsetContainer() { + static::$container = NULL; + } + + /** + * Returns the currently active global container. + * + * @return \Drupal\Component\DependencyInjection\ContainerInterface + * + * @throws \Drupal\Core\DependencyInjection\ContainerNotInitializedException + */ + public static function getContainer() { + if (static::$container === NULL) { + throw new ContainerNotInitializedException('\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.'); + } + return static::$container; + } + + /** + * Returns TRUE if the container has been initialized, FALSE otherwise. + * + * @return bool + */ + public static function hasContainer() { + return static::$container !== NULL; + } + + /** + * Retrieves a service from the container. + * + * Use this method if the desired service is not one of those with a dedicated + * accessor method below. If it is listed below, those methods are preferred + * as they can return useful type hints. + * + * @param string $id + * The ID of the service to retrieve. + * + * @return mixed + * The specified service. + */ + public static function service($id) { + return static::getContainer()->get($id); + } + + /** + * Indicates if a service is defined in the container. + * + * @param string $id + * The ID of the service to check. + * + * @return bool + * TRUE if the specified service exists, FALSE otherwise. + */ + public static function hasService($id) { + // Check hasContainer() first in order to always return a Boolean. + return static::hasContainer() && static::getContainer()->has($id); + } + + /** + * Gets the app root. + * + * @return string + */ + public static function root() { + return static::getContainer()->getParameter('app.root'); + } + + /** + * Gets the active install profile. + * + * @return string|false|null + * The name of the active install profile. FALSE indicates that the site is + * not using an install profile. NULL indicates that the site has not yet + * been installed. + */ + public static function installProfile() { + return static::getContainer()->getParameter('install_profile'); + } + + /** + * Indicates if there is a currently active request object. + * + * @return bool + * TRUE if there is a currently active request object, FALSE otherwise. + */ + public static function hasRequest() { + // Check hasContainer() first in order to always return a Boolean. + return static::hasContainer() && static::getContainer()->has('request_stack') && static::getContainer()->get('request_stack')->getCurrentRequest() !== NULL; + } + + /** + * Retrieves the currently active request object. + * + * Note: The use of this wrapper in particular is especially discouraged. Most + * code should not need to access the request directly. Doing so means it + * will only function when handling an HTTP request, and will require special + * modification or wrapping when run from a command line tool, from certain + * queue processors, or from automated tests. + * + * If code must access the request, it is considerably better to register + * an object with the Service Container and give it a setRequest() method + * that is configured to run when the service is created. That way, the + * correct request object can always be provided by the container and the + * service can still be unit tested. + * + * If this method must be used, never save the request object that is + * returned. Doing so may lead to inconsistencies as the request object is + * volatile and may change at various times, such as during a subrequest. + * + * @return \Symfony\Component\HttpFoundation\Request + * The currently active request object. + */ + public static function request() { + return static::getContainer()->get('request_stack')->getCurrentRequest(); + } + + /** + * Retrieves the request stack. + * + * @return \Symfony\Component\HttpFoundation\RequestStack + * The request stack + */ + public static function requestStack() { + return static::getContainer()->get('request_stack'); + } + + /** + * Retrieves the currently active route match object. + * + * @return \Drupal\Core\Routing\RouteMatchInterface + * The currently active route match object. + */ + public static function routeMatch() { + return static::getContainer()->get('current_route_match'); + } + + /** + * Gets the current active user. + * + * This method will return the \Drupal\Core\Session\AccountProxy object of the + * current user. You can use the \Drupal\user\Entity\User::load() method to + * load the full user entity object. For example: + * @code + * $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); + * @endcode + * + * @return \Drupal\Core\Session\AccountProxyInterface + */ + public static function currentUser() { + return static::getContainer()->get('current_user'); + } + + /** + * Retrieves the entity type manager. + * + * @return \Drupal\Core\Entity\EntityTypeManagerInterface + * The entity type manager. + */ + public static function entityTypeManager() { + return static::getContainer()->get('entity_type.manager'); + } + + /** + * Returns the current primary database. + * + * @return \Drupal\Core\Database\Connection + * The current active database's master connection. + */ + public static function database() { + return static::getContainer()->get('database'); + } + + /** + * Returns the requested cache bin. + * + * @param string $bin + * (optional) The cache bin for which the cache object should be returned, + * defaults to 'default'. + * + * @return \Drupal\Core\Cache\CacheBackendInterface + * The cache object associated with the specified bin. + * + * @ingroup cache + */ + public static function cache($bin = 'default') { + return static::getContainer()->get('cache.' . $bin); + } + + /** + * Retrieves the class resolver. + * + * This is to be used in procedural code such as module files to instantiate + * an object of a class that implements + * \Drupal\Core\DependencyInjection\ContainerInjectionInterface. + * + * One common use case is to provide a class which contains the actual code + * of a hook implementation, without having to create a service. + * + * @param string $class + * (optional) A class name to instantiate. + * + * @return \Drupal\Core\DependencyInjection\ClassResolverInterface|object + * The class resolver or if $class is provided, a class instance with a + * given class definition. + * + * @throws \InvalidArgumentException + * If $class does not exist. + */ + public static function classResolver($class = NULL) { + if ($class) { + return static::getContainer()->get('class_resolver')->getInstanceFromDefinition($class); + } + return static::getContainer()->get('class_resolver'); + } + + /** + * Returns an expirable key value store collection. + * + * @param string $collection + * The name of the collection holding key and value pairs. + * + * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface + * An expirable key value store collection. + */ + public static function keyValueExpirable($collection) { + return static::getContainer()->get('keyvalue.expirable')->get($collection); + } + + /** + * Returns the locking layer instance. + * + * @return \Drupal\Core\Lock\LockBackendInterface + * + * @ingroup lock + */ + public static function lock() { + return static::getContainer()->get('lock'); + } + + /** + * Retrieves a configuration object. + * + * This is the main entry point to the configuration API. Calling + * @code \Drupal::config('my_module.admin') @endcode will return a + * configuration object the my_module module can use to read its + * administrative settings. + * + * @param string $name + * The name of the configuration object to retrieve, which typically + * corresponds to a configuration file. For + * @code \Drupal::config('my_module.admin') @endcode, the configuration + * object returned will contain the content of the my_module.admin + * configuration file. + * + * @return \Drupal\Core\Config\ImmutableConfig + * An immutable configuration object. + */ + public static function config($name) { + return static::getContainer()->get('config.factory')->get($name); + } + + /** + * Retrieves the configuration factory. + * + * This is mostly used to change the override settings on the configuration + * factory. For example, changing the language, or turning all overrides on + * or off. + * + * @return \Drupal\Core\Config\ConfigFactoryInterface + * The configuration factory service. + */ + public static function configFactory() { + return static::getContainer()->get('config.factory'); + } + + /** + * Returns a queue for the given queue name. + * + * The following values can be set in your settings.php file's $settings + * array to define which services are used for queues: + * - queue_reliable_service_$name: The container service to use for the + * reliable queue $name. + * - queue_service_$name: The container service to use for the + * queue $name. + * - queue_default: The container service to use by default for queues + * without overrides. This defaults to 'queue.database'. + * + * @param string $name + * The name of the queue to work with. + * @param bool $reliable + * (optional) TRUE if the ordering of items and guaranteeing every item + * executes at least once is important, FALSE if scalability is the main + * concern. Defaults to FALSE. + * + * @return \Drupal\Core\Queue\QueueInterface + * The queue object for a given name. + */ + public static function queue($name, $reliable = FALSE) { + return static::getContainer()->get('queue')->get($name, $reliable); + } + + /** + * Returns a key/value storage collection. + * + * @param string $collection + * Name of the key/value collection to return. + * + * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface + */ + public static function keyValue($collection) { + return static::getContainer()->get('keyvalue')->get($collection); + } + + /** + * Returns the state storage service. + * + * Use this to store machine-generated data, local to a specific environment + * that does not need deploying and does not need human editing; for example, + * the last time cron was run. Data which needs to be edited by humans and + * needs to be the same across development, production, etc. environments + * (for example, the system maintenance message) should use \Drupal::config() instead. + * + * @return \Drupal\Core\State\StateInterface + */ + public static function state() { + return static::getContainer()->get('state'); + } + + /** + * Returns the default http client. + * + * @return \GuzzleHttp\Client + * A guzzle http client instance. + */ + public static function httpClient() { + return static::getContainer()->get('http_client'); + } + + /** + * Returns the entity query object for this entity type. + * + * @param string $entity_type + * The entity type (for example, node) for which the query object should be + * returned. + * @param string $conjunction + * (optional) Either 'AND' if all conditions in the query need to apply, or + * 'OR' if any of them is sufficient. Defaults to 'AND'. + * + * @return \Drupal\Core\Entity\Query\QueryInterface + * The query object that can query the given entity type. + */ + public static function entityQuery($entity_type, $conjunction = 'AND') { + return static::entityTypeManager()->getStorage($entity_type)->getQuery($conjunction); + } + + /** + * Returns the entity query aggregate object for this entity type. + * + * @param string $entity_type + * The entity type (for example, node) for which the query object should be + * returned. + * @param string $conjunction + * (optional) Either 'AND' if all conditions in the query need to apply, or + * 'OR' if any of them is sufficient. Defaults to 'AND'. + * + * @return \Drupal\Core\Entity\Query\QueryAggregateInterface + * The query object that can query the given entity type. + */ + public static function entityQueryAggregate($entity_type, $conjunction = 'AND') { + return static::entityTypeManager()->getStorage($entity_type)->getAggregateQuery($conjunction); + } + + /** + * Returns the flood instance. + * + * @return \Drupal\Core\Flood\FloodInterface + */ + public static function flood() { + return static::getContainer()->get('flood'); + } + + /** + * Returns the module handler. + * + * @return \Drupal\Core\Extension\ModuleHandlerInterface + */ + public static function moduleHandler() { + return static::getContainer()->get('module_handler'); + } + + /** + * Returns the typed data manager service. + * + * Use the typed data manager service for creating typed data objects. + * + * @return \Drupal\Core\TypedData\TypedDataManagerInterface + * The typed data manager. + * + * @see \Drupal\Core\TypedData\TypedDataManager::create() + */ + public static function typedDataManager() { + return static::getContainer()->get('typed_data_manager'); + } + + /** + * Returns the token service. + * + * @return \Drupal\Core\Utility\Token + * The token service. + */ + public static function token() { + return static::getContainer()->get('token'); + } + + /** + * Returns the URL generator service. + * + * @return \Drupal\Core\Routing\UrlGeneratorInterface + * The URL generator service. + */ + public static function urlGenerator() { + return static::getContainer()->get('url_generator'); + } + + /** + * Returns the link generator service. + * + * @return \Drupal\Core\Utility\LinkGeneratorInterface + */ + public static function linkGenerator() { + return static::getContainer()->get('link_generator'); + } + + /** + * Returns the string translation service. + * + * @return \Drupal\Core\StringTranslation\TranslationManager + * The string translation manager. + */ + public static function translation() { + return static::getContainer()->get('string_translation'); + } + + /** + * Returns the language manager service. + * + * @return \Drupal\Core\Language\LanguageManagerInterface + * The language manager. + */ + public static function languageManager() { + return static::getContainer()->get('language_manager'); + } + + /** + * Returns the CSRF token manager service. + * + * The generated token is based on the session ID of the current user. Normally, + * anonymous users do not have a session, so the generated token will be + * different on every page request. To generate a token for users without a + * session, manually start a session prior to calling this function. + * + * @return \Drupal\Core\Access\CsrfTokenGenerator + * The CSRF token manager. + * + * @see \Drupal\Core\Session\SessionManager::start() + */ + public static function csrfToken() { + return static::getContainer()->get('csrf_token'); + } + + /** + * Returns the transliteration service. + * + * @return \Drupal\Core\Transliteration\PhpTransliteration + * The transliteration manager. + */ + public static function transliteration() { + return static::getContainer()->get('transliteration'); + } + + /** + * Returns the form builder service. + * + * @return \Drupal\Core\Form\FormBuilderInterface + * The form builder. + */ + public static function formBuilder() { + return static::getContainer()->get('form_builder'); + } + + /** + * Gets the theme service. + * + * @return \Drupal\Core\Theme\ThemeManagerInterface + */ + public static function theme() { + return static::getContainer()->get('theme.manager'); + } + + /** + * Gets the syncing state. + * + * @return bool + * Returns TRUE is syncing flag set. + */ + public static function isConfigSyncing() { + return static::getContainer()->get('config.installer')->isSyncing(); + } + + /** + * Returns a channel logger object. + * + * @param string $channel + * The name of the channel. Can be any string, but the general practice is + * to use the name of the subsystem calling this. + * + * @return \Psr\Log\LoggerInterface + * The logger for this channel. + */ + public static function logger($channel) { + return static::getContainer()->get('logger.factory')->get($channel); + } + + /** + * Returns the menu tree. + * + * @return \Drupal\Core\Menu\MenuLinkTreeInterface + * The menu tree. + */ + public static function menuTree() { + return static::getContainer()->get('menu.link_tree'); + } + + /** + * Returns the path validator. + * + * @return \Drupal\Core\Path\PathValidatorInterface + */ + public static function pathValidator() { + return static::getContainer()->get('path.validator'); + } + + /** + * Returns the access manager service. + * + * @return \Drupal\Core\Access\AccessManagerInterface + * The access manager service. + */ + public static function accessManager() { + return static::getContainer()->get('access_manager'); + } + + /** + * Returns the redirect destination helper. + * + * @return \Drupal\Core\Routing\RedirectDestinationInterface + * The redirect destination helper. + */ + public static function destination() { + return static::getContainer()->get('redirect.destination'); + } + + /** + * Returns the entity definition update manager. + * + * @return \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface + * The entity definition update manager. + */ + public static function entityDefinitionUpdateManager() { + return static::getContainer()->get('entity.definition_update_manager'); + } + + /** + * Returns the time service. + * + * @return \Drupal\Component\Datetime\TimeInterface + * The time service. + */ + public static function time() { + return static::getContainer()->get('datetime.time'); + } + + /** + * Returns the messenger. + * + * @return \Drupal\Core\Messenger\MessengerInterface + * The messenger. + */ + public static function messenger() { + return static::getContainer()->get('messenger'); + } + +} diff --git a/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-git/index.php b/cmd/ddev/cmd/testdata/TestConfigUpdate/drupal11-git/index.php new file mode 100644 index 00000000000..e69de29bb2d diff --git a/docs/content/users/install/docker-installation.md b/docs/content/users/install/docker-installation.md index a33008b83fd..6e6a60706c7 100644 --- a/docs/content/users/install/docker-installation.md +++ b/docs/content/users/install/docker-installation.md @@ -48,7 +48,7 @@ You’ll need a Docker provider on your system before you can [install DDEV](dde Docker Desktop for Mac can be downloaded from [docker.com](https://www.docker.com/products/docker-desktop). It has long been supported by DDEV and has extensive automated testing. It is not open-source, may require a license for many users, and sometimes has stability problems. !!!warning "Ports unavailable?" - If you get messages like `Ports are not available... exposing port failed... is vmnetd running?` it means you need to check the "Allow privileged port mapping (requires password)" checkbox in the "Advanced" section of the Docker Desktop configuration. You may have to stop and restart Docker Desktop. (More extensive problem resolution is in [Docker Desktop issue](https://github.com/docker/for-mac/issues/6677).) + If you get messages like `Ports are not available... exposing port failed... is vmnetd running?` it means you need to check the "Allow privileged port mapping (requires password)" checkbox in the "Advanced" section of the Docker Desktop configuration. You may have to stop and restart Docker Desktop, and you may have to turn it off, restart Docker Desktop, turn it on again, restart Docker Desktop. (More extensive problem resolution is in [Docker Desktop issue](https://github.com/docker/for-mac/issues/6677).) ### Rancher Desktop diff --git a/docs/content/users/quickstart.md b/docs/content/users/quickstart.md index b0135f87002..fa582fe46c7 100644 --- a/docs/content/users/quickstart.md +++ b/docs/content/users/quickstart.md @@ -171,6 +171,7 @@ For all versions of Drupal 8+ the Composer techniques work. The settings configu ddev config --project-type=drupal --php-version=8.3 --docroot=web ddev start ddev composer create drupal/recommended-project:^10 + ddev config --update ddev composer require drush/drush ddev drush site:install --account-name=admin --account-pass=admin -y # use the one-time link (CTRL/CMD + Click) from the command below to edit your admin account details. @@ -181,11 +182,11 @@ For all versions of Drupal 8+ the Composer techniques work. The settings configu === "Drupal 11 (dev)" ```bash - mkdir my-drupal-site - cd my-drupal-site - ddev config --project-type=drupal --php-version=8.3 --docroot=web --corepack-enable + mkdir my-drupal-site && cd my-drupal-site + ddev config --project-type=drupal --php-version=8.3 --docroot=web ddev start ddev composer create drupal/recommended-project:^11.x-dev + ddev config --update ddev composer require drush/drush ddev drush site:install --account-name=admin --account-pass=admin -y # use the one-time link (CTRL/CMD + Click) from the command below to edit your admin account details. @@ -201,6 +202,7 @@ For all versions of Drupal 8+ the Composer techniques work. The settings configu ddev config --project-type=drupal --php-version=8.1 --docroot=web ddev start ddev composer create drupal/recommended-project:^9 + ddev config --update ddev composer require drush/drush ddev drush site:install --account-name=admin --account-pass=admin -y # use the one-time link (CTRL/CMD + Click) from the command below to edit your admin account details. diff --git a/docs/content/users/usage/cli.md b/docs/content/users/usage/cli.md index 1d01c87999c..81d7286a3f2 100644 --- a/docs/content/users/usage/cli.md +++ b/docs/content/users/usage/cli.md @@ -2,7 +2,7 @@ Type `ddev` or `ddev -h` in a terminal window to see the available DDEV [commands](../usage/commands.md). There are commands to configure a project, start, stop, describe, etc. Each command also has help using `ddev help ` or `ddev command -h`. For example, `ddev help snapshot` will show help and examples for the snapshot command. -* [`ddev config`](../usage/commands.md#config) configures a project’s type and docroot. +* [`ddev config`](../usage/commands.md#config) configures a project’s type and docroot, either interactively or with flags. * [`ddev start`](../usage/commands.md#start) starts up a project. * [`ddev launch`](../usage/commands.md#launch) opens a web browser showing the project. * [`ddev list`](../usage/commands.md#list) shows current projects and their state. diff --git a/docs/content/users/usage/commands.md b/docs/content/users/usage/commands.md index ccdd6939747..81037b97c80 100644 --- a/docs/content/users/usage/commands.md +++ b/docs/content/users/usage/commands.md @@ -162,7 +162,7 @@ ddev composer create drupal/recommended-project ## `config` -Create or modify a DDEV project’s configuration in the current directory. +Create or modify a DDEV project’s configuration in the current directory. By default, `ddev config` will not change configuration that already exists in your `.ddev/config.yaml`, it will only make changes you specify with flags. However, if you want to autodetect everything, `ddev config --update` will usually do everything you need. !!!tip "You can also set these via YAML!" These settings, plus a few more, can be set by editing stored [Config Options](../configuration/config.md). @@ -173,6 +173,13 @@ Example: # Start interactive project configuration ddev config +# Accept defaults on a new project. This is the same as hitting +# on every question in `ddev config` +ddev config --auto + +## Detect docroot, project type, and expected defaults for an existing project +ddev config --update + # Configure a Drupal project with a `web` document root ddev config --docroot=web --project-type=drupal @@ -184,7 +191,7 @@ Flags: * `--additional-fqdns`: Comma-delimited list of project FQDNs. * `--additional-hostnames`: Comma-delimited list of project hostnames. -* `--auto`: Automatically run config without prompting. (default `true`) +* `--auto`: Automatically run config without prompting. * `--bind-all-interfaces`: Bind host ports on all interfaces, not only on localhost network interface. * `--composer-root`: Overrides the default Composer root directory for the web service. * `--composer-root-default`: Unsets a web service Composer root directory override. @@ -220,6 +227,7 @@ Flags: * `--project-type`: Provide the project type: `backdrop`, `drupal`, `drupal6`, `drupal7`, `laravel`, `magento`, `magento2`, `php`, `shopware6`, `silverstripe`, `typo3`, `wordpress`. This is autodetected and this flag is necessary only to override the detection. * `--show-config-location`: Output the location of the `config.yaml` file if it exists, or error that it doesn’t exist. * `--timezone`: Specify timezone for containers and PHP, like `Europe/London` or `America/Denver` or `GMT` or `UTC`. +* `--update`: Automatically detect and update settings by inspecting the code. * `--upload-dirs`: Sets the project’s upload directories, the destination directories of the import-files command. * `--use-dns-when-possible`: Use DNS for hostname resolution instead of `/etc/hosts` when possible. (default `true`) * `--web-environment`: Set the environment variables in the web container: `--web-environment="TYPO3_CONTEXT=Development,SOMEENV=someval"` diff --git a/pkg/ddevapp/apptypes.go b/pkg/ddevapp/apptypes.go index f83232d124d..8ab12abb9cd 100644 --- a/pkg/ddevapp/apptypes.go +++ b/pkg/ddevapp/apptypes.go @@ -386,10 +386,31 @@ func (app *DdevApp) PostImportDBAction() error { } // ConfigFileOverrideAction gives a chance for an apptype to override any element -// of config.yaml that it needs to (on initial creation, but not after that) -func (app *DdevApp) ConfigFileOverrideAction() error { - if appFuncs, ok := appTypeMatrix[app.Type]; ok && appFuncs.configOverrideAction != nil && !app.ConfigExists() { - return appFuncs.configOverrideAction(app) +// of config.yaml that it needs to +func (app *DdevApp) ConfigFileOverrideAction(overrideExistingConfig bool) error { + if appFuncs, ok := appTypeMatrix[app.Type]; ok && appFuncs.configOverrideAction != nil && (overrideExistingConfig || !app.ConfigExists()) { + origDB := app.Database + err := appFuncs.configOverrideAction(app) + if err != nil { + return err + } + // If the override function has changed the database type + // check to make sure that there's not one already existing + if origDB != app.Database { + // We can't upgrade database if it already exists + dbType, err := app.GetExistingDBType() + if err != nil { + return err + } + recommendedDBType := app.Database.Type + ":" + app.Database.Version + if dbType == "" { + // Assume that we don't have a database yet + util.Success("Configuring %s project with database type '%s'", app.Type, recommendedDBType) + } else if dbType != recommendedDBType { + util.Warning("%s project already has database type set to non-recommended: %s, not changing it to recommended %s", app.Type, dbType, recommendedDBType) + app.Database = origDB + } + } } return nil diff --git a/pkg/ddevapp/apptypes_test.go b/pkg/ddevapp/apptypes_test.go index d2201bc8c4f..6ff7af85f52 100644 --- a/pkg/ddevapp/apptypes_test.go +++ b/pkg/ddevapp/apptypes_test.go @@ -96,7 +96,7 @@ func TestConfigOverrideAction(t *testing.T) { fmt.Println("") // With no config file written, the ConfigFileOverrideAction should result in an override - err = app.ConfigFileOverrideAction() + err = app.ConfigFileOverrideAction(true) assert.NoError(err) // With a basic new app, the expectedPHPVersion should be the default @@ -106,11 +106,60 @@ func TestConfigOverrideAction(t *testing.T) { app.PHPVersion = newVersion err = app.WriteConfig() assert.NoError(err) - err = app.ConfigFileOverrideAction() + err = app.ConfigFileOverrideAction(false) assert.NoError(err) // But with a config that has been written with a specified version, the version should be untouched by // app.ConfigFileOverrideAction() assert.EqualValues(app.PHPVersion, newVersion) } +} + +// TestConfigOverrideActionOnExistingConfig tests that the ConfigOverride action is properly applied, even if the config +// existed when the override flag is enabled. +func TestConfigOverrideActionOnExistingConfig(t *testing.T) { + assert := asrt.New(t) + origDir, _ := os.Getwd() + + // This will only work for those project types defining configOverrideAction and altering php version + appTypes := map[string]string{ + nodeps.AppTypeCakePHP: nodeps.PHP83, + nodeps.AppTypeDrupal6: nodeps.PHP56, + nodeps.AppTypeDrupal7: nodeps.PHP82, + // For AppTypeDrupal we can't guess a version without a working installation. + } + + for appType, expectedPHPVersion := range appTypes { + testDir := testcommon.CreateTmpDir(t.Name()) + + app, err := ddevapp.NewApp(testDir, true) + assert.NoError(err) + + t.Cleanup(func() { + err = os.Chdir(origDir) + assert.NoError(err) + err = app.Stop(true, false) + assert.NoError(err) + _ = os.RemoveAll(testDir) + }) + + // Prompt for apptype as a way to get it into the config. + input := fmt.Sprintf(appType + "\n") + scanner := bufio.NewScanner(strings.NewReader(input)) + util.SetInputScanner(scanner) + err = app.AppTypePrompt() + assert.NoError(err) + fmt.Println("") + // We write the config first time. + newVersion := "19.0-" + appType + app.PHPVersion = newVersion + err = app.WriteConfig() + + assert.EqualValues(newVersion, app.PHPVersion, "expected PHP version %s but got %s for apptype=%s", newVersion, app.PHPVersion, appType) + + err = app.ConfigFileOverrideAction(true) + assert.NoError(err) + // We can override existing config. + assert.EqualValues(expectedPHPVersion, app.PHPVersion, "expected PHP version %s but got %s for apptype=%s", expectedPHPVersion, app.PHPVersion, appType) + } } diff --git a/pkg/ddevapp/config.go b/pkg/ddevapp/config.go index 28feb54beb2..2c2e83962ab 100644 --- a/pkg/ddevapp/config.go +++ b/pkg/ddevapp/config.go @@ -417,7 +417,7 @@ func (app *DdevApp) PromptForConfig() error { return err } - err = app.ConfigFileOverrideAction() + err = app.ConfigFileOverrideAction(false) if err != nil { return err } diff --git a/pkg/testcommon/testcommon.go b/pkg/testcommon/testcommon.go index a3c8e17fc75..c13bc5b41dd 100644 --- a/pkg/testcommon/testcommon.go +++ b/pkg/testcommon/testcommon.go @@ -114,6 +114,9 @@ func (site *TestSite) Prepare() error { } output.UserOut.Println("Copying complete") + // Remove existing in project registry + _ = globalconfig.RemoveProjectInfo(site.Name) + // Create an app. Err is ignored as we may not have // a config file to read in from a test site. app, err := ddevapp.NewApp(site.Dir, true) @@ -138,7 +141,7 @@ func (site *TestSite) Prepare() error { }, } } - err = app.ConfigFileOverrideAction() + err = app.ConfigFileOverrideAction(false) util.CheckErr(err) err = os.MkdirAll(filepath.Join(app.AppRoot, app.Docroot, app.GetUploadDir()), 0777)