Initial Drupal 11 with DDEV setup

This commit is contained in:
gluebox
2025-10-08 11:39:17 -04:00
commit 89ef74b305
25344 changed files with 2599172 additions and 0 deletions

View File

@ -0,0 +1,81 @@
<?php
namespace Drupal\config_translation\Access;
use Drupal\config_translation\ConfigMapperInterface;
use Drupal\config_translation\Exception\ConfigMapperLanguageException;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Checks access for displaying the translation add, edit, and delete forms.
*/
class ConfigTranslationFormAccess extends ConfigTranslationOverviewAccess {
/**
* Checks access to the overview based on permissions and translatability.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route_match to check against.
* @param \Drupal\Core\Session\AccountInterface $account
* The account to check access for.
* @param string $langcode
* The language code of the target language.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access(RouteMatchInterface $route_match, AccountInterface $account, $langcode = NULL) {
$mapper = $this->getMapperFromRouteMatch($route_match);
try {
$source_langcode = $mapper->getLangcode();
$source_language = $this->languageManager->getLanguage($source_langcode);
$target_language = $this->languageManager->getLanguage($langcode);
return $this->doCheckAccess($account, $mapper, $source_language, $target_language);
}
catch (ConfigMapperLanguageException) {
return AccessResult::forbidden();
}
}
/**
* Checks access given an account, configuration mapper, and source language.
*
* In addition to the checks performed by
* ConfigTranslationOverviewAccess::doCheckAccess() this makes sure the target
* language is not locked and the target language is not the source language.
*
* Although technically configuration can be overlaid with translations in the
* same language, that is logically not a good idea.
*
* @param \Drupal\Core\Session\AccountInterface $account
* The account to check access for.
* @param \Drupal\config_translation\ConfigMapperInterface $mapper
* The configuration mapper to check access for.
* @param \Drupal\Core\Language\LanguageInterface|null $source_language
* The source language to check for, if any.
* @param \Drupal\Core\Language\LanguageInterface|null $target_language
* The target language to check for, if any.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The result of the access check.
*
* @see \Drupal\config_translation\Access\ConfigTranslationOverviewAccess::doCheckAccess()
*/
protected function doCheckAccess(AccountInterface $account, ConfigMapperInterface $mapper, $source_language = NULL, $target_language = NULL) {
$base_access_result = parent::doCheckAccess($account, $mapper, $source_language);
$access =
$target_language &&
!$target_language->isLocked() &&
(!$source_language || ($target_language->getId() !== $source_language->getId()));
return $base_access_result->andIf(AccessResult::allowedIf($access));
}
}

View File

@ -0,0 +1,116 @@
<?php
namespace Drupal\config_translation\Access;
use Drupal\config_translation\ConfigMapperInterface;
use Drupal\config_translation\Exception\ConfigMapperLanguageException;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\config_translation\ConfigMapperManagerInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Checks access for displaying the configuration translation overview.
*/
class ConfigTranslationOverviewAccess implements AccessInterface {
/**
* The mapper plugin discovery service.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface
*/
protected $configMapperManager;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* Constructs a ConfigTranslationOverviewAccess object.
*
* @param \Drupal\config_translation\ConfigMapperManagerInterface $config_mapper_manager
* The mapper plugin discovery service.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager service.
*/
public function __construct(ConfigMapperManagerInterface $config_mapper_manager, LanguageManagerInterface $language_manager) {
$this->configMapperManager = $config_mapper_manager;
$this->languageManager = $language_manager;
}
/**
* Checks access to the overview based on permissions and translatability.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route_match to check against.
* @param \Drupal\Core\Session\AccountInterface $account
* The account to check access for.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access(RouteMatchInterface $route_match, AccountInterface $account) {
$mapper = $this->getMapperFromRouteMatch($route_match);
try {
$langcode = $mapper->getLangcode();
}
catch (ConfigMapperLanguageException) {
// ConfigTranslationController shows a helpful message if the language
// codes do not match, so do not let that prevent granting access.
$langcode = 'en';
}
$source_language = $this->languageManager->getLanguage($langcode);
return $this->doCheckAccess($account, $mapper, $source_language);
}
/**
* Gets a configuration mapper using a route match.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match to populate the mapper with.
*
* @return \Drupal\config_translation\ConfigMapperInterface
* The configuration mapper.
*/
protected function getMapperFromRouteMatch(RouteMatchInterface $route_match) {
$mapper = $this->configMapperManager->createInstance($route_match->getRouteObject()
->getDefault('plugin_id'));
$mapper->populateFromRouteMatch($route_match);
return $mapper;
}
/**
* Checks access given an account, configuration mapper, and source language.
*
* Grants access if the proper permission is granted to the account, the
* configuration has translatable pieces, and the source language is not
* locked given it is present.
*
* @param \Drupal\Core\Session\AccountInterface $account
* The account to check access for.
* @param \Drupal\config_translation\ConfigMapperInterface $mapper
* The configuration mapper to check access for.
* @param \Drupal\Core\Language\LanguageInterface|null $source_language
* The source language to check for, if any.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The result of the access check.
*/
protected function doCheckAccess(AccountInterface $account, ConfigMapperInterface $mapper, $source_language = NULL) {
$access =
$account->hasPermission('translate configuration') &&
$mapper->hasSchema() &&
$mapper->hasTranslatable() &&
(!$source_language || !$source_language->isLocked());
return AccessResult::allowedIf($access)->cachePerPermissions();
}
}

View File

@ -0,0 +1,248 @@
<?php
namespace Drupal\config_translation;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Url;
use Drupal\locale\LocaleConfigManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\Route;
/**
* Configuration mapper for configuration entities.
*/
class ConfigEntityMapper extends ConfigNamesMapper implements ConfigEntityMapperInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Configuration entity type name.
*
* @var string
*/
protected $entityType;
/**
* Loaded entity instance to help produce the translation interface.
*
* @var \Drupal\Core\Config\Entity\ConfigEntityInterface
*/
protected $entity;
/**
* The label for the entity type.
*
* @var string
*/
protected $typeLabel;
/**
* Constructs a ConfigEntityMapper.
*
* @param string $plugin_id
* The config mapper plugin ID.
* @param mixed $plugin_definition
* An array of plugin information as documented in
* ConfigNamesMapper::__construct() with the following additional keys:
* - entity_type: The name of the entity type this mapper belongs to.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
* @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
* The typed configuration manager.
* @param \Drupal\locale\LocaleConfigManager $locale_config_manager
* The locale configuration manager.
* @param \Drupal\config_translation\ConfigMapperManagerInterface $config_mapper_manager
* The mapper plugin discovery service.
* @param \Drupal\Core\Routing\RouteProviderInterface $route_provider
* The route provider.
* @param \Drupal\Core\StringTranslation\TranslationInterface $translation_manager
* The string translation manager.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Symfony\Contracts\EventDispatcher\EventDispatcherInterface $event_dispatcher
* The event dispatcher.
*/
public function __construct($plugin_id, $plugin_definition, ConfigFactoryInterface $config_factory, TypedConfigManagerInterface $typed_config, LocaleConfigManager $locale_config_manager, ConfigMapperManagerInterface $config_mapper_manager, RouteProviderInterface $route_provider, TranslationInterface $translation_manager, EntityTypeManagerInterface $entity_type_manager, LanguageManagerInterface $language_manager, ?EventDispatcherInterface $event_dispatcher = NULL) {
parent::__construct($plugin_id, $plugin_definition, $config_factory, $typed_config, $locale_config_manager, $config_mapper_manager, $route_provider, $translation_manager, $language_manager, $event_dispatcher);
$this->setType($plugin_definition['entity_type']);
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
// Note that we ignore the plugin $configuration because mappers have
// nothing to configure in themselves.
return new static(
$plugin_id,
$plugin_definition,
$container->get('config.factory'),
$container->get('config.typed'),
$container->get('locale.config_manager'),
$container->get('plugin.manager.config_translation.mapper'),
$container->get('router.route_provider'),
$container->get('string_translation'),
$container->get('entity_type.manager'),
$container->get('language_manager'),
$container->get('event_dispatcher')
);
}
/**
* {@inheritdoc}
*/
public function populateFromRouteMatch(RouteMatchInterface $route_match) {
$entity = $route_match->getParameter($this->entityType);
$this->setEntity($entity);
parent::populateFromRouteMatch($route_match);
}
/**
* {@inheritdoc}
*/
public function getEntity() {
return $this->entity;
}
/**
* {@inheritdoc}
*/
public function setEntity(ConfigEntityInterface $entity) {
if (isset($this->entity)) {
return FALSE;
}
$this->entity = $entity;
// Add the list of configuration IDs belonging to this entity. We add on a
// possibly existing list of names. This allows modules to alter the entity
// page with more names if form altering added more configuration to an
// entity. This is not a Drupal 8 best practice (ideally the configuration
// would have pluggable components), but this may happen as well.
/** @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface $entity_type_info */
$entity_type_info = $this->entityTypeManager->getDefinition($this->entityType);
$this->addConfigName($entity_type_info->getConfigPrefix() . '.' . $entity->id());
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getTitle() {
return $this->entity->label() . ' ' . $this->pluginDefinition['title'];
}
/**
* {@inheritdoc}
*/
public function getBaseRouteParameters() {
return [$this->entityType => $this->entity->id()];
}
/**
* {@inheritdoc}
*/
public function setType(string $entity_type_id): bool {
if (isset($this->entityType)) {
return FALSE;
}
$this->entityType = $entity_type_id;
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getType(): string {
return $this->entityType;
}
/**
* {@inheritdoc}
*/
public function getTypeName() {
$entity_type_info = $this->entityTypeManager->getDefinition($this->entityType);
return $entity_type_info->getLabel();
}
/**
* {@inheritdoc}
*/
public function getTypeLabel() {
$entityType = $this->entityTypeManager->getDefinition($this->entityType);
return $entityType->getLabel();
}
/**
* {@inheritdoc}
*/
public function getOperations() {
return [
'list' => [
'title' => $this->t('List'),
'url' => Url::fromRoute('config_translation.entity_list', [
'mapper_id' => $this->getPluginId(),
]),
],
];
}
/**
* {@inheritdoc}
*/
public function getContextualLinkGroup() {
// @todo Contextual groups do not map to entity types in a predictable
// way. See https://www.drupal.org/node/2134841 to make them predictable.
switch ($this->entityType) {
case 'menu':
case 'block':
return $this->entityType;
case 'view':
return 'entity.view.edit_form';
default:
return NULL;
}
}
/**
* {@inheritdoc}
*/
public function getOverviewRouteName() {
return 'entity.' . $this->entityType . '.config_translation_overview';
}
/**
* {@inheritdoc}
*/
protected function processRoute(Route $route) {
// Add entity upcasting information.
$parameters = $route->getOption('parameters') ?: [];
$parameters += [
$this->entityType => [
'type' => 'entity:' . $this->entityType,
],
];
$route->setOption('parameters', $parameters);
}
}

View File

@ -0,0 +1,62 @@
<?php
namespace Drupal\config_translation;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Defines an interface for configuration entity mappers.
*/
interface ConfigEntityMapperInterface extends ConfigMapperInterface {
/**
* Gets the entity instance for this mapper.
*
* @return \Drupal\Core\Config\Entity\ConfigEntityInterface
* The configuration entity.
*/
public function getEntity();
/**
* Sets the entity instance for this mapper.
*
* This method can only be invoked when the concrete entity is known, that is
* in a request for an entity translation path. After this method is called,
* the mapper is fully populated with the proper display title and
* configuration names to use to check permissions or display a translation
* screen.
*
* @param \Drupal\Core\Config\Entity\ConfigEntityInterface $entity
* The configuration entity to set.
*
* @return bool
* TRUE, if the entity was set successfully; FALSE otherwise.
*/
public function setEntity(ConfigEntityInterface $entity);
/**
* Set entity type for this mapper.
*
* This should be set in initialization. A mapper that knows its type but
* not yet its names is still useful for router item and tab generation. The
* concrete entity only turns out later with actual controller invocations,
* when the setEntity() method is invoked before the rest of the methods are
* used.
*
* @param string $entity_type_id
* The entity type ID to set.
*
* @return bool
* TRUE if the entity type ID was set correctly; FALSE otherwise.
*/
public function setType(string $entity_type_id): bool;
/**
* Gets the entity type ID from this mapper.
*
* @return string
* The entity type ID.
*/
public function getType(): string;
}

View File

@ -0,0 +1,68 @@
<?php
namespace Drupal\config_translation;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Configuration mapper for fields.
*
* On top of plugin definition values on ConfigEntityMapper, the plugin
* definition for field mappers are required to contain the following
* additional keys:
* - base_entity_type: The name of the entity type the fields are attached to.
*/
class ConfigFieldMapper extends ConfigEntityMapper {
/**
* Loaded entity instance to help produce the translation interface.
*
* @var \Drupal\field\FieldConfigInterface
*/
protected $entity;
/**
* {@inheritdoc}
*/
public function getBaseRouteParameters() {
$parameters = parent::getBaseRouteParameters();
$base_entity_info = $this->entityTypeManager->getDefinition($this->pluginDefinition['base_entity_type']);
$bundle_parameter_key = $base_entity_info->getBundleEntityType() ?: 'bundle';
$parameters[$bundle_parameter_key] = $this->entity->getTargetBundle();
return $parameters;
}
/**
* {@inheritdoc}
*/
public function getOverviewRouteName() {
return 'entity.field_config.config_translation_overview.' . $this->pluginDefinition['base_entity_type'];
}
/**
* {@inheritdoc}
*/
public function getTypeLabel() {
$base_entity_info = $this->entityTypeManager->getDefinition($this->pluginDefinition['base_entity_type']);
return $this->t('@label fields', ['@label' => $base_entity_info->getLabel()]);
}
/**
* {@inheritdoc}
*/
public function setEntity(ConfigEntityInterface $entity) {
if (parent::setEntity($entity)) {
// Field storage config can also contain translatable values. Add the name
// of the config as well to the list of configs for this entity.
/** @var \Drupal\field\FieldStorageConfigInterface $field_storage */
$field_storage = $this->entity->getFieldStorageDefinition();
/** @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface $entity_type_info */
$entity_type_info = $this->entityTypeManager->getDefinition($field_storage->getEntityTypeId());
$this->addConfigName($entity_type_info->getConfigPrefix() . '.' . $field_storage->id());
return TRUE;
}
return FALSE;
}
}

View File

@ -0,0 +1,307 @@
<?php
namespace Drupal\config_translation;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\Routing\RouteCollection;
/**
* Defines an interface for configuration mapper.
*/
interface ConfigMapperInterface {
/**
* Returns title of this translation page.
*
* @return string
* The page title.
*/
public function getTitle();
/**
* Sets the route collection.
*
* @param \Symfony\Component\Routing\RouteCollection $collection
* The route collection.
*/
public function setRouteCollection(RouteCollection $collection);
/**
* Returns the name of the base route the mapper is attached to.
*
* @return string
* The name of the base route the mapper is attached to.
*/
public function getBaseRouteName();
/**
* Returns the route parameters for the base route the mapper is attached to.
*
* @return array
* An array of route parameters for the base route.
*/
public function getBaseRouteParameters();
/**
* Returns the base route object the mapper is attached to.
*
* @return \Symfony\Component\Routing\Route
* The base route object the mapper is attached to.
*/
public function getBaseRoute();
/**
* Returns a processed path for the base route the mapper is attached to.
*
* @return string
* Processed path with placeholders replaced.
*/
public function getBasePath();
/**
* Returns route name for the translation overview route.
*
* @return string
* Route name for the mapper.
*/
public function getOverviewRouteName();
/**
* Returns the route parameters for the translation overview route.
*
* @return array
* An array of route parameters for the translation overview route.
*/
public function getOverviewRouteParameters();
/**
* Returns the route object for a translation overview route.
*
* @return \Symfony\Component\Routing\Route
* The route object for the translation page.
*/
public function getOverviewRoute();
/**
* Returns a processed path for the translation overview route.
*
* @return string
* Processed path with placeholders replaced.
*/
public function getOverviewPath();
/**
* Returns route name for the translation add form route.
*
* @return string
* Route name for the mapper.
*/
public function getAddRouteName();
/**
* Returns the route parameters for the translation add form route.
*
* @return array
* An array of route parameters for the translation add form route.
*/
public function getAddRouteParameters();
/**
* Returns the route object for a translation add form route.
*
* @return \Symfony\Component\Routing\Route
* The route object for the translation page.
*/
public function getAddRoute();
/**
* Returns route name for the translation edit form route.
*
* @return string
* Route name for the mapper.
*/
public function getEditRouteName();
/**
* Returns the route parameters for the translation edit form route.
*
* @return array
* An array of route parameters for the translation edit form route.
*/
public function getEditRouteParameters();
/**
* Returns the route object for a translation edit form route.
*
* @return \Symfony\Component\Routing\Route
* The route object for the translation page.
*/
public function getEditRoute();
/**
* Returns route name for the translation deletion route.
*
* @return string
* Route name for the mapper.
*/
public function getDeleteRouteName();
/**
* Returns the route parameters for the translation deletion route.
*
* @return array
* An array of route parameters for the translation deletion route.
*/
public function getDeleteRouteParameters();
/**
* Returns the route object for the translation deletion route.
*
* @return \Symfony\Component\Routing\Route
* The route object for the translation page.
*/
public function getDeleteRoute();
/**
* Returns an array of configuration names for the mapper.
*
* @return array
* An array of configuration names for the mapper.
*/
public function getConfigNames();
/**
* Adds the given configuration name to the list of names.
*
* Note that it is the responsibility of the calling code to ensure that the
* configuration exists.
*
* @param string $name
* Configuration name.
*/
public function addConfigName($name);
/**
* Returns the weight of the mapper.
*
* @return int
* The weight of the mapper.
*/
public function getWeight();
/**
* Returns an array with all configuration data.
*
* @return array
* Configuration data keyed by configuration names.
*/
public function getConfigData();
/**
* Returns the original language code of the configuration.
*
* @throws \RuntimeException
* Throws an exception if the language codes in the config files don't
* match.
*/
public function getLangcode();
/**
* Returns the language code of a configuration object given its name.
*
* @param string $config_name
* The name of the configuration object.
*
* @return string
* The language code of the configuration object.
*/
public function getLangcodeFromConfig($config_name);
/**
* Sets the original language code.
*
* @param string $langcode
* The langcode.
*
* @return $this
*/
public function setLangcode($langcode);
/**
* Returns the name of the type of data the mapper encapsulates.
*
* @return string
* The name of the type of data the mapper encapsulates.
*/
public function getTypeName();
/**
* Provides an array of information to build a list of operation links.
*
* @return array
* An associative array of operation link data for this list, keyed by
* operation name, containing the following key-value pairs:
* - title: The localized title of the operation.
* - href: The path for the operation.
* - options: An array of URL options for the path.
* - weight: The weight of this operation.
*/
public function getOperations();
/**
* Returns the label of the type of data the mapper encapsulates.
*
* @return string
* The label of the type of data the mapper encapsulates.
*/
public function getTypeLabel();
/**
* Checks that all pieces of this configuration mapper have a schema.
*
* @return bool
* TRUE if all of the elements have schema, FALSE otherwise.
*/
public function hasSchema();
/**
* Checks if pieces of this configuration mapper have translatables.
*
* @return bool
* TRUE if at least one of the configuration elements has translatables,
* FALSE otherwise.
*/
public function hasTranslatable();
/**
* Checks whether there is already a translation for this mapper.
*
* @param \Drupal\Core\Language\LanguageInterface $language
* A language object.
*
* @return bool
* TRUE if any of the configuration elements have a translation in the
* given language, FALSE otherwise.
*/
public function hasTranslation(LanguageInterface $language);
/**
* Populate the config mapper with route match data.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
*
* @see \Drupal\config_translation\Event\ConfigTranslationEvents::POPULATE_MAPPER
*/
public function populateFromRouteMatch(RouteMatchInterface $route_match);
/**
* Returns the name of the contextual link group to add contextual links to.
*
* @return string|null
* A contextual link group name or null if no link should be added.
*/
public function getContextualLinkGroup();
}

View File

@ -0,0 +1,219 @@
<?php
namespace Drupal\config_translation;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Plugin\Discovery\InfoHookDecorator;
use Drupal\Core\Plugin\Discovery\YamlDiscovery;
use Drupal\Core\Plugin\Discovery\ContainerDerivativeDiscoveryDecorator;
use Drupal\Core\Plugin\Factory\ContainerFactory;
use Drupal\Core\TypedData\TraversableTypedDataInterface;
use Drupal\Core\TypedData\TypedDataInterface;
use Symfony\Component\Routing\RouteCollection;
/**
* Manages plugins for configuration translation mappers.
*/
class ConfigMapperManager extends DefaultPluginManager implements ConfigMapperManagerInterface {
/**
* The typed config manager.
*
* @var \Drupal\Core\Config\TypedConfigManagerInterface
*/
protected $typedConfigManager;
/**
* The theme handler.
*
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected LanguageManagerInterface $languageManager;
/**
* {@inheritdoc}
*/
protected $defaults = [
'title' => '',
'names' => [],
'weight' => 20,
'class' => '\Drupal\config_translation\ConfigNamesMapper',
];
/**
* Constructs a ConfigMapperManager.
*
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* The cache backend.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config_manager
* The typed config manager.
* @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
* The theme handler.
*/
public function __construct(CacheBackendInterface $cache_backend, LanguageManagerInterface $language_manager, ModuleHandlerInterface $module_handler, TypedConfigManagerInterface $typed_config_manager, ThemeHandlerInterface $theme_handler) {
$this->typedConfigManager = $typed_config_manager;
$this->languageManager = $language_manager;
$this->factory = new ContainerFactory($this, '\Drupal\config_translation\ConfigMapperInterface');
// Let others alter definitions with hook_config_translation_info_alter().
$this->moduleHandler = $module_handler;
$this->themeHandler = $theme_handler;
$this->alterInfo('config_translation_info');
// Config translation only uses an info hook discovery, cache by language.
$cache_key = 'config_translation_info_plugins:' . $language_manager->getCurrentLanguage()->getId();
$this->setCacheBackend($cache_backend, $cache_key);
}
/**
* {@inheritdoc}
*/
protected function getDiscovery() {
if (!isset($this->discovery)) {
// Look at all themes and modules.
// @todo If the list of installed modules and themes is changed, new
// definitions are not picked up immediately and obsolete definitions
// are not removed, because the list of search directories is only
// compiled once in this constructor. The current code only works due to
// coincidence: The request that installs (for instance, a new theme)
// does not instantiate this plugin manager at the beginning of the
// request; when routes are being rebuilt at the end of the request,
// this service only happens to get instantiated with the updated list
// of installed themes.
$directories = [];
foreach ($this->moduleHandler->getModuleList() as $name => $module) {
$directories[$name] = $module->getPath();
}
foreach ($this->themeHandler->listInfo() as $theme) {
$directories[$theme->getName()] = $theme->getPath();
}
// Check for files named MODULE.config_translation.yml and
// THEME.config_translation.yml in module/theme roots.
$this->discovery = new YamlDiscovery('config_translation', $directories);
$this->discovery = new InfoHookDecorator($this->discovery, 'config_translation_info');
$this->discovery = new ContainerDerivativeDiscoveryDecorator($this->discovery);
}
return $this->discovery;
}
/**
* {@inheritdoc}
*/
public function getMappers(?RouteCollection $collection = NULL) {
$mappers = [];
foreach ($this->getDefinitions() as $id => $definition) {
$mappers[$id] = $this->createInstance($id);
if ($collection) {
$mappers[$id]->setRouteCollection($collection);
}
}
return $mappers;
}
/**
* {@inheritdoc}
*/
public function processDefinition(&$definition, $plugin_id) {
parent::processDefinition($definition, $plugin_id);
if (!isset($definition['base_route_name'])) {
throw new InvalidPluginDefinitionException($plugin_id, "The plugin definition of the mapper '$plugin_id' does not contain a base_route_name.");
}
}
/**
* {@inheritdoc}
*/
public function buildDataDefinition(array $definition, $value = NULL, $name = NULL, $parent = NULL) {
return $this->typedConfigManager->buildDataDefinition($definition, $value, $name, $parent);
}
/**
* {@inheritdoc}
*/
protected function findDefinitions() {
$definitions = $this->getDiscovery()->getDefinitions();
foreach ($definitions as $plugin_id => &$definition) {
$this->processDefinition($definition, $plugin_id);
}
if ($this->alterHook) {
$this->moduleHandler->alter($this->alterHook, $definitions);
}
// If this plugin was provided by a module that does not exist, remove the
// plugin definition.
foreach ($definitions as $plugin_id => $plugin_definition) {
if (isset($plugin_definition['provider']) && !in_array($plugin_definition['provider'], ['core', 'component']) && (!$this->moduleHandler->moduleExists($plugin_definition['provider']) && !in_array($plugin_definition['provider'], array_keys($this->themeHandler->listInfo())))) {
unset($definitions[$plugin_id]);
}
}
return $definitions;
}
/**
* {@inheritdoc}
*/
public function hasTranslatable($name) {
return $this->findTranslatable($this->typedConfigManager->get($name));
}
/**
* Returns TRUE if at least one translatable element is found.
*
* @param \Drupal\Core\TypedData\TypedDataInterface $element
* Configuration schema element.
*
* @return bool
* A boolean indicating if there is at least one translatable element.
*/
protected function findTranslatable(TypedDataInterface $element) {
// In case this is a sequence or a mapping check whether any child element
// is translatable.
if ($element instanceof TraversableTypedDataInterface) {
foreach ($element as $child_element) {
if ($this->findTranslatable($child_element)) {
return TRUE;
}
}
// If none of the child elements are translatable, return FALSE.
return FALSE;
}
else {
$definition = $element->getDataDefinition();
return isset($definition['translatable']) && $definition['translatable'];
}
}
/**
* {@inheritdoc}
*/
public function clearCachedDefinitions() {
$cids = [];
foreach ($this->languageManager->getLanguages() as $language) {
$cids[] = 'config_translation_info_plugins:' . $language->getId();
}
$this->cacheBackend->deleteMultiple($cids);
$this->definitions = NULL;
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace Drupal\config_translation;
use Drupal\Component\Plugin\PluginManagerInterface;
use Symfony\Component\Routing\RouteCollection;
/**
* Provides a common interface for config mapper managers.
*/
interface ConfigMapperManagerInterface extends PluginManagerInterface {
/**
* Returns an array of all mappers.
*
* @param \Symfony\Component\Routing\RouteCollection $collection
* The route collection used to initialize the mappers.
*
* @return \Drupal\config_translation\ConfigMapperInterface[]
* An array of all mappers.
*/
public function getMappers(?RouteCollection $collection = NULL);
/**
* Returns TRUE if the configuration data has translatable items.
*
* @param string $name
* Configuration key.
*
* @return bool
* A boolean indicating if the configuration data has translatable items.
*/
public function hasTranslatable($name);
}

View File

@ -0,0 +1,503 @@
<?php
namespace Drupal\config_translation;
use Drupal\config_translation\Event\ConfigMapperPopulateEvent;
use Drupal\config_translation\Event\ConfigTranslationEvents;
use Drupal\config_translation\Exception\ConfigMapperLanguageException;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Url;
use Drupal\locale\LocaleConfigManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Configuration mapper base implementation.
*/
class ConfigNamesMapper extends PluginBase implements ConfigMapperInterface, ContainerFactoryPluginInterface {
/**
* The configuration factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The typed config manager.
*
* @var \Drupal\Core\Config\TypedConfigManagerInterface
*/
protected $typedConfigManager;
/**
* The typed configuration manager.
*
* @var \Drupal\locale\LocaleConfigManager
*/
protected $localeConfigManager;
/**
* The mapper plugin discovery service.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface
*/
protected $configMapperManager;
/**
* The route provider.
*
* @var \Drupal\Core\Routing\RouteProviderInterface
*/
protected $routeProvider;
/**
* The base route object that the mapper is attached to.
*
* @var \Symfony\Component\Routing\Route
*/
protected $baseRoute;
/**
* The available routes.
*
* @var \Symfony\Component\Routing\RouteCollection
*/
protected $routeCollection;
/**
* The language code of the language this mapper, if any.
*
* @var string|null
*/
protected $langcode = NULL;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The event dispatcher.
*
* @var \Symfony\Contracts\EventDispatcher\EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* Constructs a ConfigNamesMapper.
*
* @param string $plugin_id
* The config mapper plugin ID.
* @param mixed $plugin_definition
* An array of plugin information with the following keys:
* - title: The title of the mapper, used for generating page titles.
* - base_route_name: The route name of the base route this mapper is
* attached to.
* - names: (optional) An array of configuration names.
* - weight: (optional) The weight of this mapper, used in mapper listings.
* Defaults to 20.
* - list_controller: (optional) Class name for list controller used to
* generate lists of this type of configuration.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
* @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
* The typed configuration manager.
* @param \Drupal\locale\LocaleConfigManager $locale_config_manager
* The locale configuration manager.
* @param \Drupal\config_translation\ConfigMapperManagerInterface $config_mapper_manager
* The mapper plugin discovery service.
* @param \Drupal\Core\Routing\RouteProviderInterface $route_provider
* The route provider.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation manager.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Symfony\Contracts\EventDispatcher\EventDispatcherInterface $event_dispatcher
* (optional) The event dispatcher.
*
* @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
* Throws an exception if the route specified by the 'base_route_name' in
* the plugin definition could not be found by the route provider.
*/
public function __construct($plugin_id, $plugin_definition, ConfigFactoryInterface $config_factory, TypedConfigManagerInterface $typed_config, LocaleConfigManager $locale_config_manager, ConfigMapperManagerInterface $config_mapper_manager, RouteProviderInterface $route_provider, TranslationInterface $string_translation, LanguageManagerInterface $language_manager, ?EventDispatcherInterface $event_dispatcher = NULL) {
$this->pluginId = $plugin_id;
$this->pluginDefinition = $plugin_definition;
$this->routeProvider = $route_provider;
$this->configFactory = $config_factory;
$this->typedConfigManager = $typed_config;
$this->localeConfigManager = $locale_config_manager;
$this->configMapperManager = $config_mapper_manager;
$this->stringTranslation = $string_translation;
$this->languageManager = $language_manager;
$this->eventDispatcher = $event_dispatcher ?: \Drupal::service('event_dispatcher');
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
// Note that we ignore the plugin $configuration because mappers have
// nothing to configure in themselves.
return new static(
$plugin_id,
$plugin_definition,
$container->get('config.factory'),
$container->get('config.typed'),
$container->get('locale.config_manager'),
$container->get('plugin.manager.config_translation.mapper'),
$container->get('router.route_provider'),
$container->get('string_translation'),
$container->get('language_manager'),
$container->get('event_dispatcher')
);
}
/**
* {@inheritdoc}
*/
public function setRouteCollection(RouteCollection $collection) {
$this->routeCollection = $collection;
}
/**
* {@inheritdoc}
*/
public function getTitle() {
// A title from a *.config_translation.yml. Should be translated for
// display in the current page language.
// phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
return $this->t($this->pluginDefinition['title']);
}
/**
* {@inheritdoc}
*/
public function getBaseRouteName() {
return $this->pluginDefinition['base_route_name'];
}
/**
* {@inheritdoc}
*/
public function getBaseRouteParameters() {
return [];
}
/**
* {@inheritdoc}
*/
public function getBaseRoute() {
if ($this->routeCollection) {
return $this->routeCollection->get($this->getBaseRouteName());
}
else {
return $this->routeProvider->getRouteByName($this->getBaseRouteName());
}
}
/**
* Allows to process all config translation routes.
*
* @param \Symfony\Component\Routing\Route $route
* The route object to process.
*/
protected function processRoute(Route $route) {
}
/**
* {@inheritdoc}
*/
public function getBasePath() {
return Url::fromRoute($this->getBaseRouteName(), $this->getBaseRouteParameters())->getInternalPath();
}
/**
* {@inheritdoc}
*/
public function getOverviewRouteName() {
return 'config_translation.item.overview.' . $this->getBaseRouteName();
}
/**
* {@inheritdoc}
*/
public function getOverviewRouteParameters() {
return $this->getBaseRouteParameters();
}
/**
* {@inheritdoc}
*/
public function getOverviewRoute() {
$route = new Route(
$this->getBaseRoute()->getPath() . '/translate',
[
'_controller' => '\Drupal\config_translation\Controller\ConfigTranslationController::itemPage',
'plugin_id' => $this->getPluginId(),
],
['_config_translation_overview_access' => 'TRUE']
);
$this->processRoute($route);
return $route;
}
/**
* {@inheritdoc}
*/
public function getOverviewPath() {
return Url::fromRoute($this->getOverviewRouteName(), $this->getOverviewRouteParameters())->getInternalPath();
}
/**
* {@inheritdoc}
*/
public function getAddRouteName() {
return 'config_translation.item.add.' . $this->getBaseRouteName();
}
/**
* {@inheritdoc}
*/
public function getAddRouteParameters() {
// If sub-classes provide route parameters in getBaseRouteParameters(), they
// probably also want to provide those for the add, edit, and delete forms.
$parameters = $this->getBaseRouteParameters();
$parameters['langcode'] = $this->langcode;
return $parameters;
}
/**
* {@inheritdoc}
*/
public function getAddRoute() {
$route = new Route(
$this->getBaseRoute()->getPath() . '/translate/{langcode}/add',
[
'_form' => '\Drupal\config_translation\Form\ConfigTranslationAddForm',
'plugin_id' => $this->getPluginId(),
],
['_config_translation_form_access' => 'TRUE']
);
$this->processRoute($route);
return $route;
}
/**
* {@inheritdoc}
*/
public function getEditRouteName() {
return 'config_translation.item.edit.' . $this->getBaseRouteName();
}
/**
* {@inheritdoc}
*/
public function getEditRouteParameters() {
return $this->getAddRouteParameters();
}
/**
* {@inheritdoc}
*/
public function getEditRoute() {
$route = new Route(
$this->getBaseRoute()->getPath() . '/translate/{langcode}/edit',
[
'_form' => '\Drupal\config_translation\Form\ConfigTranslationEditForm',
'plugin_id' => $this->getPluginId(),
],
['_config_translation_form_access' => 'TRUE']
);
$this->processRoute($route);
return $route;
}
/**
* {@inheritdoc}
*/
public function getDeleteRouteName() {
return 'config_translation.item.delete.' . $this->getBaseRouteName();
}
/**
* {@inheritdoc}
*/
public function getDeleteRouteParameters() {
return $this->getAddRouteParameters();
}
/**
* {@inheritdoc}
*/
public function getDeleteRoute() {
$route = new Route(
$this->getBaseRoute()->getPath() . '/translate/{langcode}/delete',
[
'_form' => '\Drupal\config_translation\Form\ConfigTranslationDeleteForm',
'plugin_id' => $this->getPluginId(),
],
['_config_translation_form_access' => 'TRUE']
);
$this->processRoute($route);
return $route;
}
/**
* {@inheritdoc}
*/
public function getConfigNames() {
return $this->pluginDefinition['names'];
}
/**
* {@inheritdoc}
*/
public function addConfigName($name) {
$this->pluginDefinition['names'][] = $name;
}
/**
* {@inheritdoc}
*/
public function getWeight() {
return $this->pluginDefinition['weight'];
}
/**
* {@inheritdoc}
*/
public function populateFromRouteMatch(RouteMatchInterface $route_match) {
$this->langcode = $route_match->getParameter('langcode');
$event = new ConfigMapperPopulateEvent($this, $route_match);
$this->eventDispatcher->dispatch($event, ConfigTranslationEvents::POPULATE_MAPPER);
}
/**
* {@inheritdoc}
*/
public function getTypeLabel() {
return $this->getTitle();
}
/**
* {@inheritdoc}
*/
public function getLangcode() {
$langcodes = array_map([$this, 'getLangcodeFromConfig'], $this->getConfigNames());
if (count(array_unique($langcodes)) > 1) {
throw new ConfigMapperLanguageException('A config mapper can only contain configuration for a single language.');
}
return reset($langcodes);
}
/**
* {@inheritdoc}
*/
public function getLangcodeFromConfig($config_name) {
// Default to English if no language code was provided in the file.
// Although it is a best practice to include a language code, if the
// developer did not think about a multilingual use case, we fall back
// on assuming the file is English.
return $this->configFactory->get($config_name)->get('langcode') ?: 'en';
}
/**
* {@inheritdoc}
*/
public function setLangcode($langcode) {
$this->langcode = $langcode;
return $this;
}
/**
* {@inheritdoc}
*/
public function getConfigData() {
$config_data = [];
foreach ($this->getConfigNames() as $name) {
$config_data[$name] = $this->configFactory->getEditable($name)->get();
}
return $config_data;
}
/**
* {@inheritdoc}
*/
public function hasSchema() {
foreach ($this->getConfigNames() as $name) {
if (!$this->typedConfigManager->hasConfigSchema($name)) {
return FALSE;
}
}
return TRUE;
}
/**
* {@inheritdoc}
*/
public function hasTranslatable() {
foreach ($this->getConfigNames() as $name) {
if ($this->configMapperManager->hasTranslatable($name)) {
return TRUE;
}
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function hasTranslation(LanguageInterface $language) {
foreach ($this->getConfigNames() as $name) {
if ($this->localeConfigManager->hasTranslation($name, $language->getId())) {
return TRUE;
}
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function getTypeName() {
return $this->t('Settings');
}
/**
* {@inheritdoc}
*/
public function getOperations() {
return [
'translate' => [
'title' => $this->t('Translate'),
'url' => Url::fromRoute($this->getOverviewRouteName(), $this->getOverviewRouteParameters()),
],
];
}
/**
* {@inheritdoc}
*/
public function getContextualLinkGroup() {
return NULL;
}
}

View File

@ -0,0 +1,99 @@
<?php
namespace Drupal\config_translation\Controller;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines the config translation list builder for blocks.
*/
class ConfigTranslationBlockListBuilder extends ConfigTranslationEntityListBuilder {
/**
* An array of theme info keyed by theme name.
*
* @var array
*/
protected $themes = [];
/**
* {@inheritdoc}
*/
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, ThemeHandlerInterface $theme_handler) {
parent::__construct($entity_type, $storage);
$this->themes = $theme_handler->listInfo();
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('entity_type.manager')->getStorage($entity_type->id()),
$container->get('theme_handler')
);
}
/**
* {@inheritdoc}
*/
public function getFilterLabels() {
$info = parent::getFilterLabels();
$info['placeholder'] = $this->t('Enter block, theme or category');
$info['description'] = $this->t('Enter a part of the block, theme or category to filter by.');
return $info;
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
$theme = $entity->getTheme();
$plugin_definition = $entity->getPlugin()->getPluginDefinition();
$row['label'] = [
'data' => $entity->label(),
'class' => 'table-filter-text-source',
];
$row['theme'] = [
'data' => $this->themes[$theme]->info['name'],
'class' => 'table-filter-text-source',
];
$row['category'] = [
'data' => $plugin_definition['category'],
'class' => 'table-filter-text-source',
];
$row['operations']['data'] = $this->buildOperations($entity);
return $row;
}
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['label'] = $this->t('Block');
$header['theme'] = $this->t('Theme');
$header['category'] = $this->t('Category');
$header['operations'] = $this->t('Operations');
return $header;
}
/**
* {@inheritdoc}
*/
public function sortRows($a, $b) {
return $this->sortRowsMultiple($a, $b, ['theme', 'category', 'label']);
}
}

View File

@ -0,0 +1,293 @@
<?php
namespace Drupal\config_translation\Controller;
use Drupal\Component\Serialization\Json;
use Drupal\config_translation\ConfigMapperManagerInterface;
use Drupal\config_translation\Exception\ConfigMapperLanguageException;
use Drupal\Core\Access\AccessManagerInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Language\Language;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Routing\RouteMatch;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
/**
* Provides page callbacks for the configuration translation interface.
*/
class ConfigTranslationController extends ControllerBase {
/**
* The configuration mapper manager.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface
*/
protected $configMapperManager;
/**
* The menu link access service.
*
* @var \Drupal\Core\Access\AccessManagerInterface
*/
protected $accessManager;
/**
* The dynamic router service.
*
* @var \Symfony\Component\Routing\Matcher\RequestMatcherInterface
*/
protected $router;
/**
* The path processor service.
*
* @var \Drupal\Core\PathProcessor\InboundPathProcessorInterface
*/
protected $pathProcessor;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $account;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* Constructs a ConfigTranslationController.
*
* @param \Drupal\config_translation\ConfigMapperManagerInterface $config_mapper_manager
* The configuration mapper manager.
* @param \Drupal\Core\Access\AccessManagerInterface $access_manager
* The menu link access service.
* @param \Symfony\Component\Routing\Matcher\RequestMatcherInterface $router
* The dynamic router service.
* @param \Drupal\Core\PathProcessor\InboundPathProcessorInterface $path_processor
* The inbound path processor.
* @param \Drupal\Core\Session\AccountInterface $account
* The current user.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
*/
public function __construct(ConfigMapperManagerInterface $config_mapper_manager, AccessManagerInterface $access_manager, RequestMatcherInterface $router, InboundPathProcessorInterface $path_processor, AccountInterface $account, LanguageManagerInterface $language_manager, RendererInterface $renderer) {
$this->configMapperManager = $config_mapper_manager;
$this->accessManager = $access_manager;
$this->router = $router;
$this->pathProcessor = $path_processor;
$this->account = $account;
$this->languageManager = $language_manager;
$this->renderer = $renderer;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('plugin.manager.config_translation.mapper'),
$container->get('access_manager'),
$container->get('router'),
$container->get('path_processor_manager'),
$container->get('current_user'),
$container->get('language_manager'),
$container->get('renderer')
);
}
/**
* Language translations overview page for a configuration name.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* Page request object.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
* @param string $plugin_id
* The plugin ID of the mapper.
*
* @return array
* Page render array.
*/
public function itemPage(Request $request, RouteMatchInterface $route_match, $plugin_id) {
$cacheable_metadata = new CacheableMetadata();
/** @var \Drupal\config_translation\ConfigMapperInterface $mapper */
$mapper = $this->configMapperManager->createInstance($plugin_id);
$mapper->populateFromRouteMatch($route_match);
$page = [];
$page['#title'] = $this->t('Translations for %label', ['%label' => $mapper->getTitle()]);
$languages = $this->languageManager->getLanguages();
if (count($languages) == 1) {
$this->messenger()->addWarning($this->t('In order to translate configuration, the website must have at least two <a href=":url">languages</a>.', [':url' => Url::fromRoute('entity.configurable_language.collection')->toString()]));
}
try {
$original_langcode = $mapper->getLangcode();
$operations_access = TRUE;
}
catch (ConfigMapperLanguageException) {
$items = [];
foreach ($mapper->getConfigNames() as $config_name) {
$langcode = $mapper->getLangcodeFromConfig($config_name);
$items[] = $this->t('@name: @langcode', [
'@name' => $config_name,
'@langcode' => $langcode,
]);
}
$message = [
'message' => ['#markup' => $this->t('The configuration objects have different language codes so they cannot be translated:')],
'items' => [
'#theme' => 'item_list',
'#items' => $items,
],
];
$this->messenger()->addWarning($this->renderer->renderInIsolation($message));
$original_langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
$operations_access = FALSE;
}
if (!isset($languages[$original_langcode])) {
// If the language is not configured on the site, create a dummy language
// object for this listing only to ensure the user gets useful info.
$language_name = $this->languageManager->getLanguageName($original_langcode);
$languages[$original_langcode] = new Language(['id' => $original_langcode, 'name' => $language_name]);
}
// We create a fake request object to pass into
// ConfigMapperInterface::populateFromRouteMatch() for the different
// languages.
// Creating a separate request for each language and route is neither easily
// possible nor performant.
$fake_request = $request->duplicate();
$page['languages'] = [
'#type' => 'table',
'#header' => [$this->t('Language'), $this->t('Operations')],
];
foreach ($languages as $language) {
$langcode = $language->getId();
// This is needed because
// ConfigMapperInterface::getAddRouteParameters(), for example,
// needs to return the correct language code for each table row.
$fake_route_match = RouteMatch::createFromRequest($fake_request);
$mapper->populateFromRouteMatch($fake_route_match);
$mapper->setLangcode($langcode);
// Prepare the language name and the operations depending on whether this
// is the original language or not.
if ($langcode == $original_langcode) {
$language_name = '<strong>' . $this->t('@language (original)', ['@language' => $language->getName()]) . '</strong>';
// Check access for the path/route for editing, so we can decide to
// include a link to edit or not.
$edit_access = $this->accessManager->checkNamedRoute($mapper->getBaseRouteName(), $route_match->getRawParameters()->all(), $this->account, TRUE);
$cacheable_metadata->addCacheableDependency($edit_access);
// Build list of operations.
$operations = [];
if ($edit_access->isAllowed()) {
$operations['edit'] = [
'title' => $this->t('Edit'),
'url' => Url::fromRoute($mapper->getBaseRouteName(), $mapper->getBaseRouteParameters(), ['query' => ['destination' => $mapper->getOverviewPath()]]),
];
}
}
else {
$language_name = $language->getName();
// The translation check below might change if the configs change, so we
// need to add their cache tags.
$cache_tags = [];
foreach ($mapper->getConfigNames() as $configName) {
$cache_tags[] = "config:$configName";
}
$cacheable_metadata->addCacheTags($cache_tags);
$operations = [];
// If no translation exists for this language, link to add one.
if (!$mapper->hasTranslation($language)) {
$operations['add'] = [
'title' => $this->t('Add'),
'url' => Url::fromRoute($mapper->getAddRouteName(), $mapper->getAddRouteParameters()),
'attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 880,
]),
],
];
}
else {
// Otherwise, link to edit the existing translation.
$operations['edit'] = [
'title' => $this->t('Edit'),
'url' => Url::fromRoute($mapper->getEditRouteName(), $mapper->getEditRouteParameters()),
'attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 880,
]),
],
];
$operations['delete'] = [
'title' => $this->t('Delete'),
'url' => Url::fromRoute($mapper->getDeleteRouteName(), $mapper->getDeleteRouteParameters()),
'attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 880,
]),
],
];
}
}
$page['languages'][$langcode]['language'] = [
'#markup' => $language_name,
];
$page['languages'][$langcode]['operations'] = [
'#type' => 'operations',
'#links' => $operations,
// Even if the mapper contains multiple language codes, the source
// configuration can still be edited.
'#access' => ($langcode == $original_langcode) || $operations_access,
'#attached' => ['library' => ['core/drupal.dialog.ajax']],
];
}
$cacheable_metadata->applyTo($page);
return $page;
}
}

View File

@ -0,0 +1,135 @@
<?php
namespace Drupal\config_translation\Controller;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
/**
* Defines the configuration translation list builder for entities.
*/
class ConfigTranslationEntityListBuilder extends ConfigEntityListBuilder implements ConfigTranslationEntityListBuilderInterface {
/**
* Provides user facing strings for the filter element.
*
* @return array
* An associative array of facing strings.
*/
protected function getFilterLabels() {
return [
'placeholder' => $this->t('Enter label'),
'description' => $this->t('Enter a part of the label or description to filter by.'),
];
}
/**
* {@inheritdoc}
*/
public function render() {
$build = parent::render();
$filter = $this->getFilterLabels();
usort($build['table']['#rows'], [$this, 'sortRows']);
$build['filters'] = [
'#type' => 'container',
'#attributes' => [
'class' => ['table-filter', 'js-show'],
],
'#weight' => -10,
];
$build['filters']['text'] = [
'#type' => 'search',
'#title' => $this->t('Search'),
'#size' => 30,
'#placeholder' => $filter['placeholder'],
'#attributes' => [
'class' => ['table-filter-text'],
'data-table' => '.config-translation-entity-list',
'autocomplete' => 'off',
'title' => $filter['description'],
],
];
$build['table']['#attributes']['class'][] = 'config-translation-entity-list';
$build['table']['#weight'] = 0;
$build['#attached']['library'][] = 'system/drupal.system.modules';
return $build;
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
$row['label']['data'] = $entity->label();
$row['label']['class'][] = 'table-filter-text-source';
return $row + parent::buildRow($entity);
}
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['label'] = $this->t('Label');
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function getOperations(EntityInterface $entity) {
$operations = parent::getOperations($entity);
foreach (array_keys($operations) as $operation) {
// This is a translation UI for translators. Show the translation
// operation only.
if (!($operation == 'translate')) {
unset($operations[$operation]);
}
}
return $operations;
}
/**
* {@inheritdoc}
*/
public function sortRows($a, $b) {
return $this->sortRowsMultiple($a, $b, ['label']);
}
/**
* Sorts an array by multiple criteria.
*
* @param array $a
* First item for comparison.
* @param array $b
* Second item for comparison.
* @param array $keys
* The array keys to sort on.
*
* @return int
* The comparison result for uasort().
*/
protected function sortRowsMultiple($a, $b, $keys) {
$key = array_shift($keys);
$a_value = (is_array($a) && isset($a[$key]['data'])) ? $a[$key]['data'] : '';
$b_value = (is_array($b) && isset($b[$key]['data'])) ? $b[$key]['data'] : '';
if ($a_value == $b_value && !empty($keys)) {
return $this->sortRowsMultiple($a, $b, $keys);
}
return strnatcasecmp($a_value, $b_value);
}
/**
* {@inheritdoc}
*/
public function setMapperDefinition($mapper_definition) {
// @todo Why is this method called on all config list controllers?
return $this;
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace Drupal\config_translation\Controller;
use Drupal\Core\Entity\EntityListBuilderInterface;
/**
* Defines an interface for configuration translation entity list builders.
*/
interface ConfigTranslationEntityListBuilderInterface extends EntityListBuilderInterface {
/**
* Sorts an array by value.
*
* @param array $a
* First item for comparison.
* @param array $b
* Second item for comparison.
*
* @return int
* The comparison result for uasort().
*/
public function sortRows($a, $b);
/**
* Sets the config translation mapper definition.
*
* @param mixed $mapper_definition
* The plugin definition of the config translation mapper.
*
* @return $this
*/
public function setMapperDefinition($mapper_definition);
}

View File

@ -0,0 +1,183 @@
<?php
namespace Drupal\config_translation\Controller;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines the config translation list builder for field entities.
*/
class ConfigTranslationFieldListBuilder extends ConfigTranslationEntityListBuilder {
/**
* The name of the entity type the fields are attached to.
*
* @var string
*/
protected $baseEntityType = '';
/**
* An array containing the base entity type's definition.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $baseEntityInfo;
/**
* The bundle info for the base entity type.
*
* @var array
*/
protected $baseEntityBundles = [];
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity bundle info.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
$entity_type_manager = $container->get('entity_type.manager');
$entity_type_bundle_info = $container->get('entity_type.bundle.info');
return new static(
$entity_type,
$entity_type_manager->getStorage($entity_type->id()),
$entity_type_manager,
$entity_type_bundle_info
);
}
/**
* Constructs a new ConfigTranslationFieldListBuilder object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
* @param \Drupal\Core\Entity\EntityStorageInterface $storage
* The entity storage class.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info.
*/
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info) {
parent::__construct($entity_type, $storage);
$this->entityTypeManager = $entity_type_manager;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
}
/**
* {@inheritdoc}
*/
public function setMapperDefinition($mapper_definition) {
$this->baseEntityType = $mapper_definition['base_entity_type'];
$this->baseEntityInfo = $this->entityTypeManager->getDefinition($this->baseEntityType);
$this->baseEntityBundles = $this->entityTypeBundleInfo->getBundleInfo($this->baseEntityType);
return $this;
}
/**
* {@inheritdoc}
*/
public function load() {
// It is not possible to use the standard load method, because this needs
// all field entities only for the given baseEntityType.
$ids = \Drupal::entityQuery('field_config')
->condition('id', $this->baseEntityType . '.', 'STARTS_WITH')
->execute();
return $this->storage->loadMultiple($ids);
}
/**
* {@inheritdoc}
*/
public function getFilterLabels() {
$info = parent::getFilterLabels();
$bundle = $this->baseEntityInfo->getBundleLabel() ?: $this->t('Bundle');
$bundle = mb_strtolower($bundle);
$info['placeholder'] = $this->t('Enter field or @bundle', ['@bundle' => $bundle]);
$info['description'] = $this->t('Enter a part of the field or @bundle to filter by.', ['@bundle' => $bundle]);
return $info;
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
$row['label'] = [
'data' => $entity->label(),
'class' => 'table-filter-text-source',
];
if ($this->displayBundle()) {
$bundle = $entity->get('bundle');
$row['bundle'] = [
'data' => $this->baseEntityBundles[$bundle]['label'],
'class' => 'table-filter-text-source',
];
}
return $row + parent::buildRow($entity);
}
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['label'] = $this->t('Field');
if ($this->displayBundle()) {
$header['bundle'] = $this->baseEntityInfo->getBundleLabel() ?: $this->t('Bundle');
}
return $header + parent::buildHeader();
}
/**
* Controls the visibility of the bundle column on field list pages.
*
* @return bool
* Whenever the bundle is displayed or not.
*/
public function displayBundle() {
// The bundle key is explicitly defined in the entity definition.
if ($this->baseEntityInfo->getKey('bundle')) {
return TRUE;
}
// There is more than one bundle defined.
if (count($this->baseEntityBundles) > 1) {
return TRUE;
}
// The defined bundle ones not match the entity type name.
if (!empty($this->baseEntityBundles) && !isset($this->baseEntityBundles[$this->baseEntityType])) {
return TRUE;
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function sortRows($a, $b) {
return $this->sortRowsMultiple($a, $b, ['bundle', 'label']);
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace Drupal\config_translation\Controller;
use Drupal\config_translation\ConfigMapperManagerInterface;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Defines the configuration translation list controller.
*/
class ConfigTranslationListController extends ControllerBase {
/**
* The mapper manager.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface
*/
protected $mapperManager;
/**
* Constructs a new ConfigTranslationListController object.
*
* @param \Drupal\config_translation\ConfigMapperManagerInterface $mapper_manager
* The config mapper manager.
*/
public function __construct(ConfigMapperManagerInterface $mapper_manager) {
$this->mapperManager = $mapper_manager;
}
/**
* Provides the listing page for any entity type.
*
* @param string $mapper_id
* The name of the mapper.
*
* @return array
* A render array as expected by
* \Drupal\Core\Render\RendererInterface::render().
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
* Throws an exception if a mapper plugin could not be instantiated from the
* mapper definition in the constructor.
*/
public function listing($mapper_id) {
$mapper_definition = $this->mapperManager->getDefinition($mapper_id);
$mapper = $this->mapperManager->createInstance($mapper_id, $mapper_definition);
if (!$mapper) {
throw new NotFoundHttpException();
}
$entity_type = $mapper->getType();
// If the mapper, for example the mapper for fields, has a custom list
// controller defined, use it. Other mappers, for examples the ones for
// node_type and block, fallback to the generic configuration translation
// list controller.
$build = $this->entityTypeManager()
->getHandler($entity_type, 'config_translation_list')
->setMapperDefinition($mapper_definition)
->render();
$build['#title'] = $mapper->getTypeLabel();
return $build;
}
}

View File

@ -0,0 +1,128 @@
<?php
namespace Drupal\config_translation\Controller;
use Drupal\config_translation\ConfigMapperInterface;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines the configuration translation mapper list.
*
* Groups all defined configuration mapper instances by weight.
*/
class ConfigTranslationMapperList extends ControllerBase {
/**
* An array of configuration mapper instances.
*
* @var \Drupal\config_translation\ConfigMapperInterface[]
*/
protected $mappers;
/**
* Constructs a new ConfigTranslationMapperList object.
*
* @param \Drupal\config_translation\ConfigMapperInterface[] $mappers
* The configuration mapper manager.
*/
public function __construct(array $mappers) {
$this->mappers = $mappers;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('plugin.manager.config_translation.mapper')->getMappers()
);
}
/**
* Builds the mappers as a renderable array for table.html.twig.
*
* @return array
* Renderable array with config translation mappers.
*/
public function render() {
$build = [
'#type' => 'table',
'#header' => $this->buildHeader(),
'#rows' => [],
];
$mappers = [];
foreach ($this->mappers as $mapper) {
if ($row = $this->buildRow($mapper)) {
$mappers[$mapper->getWeight()][] = $row;
}
}
// Group by mapper weight and sort by label.
ksort($mappers);
foreach ($mappers as $weight => $mapper) {
usort($mapper, function ($a, $b) {
$a_title = (isset($a['label'])) ? $a['label'] : '';
$b_title = (isset($b['label'])) ? $b['label'] : '';
return strnatcasecmp($a_title, $b_title);
});
$mappers[$weight] = $mapper;
}
$build['#rows'] = array_merge(...$mappers);
return $build;
}
/**
* Builds a row for a mapper in the mapper listing.
*
* @param \Drupal\config_translation\ConfigMapperInterface $mapper
* The mapper.
*
* @return array
* A render array structure of fields for this mapper.
*/
public function buildRow(ConfigMapperInterface $mapper) {
$row['label'] = $mapper->getTypeLabel();
$row['operations']['data'] = $this->buildOperations($mapper);
return $row;
}
/**
* Builds the header row for the mapper listing.
*
* @return array
* A render array structure of header strings.
*/
public function buildHeader() {
$row['Label'] = $this->t('Label');
$row['operations'] = $this->t('Operations');
return $row;
}
/**
* Builds a renderable list of operation links for the entity.
*
* @param \Drupal\config_translation\ConfigMapperInterface $mapper
* The mapper.
*
* @return array
* A renderable array of operation links.
*
* @see \Drupal\Core\Entity\EntityList::buildOperations()
*/
protected function buildOperations(ConfigMapperInterface $mapper) {
// Retrieve and sort operations.
$operations = $mapper->getOperations();
uasort($operations, 'Drupal\Component\Utility\SortArray::sortByWeightElement');
$build = [
'#type' => 'operations',
'#links' => $operations,
];
return $build;
}
}

View File

@ -0,0 +1,61 @@
<?php
namespace Drupal\config_translation\Event;
use Drupal\config_translation\ConfigMapperInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Component\EventDispatcher\Event;
/**
* Provides a class for events related to configuration translation mappers.
*/
class ConfigMapperPopulateEvent extends Event {
/**
* The configuration mapper this event is related to.
*
* @var \Drupal\config_translation\ConfigMapperInterface
*/
protected $mapper;
/**
* The route match this event is related to.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;
/**
* Constructs a ConfigMapperPopulateEvent object.
*
* @param \Drupal\config_translation\ConfigMapperInterface $mapper
* The configuration mapper this event is related to.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match this event is related to.
*/
public function __construct(ConfigMapperInterface $mapper, RouteMatchInterface $route_match) {
$this->mapper = $mapper;
$this->routeMatch = $route_match;
}
/**
* Gets the configuration mapper this event is related to.
*
* @return \Drupal\config_translation\ConfigMapperInterface
* The configuration mapper this event is related to.
*/
public function getMapper() {
return $this->mapper;
}
/**
* Gets the route match this event is related to.
*
* @return \Drupal\Core\Routing\RouteMatchInterface
* The route match this event is related to.
*/
public function getRouteMatch() {
return $this->routeMatch;
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace Drupal\config_translation\Event;
/**
* Provides a list of events dispatched by the Configuration Translation module.
*/
final class ConfigTranslationEvents {
/**
* The name of the event dispatched when a configuration mapper is populated.
*
* Allows modules to add related config for translation on a specific
* translation form.
*
* @see \Drupal\config_translation\ConfigMapperInterface::populateFromRouteMatch()
*/
const POPULATE_MAPPER = 'config_translation.populate_mapper';
}

View File

@ -0,0 +1,9 @@
<?php
namespace Drupal\config_translation\Exception;
/**
* Provides an exception for configuration mappers with multiple languages.
*/
class ConfigMapperLanguageException extends \RuntimeException {
}

View File

@ -0,0 +1,34 @@
<?php
namespace Drupal\config_translation\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Defines a form for adding configuration translations.
*
* @internal
*/
class ConfigTranslationAddForm extends ConfigTranslationFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'config_translation_add_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ?RouteMatchInterface $route_match = NULL, $plugin_id = NULL, $langcode = NULL) {
$form = parent::buildForm($form, $form_state, $route_match, $plugin_id, $langcode);
$form['#title'] = $this->t('Add @language translation for %label', [
'%label' => $this->mapper->getTitle(),
'@language' => $this->language->getName(),
]);
return $form;
}
}

View File

@ -0,0 +1,150 @@
<?php
namespace Drupal\config_translation\Form;
use Drupal\config_translation\ConfigMapperManagerInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\language\ConfigurableLanguageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Builds a form to delete configuration translation.
*
* @internal
*/
class ConfigTranslationDeleteForm extends ConfirmFormBase {
/**
* The language manager.
*
* @var \Drupal\language\ConfigurableLanguageManagerInterface
*/
protected $languageManager;
/**
* The configuration mapper manager.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface
*/
protected $configMapperManager;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The configuration translation to be deleted.
*
* @var \Drupal\config_translation\ConfigMapperInterface
*/
protected $mapper;
/**
* The language of configuration translation.
*
* @var \Drupal\Core\Language\LanguageInterface
*/
protected $language;
/**
* Constructs a ConfigTranslationDeleteForm.
*
* @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager
* The language override configuration storage.
* @param \Drupal\config_translation\ConfigMapperManagerInterface $config_mapper_manager
* The configuration mapper manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
*/
public function __construct(ConfigurableLanguageManagerInterface $language_manager, ConfigMapperManagerInterface $config_mapper_manager, ModuleHandlerInterface $module_handler) {
$this->languageManager = $language_manager;
$this->configMapperManager = $config_mapper_manager;
$this->moduleHandler = $module_handler;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('language_manager'),
$container->get('plugin.manager.config_translation.mapper'),
$container->get('module_handler')
);
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete the @language translation of %label?', ['%label' => $this->mapper->getTitle(), '@language' => $this->language->getName()]);
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Delete');
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url($this->mapper->getOverviewRouteName(), $this->mapper->getOverviewRouteParameters());
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'config_translation_delete_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ?RouteMatchInterface $route_match = NULL, $plugin_id = NULL, $langcode = NULL) {
/** @var \Drupal\config_translation\ConfigMapperInterface $mapper */
$mapper = $this->configMapperManager->createInstance($plugin_id);
$mapper->populateFromRouteMatch($route_match);
$language = $this->languageManager->getLanguage($langcode);
if (!$language) {
throw new NotFoundHttpException();
}
$this->mapper = $mapper;
$this->language = $language;
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
foreach ($this->mapper->getConfigNames() as $name) {
$this->languageManager->getLanguageConfigOverride($this->language->getId(), $name)->delete();
}
// Flush all persistent caches.
$this->moduleHandler->invokeAll('cache_flush');
foreach (Cache::getBins() as $cache_backend) {
$cache_backend->deleteAll();
}
$this->messenger()->addStatus($this->t('@language translation of %label was deleted', ['%label' => $this->mapper->getTitle(), '@language' => $this->language->getName()]));
$form_state->setRedirectUrl($this->getCancelUrl());
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace Drupal\config_translation\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Defines a form for editing configuration translations.
*
* @internal
*/
class ConfigTranslationEditForm extends ConfigTranslationFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'config_translation_edit_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ?RouteMatchInterface $route_match = NULL, $plugin_id = NULL, $langcode = NULL) {
$form = parent::buildForm($form, $form_state, $route_match, $plugin_id, $langcode);
$form['#title'] = $this->t('Edit @language translation for %label', [
'%label' => $this->mapper->getTitle(),
'@language' => $this->language->getName(),
]);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
$this->messenger()->addStatus($this->t('Successfully updated @language translation.', ['@language' => $this->language->getName()]));
}
}

View File

@ -0,0 +1,252 @@
<?php
namespace Drupal\config_translation\Form;
use Drupal\config_translation\ConfigMapperManagerInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\TypedDataInterface;
use Drupal\Core\Form\BaseFormIdInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\language\ConfigurableLanguageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Provides a base form for configuration translations.
*/
abstract class ConfigTranslationFormBase extends FormBase implements BaseFormIdInterface {
/**
* The typed configuration manager.
*
* @var \Drupal\Core\Config\TypedConfigManagerInterface
*/
protected $typedConfigManager;
/**
* The configuration mapper manager.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface
*/
protected $configMapperManager;
/**
* The mapper for configuration translation.
*
* @var \Drupal\config_translation\ConfigMapperInterface
*/
protected $mapper;
/**
* The language manager.
*
* @var \Drupal\language\ConfigurableLanguageManagerInterface
*/
protected $languageManager;
/**
* The language of the configuration translation.
*
* @var \Drupal\Core\Language\LanguageInterface
*/
protected $language;
/**
* The language of the configuration translation source.
*
* @var \Drupal\Core\Language\LanguageInterface
*/
protected $sourceLanguage;
/**
* An array of base language configuration data keyed by configuration names.
*
* @var array
*/
protected $baseConfigData = [];
/**
* Constructs a ConfigTranslationFormBase.
*
* @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config_manager
* The typed configuration manager.
* @param \Drupal\config_translation\ConfigMapperManagerInterface $config_mapper_manager
* The configuration mapper manager.
* @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager
* The configurable language manager.
*/
public function __construct(TypedConfigManagerInterface $typed_config_manager, ConfigMapperManagerInterface $config_mapper_manager, ConfigurableLanguageManagerInterface $language_manager) {
$this->typedConfigManager = $typed_config_manager;
$this->configMapperManager = $config_mapper_manager;
$this->languageManager = $language_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.typed'),
$container->get('plugin.manager.config_translation.mapper'),
$container->get('language_manager')
);
}
/**
* {@inheritdoc}
*/
public function getBaseFormId() {
return 'config_translation_form';
}
/**
* Implements \Drupal\Core\Form\FormInterface::buildForm().
*
* Builds configuration form with metadata and values from the source
* language.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* (optional) The route match.
* @param string $plugin_id
* (optional) The plugin ID of the mapper.
* @param string $langcode
* (optional) The language code of the language the form is adding or
* editing.
*
* @return array
* The form structure.
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
* Throws an exception if the language code provided as a query parameter in
* the request does not match an active language.
*/
public function buildForm(array $form, FormStateInterface $form_state, ?RouteMatchInterface $route_match = NULL, $plugin_id = NULL, $langcode = NULL) {
/** @var \Drupal\config_translation\ConfigMapperInterface $mapper */
$mapper = $this->configMapperManager->createInstance($plugin_id);
$mapper->populateFromRouteMatch($route_match);
$language = $this->languageManager->getLanguage($langcode);
if (!$language) {
throw new NotFoundHttpException();
}
$this->mapper = $mapper;
$this->language = $language;
// ConfigTranslationFormAccess will not grant access if this raises an
// exception, so we can call this without a try-catch block here.
$langcode = $this->mapper->getLangcode();
$this->sourceLanguage = $this->languageManager->getLanguage($langcode);
// Get base language configuration to display in the form before setting the
// language to use for the form. This avoids repetitively settings and
// resetting the language to get original values later.
$this->baseConfigData = $this->mapper->getConfigData();
// Set the translation target language on the configuration factory.
$original_language = $this->languageManager->getConfigOverrideLanguage();
$this->languageManager->setConfigOverrideLanguage($this->language);
// Add some information to the form state for easier form altering.
$form_state->set('config_translation_mapper', $this->mapper);
$form_state->set('config_translation_language', $this->language);
$form_state->set('config_translation_source_language', $this->sourceLanguage);
$form['#attached']['library'][] = 'config_translation/drupal.config_translation.admin';
// Even though this is a nested form, we do not set #tree to TRUE because
// the form value structure is generated by using #parents for each element.
// @see \Drupal\config_translation\FormElement\FormElementBase::getElements()
$form['config_names'] = ['#type' => 'container'];
foreach ($this->mapper->getConfigNames() as $name) {
$form['config_names'][$name] = ['#type' => 'container'];
$schema = $this->typedConfigManager->get($name);
$source_config = $this->baseConfigData[$name];
$translation_config = $this->configFactory()->get($name)->get();
if ($form_element = $this->createFormElement($schema)) {
$parents = ['config_names', $name];
$form['config_names'][$name] += $form_element->getTranslationBuild($this->sourceLanguage, $this->language, $source_config, $translation_config, $parents);
}
}
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save translation'),
'#button_type' => 'primary',
];
// Set the configuration language back.
$this->languageManager->setConfigOverrideLanguage($original_language);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_values = $form_state->getValue(['translation', 'config_names']);
foreach ($form_values as $name => $value) {
$schema = $this->typedConfigManager->get($name);
// Set configuration values based on form submission and source values.
$base_config = $this->configFactory()->getEditable($name);
$config_translation = $this->languageManager->getLanguageConfigOverride($this->language->getId(), $name);
$element = $this->createFormElement($schema);
$element->setConfig($base_config, $config_translation, $value);
// If no overrides, delete language specific configuration file.
$saved_config = $config_translation->get();
if (empty($saved_config)) {
$config_translation->delete();
$this->messenger()->addStatus($this->t('@language translation was not added. To add a translation, you must modify the configuration.', ['@language' => $this->language->getName()]));
}
else {
$config_translation->save();
$this->messenger()->addStatus($this->t('Successfully saved @language translation.', ['@language' => $this->language->getName()]));
}
}
$form_state->setRedirect(
$this->mapper->getOverviewRouteName(),
$this->mapper->getOverviewRouteParameters()
);
}
/**
* Creates a form element builder.
*
* @param \Drupal\Core\TypedData\TypedDataInterface $schema
* Schema definition of configuration.
*
* @return \Drupal\config_translation\FormElement\ElementInterface|null
* The element builder object if possible.
*/
public static function createFormElement(TypedDataInterface $schema) {
$definition = $schema->getDataDefinition();
// Form element classes can be specified even for non-translatable elements
// such as the ListElement form element which is used for Mapping and
// Sequence schema elements.
if (isset($definition['form_element_class'])) {
if (!$definition->getLabel()) {
$definition->setLabel(new TranslatableMarkup('n/a'));
}
$class = $definition['form_element_class'];
return $class::create($schema);
}
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace Drupal\config_translation\FormElement;
use Drupal\Core\Language\LanguageInterface;
/**
* Defines the date format element for the configuration translation interface.
*/
class DateFormat extends FormElementBase {
/**
* {@inheritdoc}
*/
public function getTranslationElement(LanguageInterface $translation_language, $source_config, $translation_config) {
/** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = \Drupal::service('date.formatter');
$description = $this->t('A user-defined date format. See the <a href="https://www.php.net/manual/datetime.format.php#refsect1-datetime.format-parameters">PHP manual</a> for available options.');
$format = $this->t('Displayed as %date_format', ['%date_format' => $date_formatter->format(\Drupal::time()->getRequestTime(), 'custom', $translation_config)]);
return [
'#type' => 'textfield',
'#description' => $description,
'#field_suffix' => ' <small data-drupal-date-formatter="preview">' . $format . '</small>',
'#attributes' => [
'data-drupal-date-formatter' => 'source',
],
'#attached' => [
'drupalSettings' => ['dateFormats' => $date_formatter->getSampleDateFormats($translation_language->getId())],
'library' => ['system/drupal.system.date'],
],
] + parent::getTranslationElement($translation_language, $source_config, $translation_config);
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace Drupal\config_translation\FormElement;
use Drupal\Core\Config\Config;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\TypedData\TypedDataInterface;
use Drupal\language\Config\LanguageConfigOverride;
/**
* Provides an interface for configuration translation form elements.
*/
interface ElementInterface {
/**
* Creates a form element instance from a schema definition.
*
* @param \Drupal\Core\TypedData\TypedDataInterface $schema
* The configuration schema.
*
* @return static
*/
public static function create(TypedDataInterface $schema);
/**
* Builds a render array containing the source and translation form elements.
*
* @param \Drupal\Core\Language\LanguageInterface $source_language
* The source language of the configuration object.
* @param \Drupal\Core\Language\LanguageInterface $translation_language
* The language to display the translation form for.
* @param mixed $source_config
* The configuration value of the element in the source language.
* @param mixed $translation_config
* The configuration value of the element in the language to translate to.
* @param array $parents
* Parents array for the element in the form.
* @param string|null $base_key
* (optional) Base key to be used for the elements in the form. NULL for
* top-level form elements.
*
* @return array
* A render array consisting of the source and translation elements for the
* source value.
*/
public function getTranslationBuild(LanguageInterface $source_language, LanguageInterface $translation_language, $source_config, $translation_config, array $parents, $base_key = NULL);
/**
* Sets configuration based on a nested form value array.
*
* If the configuration values are the same as the source configuration, the
* override should be removed from the translation configuration.
*
* @param \Drupal\Core\Config\Config $base_config
* Base configuration values, in the source language.
* @param \Drupal\language\Config\LanguageConfigOverride $config_translation
* Translation configuration override data.
* @param mixed $config_values
* The configuration value of the element taken from the form values.
* @param string|null $base_key
* (optional) The base key that the schema and the configuration values
* belong to. This should be NULL for the top-level configuration object and
* be populated consecutively when recursing into the configuration
* structure.
*/
public function setConfig(Config $base_config, LanguageConfigOverride $config_translation, $config_values, $base_key = NULL);
}

View File

@ -0,0 +1,188 @@
<?php
namespace Drupal\config_translation\FormElement;
use Drupal\Component\Utility\Html;
use Drupal\Core\Config\Config;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\TypedData\TypedDataInterface;
use Drupal\language\Config\LanguageConfigOverride;
/**
* Provides a common base class for form elements.
*/
abstract class FormElementBase implements ElementInterface {
use StringTranslationTrait;
/**
* The schema element this form is for.
*
* @var \Drupal\Core\TypedData\TypedDataInterface
*/
protected $element;
/**
* The data definition of the element this form element is for.
*
* @var \Drupal\Core\TypedData\DataDefinitionInterface
*/
protected $definition;
/**
* Constructs a FormElementBase.
*
* @param \Drupal\Core\TypedData\TypedDataInterface $element
* The schema element this form element is for.
*/
public function __construct(TypedDataInterface $element) {
$this->element = $element;
$this->definition = $element->getDataDefinition();
}
/**
* {@inheritdoc}
*/
public static function create(TypedDataInterface $schema) {
return new static($schema);
}
/**
* {@inheritdoc}
*/
public function getTranslationBuild(LanguageInterface $source_language, LanguageInterface $translation_language, $source_config, $translation_config, array $parents, $base_key = NULL) {
$build['#theme'] = 'config_translation_manage_form_element';
// For accessibility we make source and translation appear next to each
// other in the source for each element, which is why we utilize the
// 'source' and 'translation' sub-keys for the form. The form values,
// however, should mirror the configuration structure, so that we can
// traverse the configuration schema and still access the right
// configuration values in ConfigTranslationFormBase::setConfig().
// Therefore we make the 'source' and 'translation' keys the top-level
// keys in $form_state['values'].
$build['source'] = $this->getSourceElement($source_language, $source_config);
$build['translation'] = $this->getTranslationElement($translation_language, $source_config, $translation_config);
$build['source']['#parents'] = array_merge(['source'], $parents);
$build['translation']['#parents'] = array_merge(['translation'], $parents);
return $build;
}
/**
* Returns the source element for a given configuration definition.
*
* This can be either a render array that actually outputs the source values
* directly or a read-only form element with the source values depending on
* what is considered to provide a more intuitive user interface for the
* translator.
*
* @param \Drupal\Core\Language\LanguageInterface $source_language
* Thee source language of the configuration object.
* @param mixed $source_config
* The configuration value of the element in the source language.
*
* @return array
* A render array for the source value.
*/
protected function getSourceElement(LanguageInterface $source_language, $source_config) {
if ($source_config) {
$value = '<span lang="' . $source_language->getId() . '">' . nl2br(Html::escape($source_config)) . '</span>';
}
else {
$value = $this->t('(Empty)');
}
return [
'#type' => 'item',
'#title' => $this->t('@label <span class="visually-hidden">(@source_language)</span>', [
// Labels originate from configuration schema and are translatable.
// phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
'@label' => $this->t($this->definition->getLabel()),
'@source_language' => $source_language->getName(),
]),
'#markup' => $value,
];
}
/**
* Returns the translation form element for a given configuration definition.
*
* For complex data structures (such as mappings) that are translatable
* wholesale but contain non-translatable properties, the form element is
* responsible for checking access to the source value of those properties. In
* case of formatted text, for example, access to the source text format must
* be checked. If the translator does not have access to the text format, the
* textarea must be disabled and the translator may not be able to translate
* this particular configuration element. If the translator does have access
* to the text format, the element must be locked down to that particular text
* format; in other words, the format may not be changed by the translator
* (because the text format property is not itself translatable).
*
* In addition, the form element is responsible for checking whether the
* value of such non-translatable properties in the translated configuration
* is equal to the corresponding source values. If not, that means that the
* source value has changed after the translation was added. In this case -
* again - the translation of this element must be disabled if the translator
* does not have access to the source value of the non-translatable property.
* For example, if a formatted text element, whose source format was plain
* text when it was first translated, gets changed to the Full HTML format,
* simply changing the format of the translation would lead to an XSS
* vulnerability as the translated text, that was intended to be escaped,
* would now be displayed unescaped. Thus, if the translator does not have
* access to the Full HTML format, the translation for this particular element
* may not be updated at all (the textarea must be disabled). Only if access
* to the Full HTML format is granted, an explicit translation taking into
* account the updated source value(s) may be submitted.
*
* In the specific case of formatted text this logic is implemented by
* utilizing a form element of type 'text_format' and its #format and
* #allowed_formats properties. The access logic explained above is then
* handled by the 'text_format' element itself, specifically by
* \Drupal\filter\Element\TextFormat::processFormat(). In case such a rich
* element is not available for translation of complex data, similar access
* logic must be implemented manually.
*
* @param \Drupal\Core\Language\LanguageInterface $translation_language
* The language to display the translation form for.
* @param mixed $source_config
* The configuration value of the element in the source language.
* @param mixed $translation_config
* The configuration value of the element in the language to translate to.
*
* @return array
* Form API array to represent the form element.
*
* @see \Drupal\config_translation\FormElement\TextFormat
* @see \Drupal\filter\Element\TextFormat::processFormat()
*/
protected function getTranslationElement(LanguageInterface $translation_language, $source_config, $translation_config) {
// Add basic properties that apply to all form elements.
return [
'#title' => $this->t('@label <span class="visually-hidden">(@source_language)</span>', [
// Labels originate from configuration schema and are translatable.
// phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
'@label' => $this->t($this->definition->getLabel()),
'@source_language' => $translation_language->getName(),
]),
'#default_value' => $translation_config,
'#attributes' => ['lang' => $translation_language->getId()],
];
}
/**
* {@inheritdoc}
*/
public function setConfig(Config $base_config, LanguageConfigOverride $config_translation, $config_values, $base_key = NULL) {
// Save the configuration values, if they are different from the source
// values in the base configuration. Otherwise remove the override.
if ($base_config->get($base_key) !== $config_values) {
$config_translation->set($base_key, $config_values);
}
else {
$config_translation->clear($base_key);
}
}
}

View File

@ -0,0 +1,132 @@
<?php
namespace Drupal\config_translation\FormElement;
use Drupal\Core\Config\Config;
use Drupal\Core\Language\LanguageInterface;
use Drupal\config_translation\Form\ConfigTranslationFormBase;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\TraversableTypedDataInterface;
use Drupal\Core\TypedData\TypedDataInterface;
use Drupal\language\Config\LanguageConfigOverride;
/**
* Defines the list element for the configuration translation interface.
*/
class ListElement implements ElementInterface {
use StringTranslationTrait;
/**
* The schema element this form is for.
*
* @var \Drupal\Core\TypedData\TraversableTypedDataInterface
*/
protected $element;
/**
* Constructs a ListElement.
*
* @param \Drupal\Core\TypedData\TraversableTypedDataInterface $element
* The schema element this form element is for.
*/
public function __construct(TraversableTypedDataInterface $element) {
$this->element = $element;
}
/**
* {@inheritdoc}
*/
public static function create(TypedDataInterface $schema) {
return new static($schema);
}
/**
* {@inheritdoc}
*/
public function getTranslationBuild(LanguageInterface $source_language, LanguageInterface $translation_language, $source_config, $translation_config, array $parents, $base_key = NULL) {
$build = [];
foreach ($this->element as $key => $element) {
$sub_build = [];
$element_key = isset($base_key) ? "$base_key.$key" : $key;
$definition = $element->getDataDefinition();
if ($form_element = ConfigTranslationFormBase::createFormElement($element)) {
$element_parents = array_merge($parents, [$key]);
$sub_build += $form_element->getTranslationBuild($source_language, $translation_language, $source_config[$key], $translation_config[$key], $element_parents, $element_key);
if (empty($sub_build)) {
continue;
}
// Build the sub-structure and include it with a wrapper in the form if
// there are any translatable elements there.
$build[$key] = [];
if ($element instanceof TraversableTypedDataInterface) {
$build[$key] = [
'#type' => 'details',
'#title' => $this->getGroupTitle($definition, $sub_build),
'#open' => empty($base_key),
];
}
$build[$key] += $sub_build;
}
}
return $build;
}
/**
* {@inheritdoc}
*/
public function setConfig(Config $base_config, LanguageConfigOverride $config_translation, $config_values, $base_key = NULL) {
foreach ($this->element as $key => $element) {
$element_key = isset($base_key) ? "$base_key.$key" : $key;
if ($form_element = ConfigTranslationFormBase::createFormElement($element)) {
// Traverse into the next level of the configuration.
$value = $config_values[$key] ?? NULL;
$form_element->setConfig($base_config, $config_translation, $value, $element_key);
}
}
}
/**
* Returns the title for the 'details' element of a group of schema elements.
*
* For some configuration elements the same element structure can be repeated
* multiple times (for example views displays, filters, etc.). Thus, we try to
* find a more usable title for the details summary. First check if there is
* an element which is called title or label and use its value. Then check if
* there is an element which contains these words and use those. Fall back
* to the generic definition label if no such element is found.
*
* @param \Drupal\Core\TypedData\DataDefinitionInterface $definition
* The definition of the schema element.
* @param array $group_build
* The renderable array for the group of schema elements.
*
* @return string
* The title for the group of schema elements.
*/
protected function getGroupTitle(DataDefinitionInterface $definition, array $group_build) {
$title = '';
if (isset($group_build['title']['source'])) {
$title = $group_build['title']['source']['#markup'];
}
elseif (isset($group_build['label']['source'])) {
$title = $group_build['label']['source']['#markup'];
}
else {
foreach (array_keys($group_build) as $title_key) {
if (isset($group_build[$title_key]['source']) && (str_contains($title_key, 'title') || str_contains($title_key, 'label'))) {
$title = $group_build[$title_key]['source']['#markup'];
break;
}
}
}
// phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
return (!empty($title) ? (strip_tags($title) . ' ') : '') . $this->t($definition['label']);
}
}

View File

@ -0,0 +1,82 @@
<?php
namespace Drupal\config_translation\FormElement;
use Drupal\Component\Gettext\PoItem;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Config\Config;
use Drupal\Core\Language\LanguageInterface;
use Drupal\language\Config\LanguageConfigOverride;
/**
* Defines form elements for plurals in configuration translation.
*/
class PluralVariants extends FormElementBase {
/**
* {@inheritdoc}
*/
protected function getSourceElement(LanguageInterface $source_language, $source_config) {
$plurals = $this->getNumberOfPlurals($source_language->getId());
$values = explode(PoItem::DELIMITER, $source_config);
$element = [
'#type' => 'fieldset',
'#title' => new FormattableMarkup('@label <span class="visually-hidden">(@source_language)</span>', [
// Labels originate from configuration schema and are translatable.
// phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
'@label' => $this->t($this->definition->getLabel()),
'@source_language' => $source_language->getName(),
]),
'#tree' => TRUE,
];
for ($i = 0; $i < $plurals; $i++) {
$element[$i] = [
'#type' => 'item',
// @todo Should use better labels https://www.drupal.org/node/2499639
'#title' => $i == 0 ? $this->t('Singular form') : $this->formatPlural($i, 'First plural form', '@count. plural form'),
'#markup' => new FormattableMarkup('<span lang="@langcode">@value</span>', [
'@langcode' => $source_language->getId(),
'@value' => $values[$i] ?? $this->t('(Empty)'),
]),
];
}
return $element;
}
/**
* {@inheritdoc}
*/
protected function getTranslationElement(LanguageInterface $translation_language, $source_config, $translation_config) {
$plurals = $this->getNumberOfPlurals($translation_language->getId());
$values = explode(PoItem::DELIMITER, $translation_config);
$element = [
'#type' => 'fieldset',
'#title' => new FormattableMarkup('@label <span class="visually-hidden">(@translation_language)</span>', [
// Labels originate from configuration schema and are translatable.
// phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
'@label' => $this->t($this->definition->getLabel()),
'@translation_language' => $translation_language->getName(),
]),
'#tree' => TRUE,
];
for ($i = 0; $i < $plurals; $i++) {
$element[$i] = [
'#type' => 'textfield',
// @todo Should use better labels https://www.drupal.org/node/2499639
'#title' => $i == 0 ? $this->t('Singular form') : $this->formatPlural($i, 'First plural form', '@count. plural form'),
'#default_value' => $values[$i] ?? '',
'#attributes' => ['lang' => $translation_language->getId()],
];
}
return $element;
}
/**
* {@inheritdoc}
*/
public function setConfig(Config $base_config, LanguageConfigOverride $config_translation, $config_values, $base_key = NULL) {
$config_values = implode(PoItem::DELIMITER, $config_values);
parent::setConfig($base_config, $config_translation, $config_values, $base_key);
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace Drupal\config_translation\FormElement;
use Drupal\Core\Language\LanguageInterface;
/**
* Defines the text_format element for the configuration translation interface.
*/
class TextFormat extends FormElementBase {
/**
* {@inheritdoc}
*/
public function getSourceElement(LanguageInterface $source_language, $source_config) {
// Instead of the formatted output show a disabled textarea. This allows for
// easier side-by-side comparison, especially with formats with text
// editors.
return $this->getTranslationElement($source_language, $source_config, $source_config) + [
'#value' => $source_config['value'],
'#disabled' => TRUE,
'#allow_focus' => TRUE,
];
}
/**
* {@inheritdoc}
*/
public function getTranslationElement(LanguageInterface $translation_language, $source_config, $translation_config) {
return [
'#type' => 'text_format',
// Override the #default_value property from the parent class.
'#default_value' => $translation_config['value'],
'#format' => $translation_config['format'],
// @see \Drupal\config_translation\Element\FormElementBase::getTranslationElement()
'#allowed_formats' => [$source_config['format']],
] + parent::getTranslationElement($translation_language, $source_config, $translation_config);
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace Drupal\config_translation\FormElement;
use Drupal\Core\Language\LanguageInterface;
/**
* Defines the textarea element for the configuration translation interface.
*/
class Textarea extends FormElementBase {
/**
* {@inheritdoc}
*/
public function getTranslationElement(LanguageInterface $translation_language, $source_config, $translation_config) {
// Estimate a comfortable size of the input textarea.
if (is_string($translation_config)) {
$rows_words = ceil(str_word_count($translation_config) / 5);
$rows_newlines = substr_count($translation_config, "\n") + 1;
$rows = max($rows_words, $rows_newlines);
}
return [
'#type' => 'textarea',
'#rows' => $rows ?? 1,
] + parent::getTranslationElement($translation_language, $source_config, $translation_config);
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace Drupal\config_translation\FormElement;
use Drupal\Core\Language\LanguageInterface;
/**
* Defines the textfield element for the configuration translation interface.
*/
class Textfield extends FormElementBase {
/**
* {@inheritdoc}
*/
public function getTranslationElement(LanguageInterface $translation_language, $source_config, $translation_config) {
return [
'#type' => 'textfield',
] + parent::getTranslationElement($translation_language, $source_config, $translation_config);
}
}

View File

@ -0,0 +1,225 @@
<?php
namespace Drupal\config_translation\Hook;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\field\FieldConfigInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Url;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Hook\Attribute\Hook;
/**
* Hook implementations for config_translation.
*/
class ConfigTranslationHooks {
use StringTranslationTrait;
/**
* Implements hook_help().
*/
#[Hook('help')]
public function help($route_name, RouteMatchInterface $route_match): ?string {
switch ($route_name) {
case 'help.page.config_translation':
$output = '';
$output .= '<h2>' . $this->t('About') . '</h2>';
$output .= '<p>' . $this->t('The Configuration Translation module allows you to translate configuration text; for example, the site name, vocabularies, menus, or date formats. Together with the modules <a href=":language">Language</a>, <a href=":content-translation">Content Translation</a>, and <a href=":locale">Interface Translation</a>, it allows you to build multilingual websites. For more information, see the <a href=":doc_url">online documentation for the Configuration Translation module</a>.', [
':doc_url' => 'https://www.drupal.org/documentation/modules/config_translation',
':config' => Url::fromRoute('help.page', [
'name' => 'config',
])->toString(),
':language' => Url::fromRoute('help.page', [
'name' => 'language',
])->toString(),
':locale' => Url::fromRoute('help.page', [
'name' => 'locale',
])->toString(),
':content-translation' => \Drupal::moduleHandler()->moduleExists('content_translation') ? Url::fromRoute('help.page', [
'name' => 'content_translation',
])->toString() : '#',
]) . '</p>';
$output .= '<h2>' . $this->t('Uses') . '</h2>';
$output .= '<dl>';
$output .= '<dt>' . $this->t('Enabling translation') . '</dt>';
$output .= '<dd>' . $this->t('In order to translate configuration, the website must have at least two <a href=":url">languages</a>.', [
':url' => Url::fromRoute('entity.configurable_language.collection')->toString(),
]) . '</dd>';
$output .= '<dt>' . $this->t('Translating configuration text') . '</dt>';
$output .= '<dd>' . $this->t('Users with the <em>Translate user edited configuration</em> permission can access the configuration translation overview, and manage translations for specific languages. The <a href=":translation-page">Configuration translation</a> page shows a list of all configuration text that can be translated, either as individual items or as lists. After you click on <em>Translate</em>, you are provided with a list of all languages. You can <em>add</em> or <em>edit</em> a translation for a specific language. Users with specific configuration permissions can also <em>edit</em> the text for the site\'s default language. For some configuration text items (for example for the site information), the specific translation pages can also be accessed directly from their configuration pages.', [
':translation-page' => Url::fromRoute('config_translation.mapper_list')->toString(),
]) . '</dd>';
$output .= '<dt>' . $this->t('Translating date formats') . '</dt>';
$output .= '<dd>' . $this->t('You can choose to translate date formats on the <a href=":translation-page">Configuration translation</a> page. This allows you not only to translate the label text, but also to set a language-specific <em>PHP date format</em>.', [
':translation-page' => Url::fromRoute('config_translation.mapper_list')->toString(),
]) . '</dd>';
$output .= '</dl>';
return $output;
case 'config_translation.mapper_list':
$output = '<p>' . $this->t('This page lists all configuration items on your site that have translatable text, like your site name, role names, etc.') . '</p>';
return $output;
}
return NULL;
}
/**
* Implements hook_theme().
*/
#[Hook('theme')]
public function theme() : array {
return [
'config_translation_manage_form_element' => [
'render element' => 'element',
'template' => 'config_translation_manage_form_element',
],
];
}
/**
* Implements hook_themes_installed().
*/
#[Hook('themes_installed')]
public function themesInstalled(): void {
// Themes can provide *.config_translation.yml declarations.
// @todo Make ThemeHandler trigger an event instead and make
// ConfigMapperManager plugin manager subscribe to it.
// @see https://www.drupal.org/node/2206347
\Drupal::service('plugin.manager.config_translation.mapper')->clearCachedDefinitions();
}
/**
* Implements hook_themes_uninstalled().
*/
#[Hook('themes_uninstalled')]
public function themesUninstalled(): void {
// Themes can provide *.config_translation.yml declarations.
// @todo Make ThemeHandler trigger an event instead and make
// ConfigMapperManager plugin manager subscribe to it.
// @see https://www.drupal.org/node/2206347
\Drupal::service('plugin.manager.config_translation.mapper')->clearCachedDefinitions();
}
/**
* Implements hook_entity_type_alter().
*/
#[Hook('entity_type_alter')]
public function entityTypeAlter(array &$entity_types) : void {
/** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
foreach ($entity_types as $entity_type_id => $entity_type) {
if ($entity_type->entityClassImplements(ConfigEntityInterface::class)) {
if ($entity_type_id == 'block') {
$class = 'Drupal\config_translation\Controller\ConfigTranslationBlockListBuilder';
}
elseif ($entity_type_id == 'field_config') {
$class = 'Drupal\config_translation\Controller\ConfigTranslationFieldListBuilder';
// Will be filled in dynamically, see
// \Drupal\field\Entity\FieldConfig::linkTemplates().
$entity_type->setLinkTemplate('config-translation-overview', $entity_type->getLinkTemplate('edit-form') . '/translate');
}
else {
$class = 'Drupal\config_translation\Controller\ConfigTranslationEntityListBuilder';
}
$entity_type->setHandlerClass('config_translation_list', $class);
if ($entity_type->hasLinkTemplate('edit-form')) {
$entity_type->setLinkTemplate('config-translation-overview', $entity_type->getLinkTemplate('edit-form') . '/translate');
}
}
}
}
/**
* Implements hook_config_translation_info().
*/
#[Hook('config_translation_info')]
public function configTranslationInfo(&$info): void {
$entity_type_manager = \Drupal::entityTypeManager();
// If field UI is not enabled, the base routes of the type
// "entity.field_config.{$entity_type}_field_edit_form" are not defined.
if (\Drupal::moduleHandler()->moduleExists('field_ui')) {
// Add fields entity mappers to all fieldable entity types defined.
foreach ($entity_type_manager->getDefinitions() as $entity_type_id => $entity_type) {
// Make sure entity type has field UI enabled and has a base route.
if ($entity_type->get('field_ui_base_route')) {
$info[$entity_type_id . '_fields'] = [
'base_route_name' => "entity.field_config.{$entity_type_id}_field_edit_form",
'entity_type' => 'field_config',
'class' => '\Drupal\config_translation\ConfigFieldMapper',
'base_entity_type' => $entity_type_id,
'weight' => 10,
];
}
}
}
// Discover configuration entities automatically.
foreach ($entity_type_manager->getDefinitions() as $entity_type_id => $entity_type) {
// Determine base path for entities automatically if provided via the
// configuration entity.
if (!$entity_type->entityClassImplements(ConfigEntityInterface::class) || !$entity_type->hasLinkTemplate('edit-form')) {
// Do not record this entity mapper if the entity type does not
// provide a base route. We'll surely not be able to do anything with
// it anyway. Configuration entities with a dynamic base path, such as
// fields, need special treatment. See above.
continue;
}
// Use the entity type as the plugin ID.
$base_route_name = "entity.{$entity_type_id}.edit_form";
$info[$entity_type_id] = [
'class' => '\Drupal\config_translation\ConfigEntityMapper',
'base_route_name' => $base_route_name,
'title' => $entity_type->getSingularLabel(),
'names' => [],
'entity_type' => $entity_type_id,
'weight' => 10,
];
}
}
/**
* Implements hook_entity_operation().
*/
#[Hook('entity_operation')]
public function entityOperation(EntityInterface $entity): array {
$operations = [];
$entity_type = $entity->getEntityType();
if ($entity_type->entityClassImplements(ConfigEntityInterface::class) && $entity->hasLinkTemplate('config-translation-overview') && \Drupal::currentUser()->hasPermission('translate configuration')) {
$link_template = 'config-translation-overview';
if ($entity instanceof FieldConfigInterface) {
$link_template = "config-translation-overview.{$entity->getTargetEntityTypeId()}";
}
$operations['translate'] = [
'title' => $this->t('Translate'),
'weight' => 50,
'url' => $entity->toUrl($link_template),
];
}
return $operations;
}
/**
* Implements hook_config_schema_info_alter().
*/
#[Hook('config_schema_info_alter')]
public function configSchemaInfoAlter(&$definitions): void {
$map = [
'label' => '\Drupal\config_translation\FormElement\Textfield',
'text' => '\Drupal\config_translation\FormElement\Textarea',
'date_format' => '\Drupal\config_translation\FormElement\DateFormat',
'text_format' => '\Drupal\config_translation\FormElement\TextFormat',
'mapping' => '\Drupal\config_translation\FormElement\ListElement',
'sequence' => '\Drupal\config_translation\FormElement\ListElement',
'plural_label' => '\Drupal\config_translation\FormElement\PluralVariants',
];
// Enhance the text and date type definitions with classes to generate
// proper form elements in ConfigTranslationFormBase. Other translatable
// types will appear as a one line textfield.
foreach ($definitions as $type => &$definition) {
if (isset($map[$type]) && !isset($definition['form_element_class'])) {
$definition['form_element_class'] = $map[$type];
}
}
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace Drupal\config_translation\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\config_translation\ConfigMapperManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides dynamic contextual links for configuration translation.
*/
class ConfigTranslationContextualLinks extends DeriverBase implements ContainerDeriverInterface {
/**
* The mapper plugin discovery service.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface
*/
protected $mapperManager;
/**
* Constructs a new ConfigTranslationContextualLinks.
*
* @param \Drupal\config_translation\ConfigMapperManagerInterface $mapper_manager
* The mapper plugin discovery service.
*/
public function __construct(ConfigMapperManagerInterface $mapper_manager) {
$this->mapperManager = $mapper_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static(
$container->get('plugin.manager.config_translation.mapper')
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
// Create contextual links for all mappers.
$mappers = $this->mapperManager->getMappers();
foreach ($mappers as $plugin_id => $mapper) {
// @todo Contextual groups do not map to entity types in a predictable
// way. See https://www.drupal.org/node/2134841 to make them
// predictable.
$group_name = $mapper->getContextualLinkGroup();
if (empty($group_name)) {
continue;
}
/** @var \Drupal\config_translation\ConfigMapperInterface $mapper */
$route_name = $mapper->getOverviewRouteName();
$this->derivatives[$route_name] = $base_plugin_definition;
$this->derivatives[$route_name]['config_translation_plugin_id'] = $plugin_id;
$this->derivatives[$route_name]['class'] = '\Drupal\config_translation\Plugin\Menu\ContextualLink\ConfigTranslationContextualLink';
$this->derivatives[$route_name]['route_name'] = $route_name;
$this->derivatives[$route_name]['group'] = $group_name;
}
return parent::getDerivativeDefinitions($base_plugin_definition);
}
}

View File

@ -0,0 +1,72 @@
<?php
namespace Drupal\config_translation\Plugin\Derivative;
use Drupal\config_translation\ConfigMapperManagerInterface;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides dynamic local tasks for config translation.
*/
class ConfigTranslationLocalTasks extends DeriverBase implements ContainerDeriverInterface {
/**
* The mapper plugin discovery service.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface
*/
protected $mapperManager;
/**
* The base plugin ID.
*
* @var string
*/
protected $basePluginId;
/**
* Constructs a new ConfigTranslationLocalTasks.
*
* @param string $base_plugin_id
* The base plugin ID.
* @param \Drupal\config_translation\ConfigMapperManagerInterface $mapper_manager
* The mapper plugin discovery service.
*/
public function __construct($base_plugin_id, ConfigMapperManagerInterface $mapper_manager) {
$this->basePluginId = $base_plugin_id;
$this->mapperManager = $mapper_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static(
$base_plugin_id,
$container->get('plugin.manager.config_translation.mapper')
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
$mappers = $this->mapperManager->getMappers();
foreach ($mappers as $plugin_id => $mapper) {
/** @var \Drupal\config_translation\ConfigMapperInterface $mapper */
$route_name = $mapper->getOverviewRouteName();
$base_route = $mapper->getBaseRouteName();
if (!empty($base_route)) {
$this->derivatives[$route_name] = $base_plugin_definition;
$this->derivatives[$route_name]['config_translation_plugin_id'] = $plugin_id;
$this->derivatives[$route_name]['class'] = '\Drupal\config_translation\Plugin\Menu\LocalTask\ConfigTranslationLocalTask';
$this->derivatives[$route_name]['route_name'] = $route_name;
$this->derivatives[$route_name]['base_route'] = $base_route;
}
}
return parent::getDerivativeDefinitions($base_plugin_definition);
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace Drupal\config_translation\Plugin\Menu\ContextualLink;
use Drupal\Core\Menu\ContextualLinkDefault;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\Request;
/**
* Defines a contextual link plugin with a dynamic title.
*/
class ConfigTranslationContextualLink extends ContextualLinkDefault {
use StringTranslationTrait;
/**
* The mapper plugin discovery service.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface
*/
protected $mapperManager;
/**
* {@inheritdoc}
*/
public function getTitle(?Request $request = NULL) {
// Use the custom 'config_translation_plugin_id' plugin definition key to
// retrieve the title. We need to retrieve a runtime title (as opposed to
// storing the title on the plugin definition for the link) because it
// contains translated parts that we need in the runtime language.
$type_name = mb_strtolower($this->mapperManager()->createInstance($this->pluginDefinition['config_translation_plugin_id'])->getTypeLabel());
return $this->t('Translate @type_name', ['@type_name' => $type_name]);
}
/**
* Gets the mapper manager.
*
* @return \Drupal\config_translation\ConfigMapperManagerInterface
* The mapper manager.
*/
protected function mapperManager() {
if (!$this->mapperManager) {
$this->mapperManager = \Drupal::service('plugin.manager.config_translation.mapper');
}
return $this->mapperManager;
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace Drupal\config_translation\Plugin\Menu\LocalTask;
use Drupal\Core\Menu\LocalTaskDefault;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\Request;
/**
* Defines a local task plugin with a dynamic title.
*/
class ConfigTranslationLocalTask extends LocalTaskDefault {
use StringTranslationTrait;
/**
* The mapper plugin discovery service.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface
*/
protected $mapperManager;
/**
* {@inheritdoc}
*/
public function getTitle(?Request $request = NULL) {
// Take custom 'config_translation_plugin_id' plugin definition key to
// retrieve title. We need to retrieve a runtime title (as opposed to
// storing the title on the plugin definition for the link) because
// it contains translated parts that we need in the runtime language.
$type_name = mb_strtolower($this->mapperManager()->createInstance($this->pluginDefinition['config_translation_plugin_id'])->getTypeLabel());
return $this->t('Translate @type_name', ['@type_name' => $type_name]);
}
/**
* Gets the mapper manager.
*
* @return \Drupal\config_translation\ConfigMapperManagerInterface
* The mapper manager.
*/
protected function mapperManager() {
if (!$this->mapperManager) {
$this->mapperManager = \Drupal::service('plugin.manager.config_translation.mapper');
}
return $this->mapperManager;
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace Drupal\config_translation\Plugin\migrate\source\d6;
use Drupal\user\Plugin\migrate\source\ProfileField;
// cspell:ignore nprofile objectid
/**
* Drupal 6 i18n strings profile field source from database.
*
* For available configuration keys, refer to the parent classes.
*
* @see \Drupal\migrate\Plugin\migrate\source\SqlBase
* @see \Drupal\migrate\Plugin\migrate\source\SourcePluginBase
*
* @MigrateSource(
* id = "d6_profile_field_translation",
* source_module = "i18nprofile"
* )
*/
class ProfileFieldTranslation extends ProfileField {
/**
* {@inheritdoc}
*/
public function query() {
$query = parent::query();
$query->fields('i18n', ['property'])
->fields('lt', ['lid', 'translation', 'language']);
$query->leftJoin('i18n_strings', 'i18n', '[i18n].[objectid] = [pf].[name]');
$query->innerJoin('locales_target', 'lt', '[lt].[lid] = [i18n].[lid]');
return $query;
}
/**
* {@inheritdoc}
*/
public function fields() {
$fields = [
'lid' => $this->t('Locales target language ID.'),
'language' => $this->t('Language for this field.'),
'translation' => $this->t('Translation of either the title or explanation.'),
];
return parent::fields() + $fields;
}
/**
* {@inheritdoc}
*/
public function getIds() {
$ids['language']['type'] = 'string';
$ids['lid']['type'] = 'integer';
$ids['lid']['alias'] = 'lt';
return parent::getIds() + $ids;
}
}

View File

@ -0,0 +1,55 @@
<?php
namespace Drupal\config_translation\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\config_translation\ConfigMapperManagerInterface;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;
/**
* Listens to the dynamic route events.
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* The mapper plugin discovery service.
*
* @var \Drupal\config_translation\ConfigMapperManagerInterface
*/
protected $mapperManager;
/**
* Constructs a new RouteSubscriber.
*
* @param \Drupal\config_translation\ConfigMapperManagerInterface $mapper_manager
* The mapper plugin discovery service.
*/
public function __construct(ConfigMapperManagerInterface $mapper_manager) {
$this->mapperManager = $mapper_manager;
}
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
$mappers = $this->mapperManager->getMappers($collection);
foreach ($mappers as $mapper) {
$collection->add($mapper->getOverviewRouteName(), $mapper->getOverviewRoute());
$collection->add($mapper->getAddRouteName(), $mapper->getAddRoute());
$collection->add($mapper->getEditRouteName(), $mapper->getEditRoute());
$collection->add($mapper->getDeleteRouteName(), $mapper->getDeleteRoute());
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
// Come after field_ui.
$events[RoutingEvents::ALTER] = ['onAlterRoutes', -110];
return $events;
}
}