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,71 @@
<?php
namespace Drupal\path\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides the path admin overview filter form.
*
* @internal
*/
class PathFilterForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'path_admin_filter_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $keys = NULL) {
$form['#attributes'] = ['class' => ['search-form']];
$form['basic'] = [
'#type' => 'details',
'#title' => $this->t('Filter aliases'),
'#open' => TRUE,
'#attributes' => ['class' => ['container-inline']],
];
$form['basic']['filter'] = [
'#type' => 'search',
'#title' => $this->t('Path alias'),
'#title_display' => 'invisible',
'#default_value' => $keys,
'#maxlength' => 128,
'#size' => 25,
];
$form['basic']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Filter'),
];
if ($keys) {
$form['basic']['reset'] = [
'#type' => 'submit',
'#value' => $this->t('Reset'),
'#submit' => ['::resetForm'],
];
}
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect('entity.path_alias.collection', [], [
'query' => ['search' => trim($form_state->getValue('filter'))],
]);
}
/**
* Resets the filter selections.
*/
public function resetForm(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect('entity.path_alias.collection');
}
}

View File

@ -0,0 +1,157 @@
<?php
namespace Drupal\path\Hook;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\path\PathAliasListBuilder;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;
use Drupal\Core\Entity\ContentEntityDeleteForm;
use Drupal\path\PathAliasForm;
use Drupal\Core\Url;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Hook\Attribute\Hook;
/**
* Hook implementations for path.
*/
class PathHooks {
use StringTranslationTrait;
/**
* Implements hook_help().
*/
#[Hook('help')]
public function help($route_name, RouteMatchInterface $route_match): ?string {
switch ($route_name) {
case 'help.page.path':
$output = '';
$output .= '<h2>' . $this->t('About') . '</h2>';
$output .= '<p>' . $this->t('The Path module allows you to specify an alias, or custom URL, for any existing internal system path. Aliases should not be confused with URL redirects, which allow you to forward a changed or inactive URL to a new URL. In addition to making URLs more readable, aliases also help search engines index content more effectively. Multiple aliases may be used for a single internal system path. To automate the aliasing of paths, you can install the contributed module <a href=":pathauto">Pathauto</a>. For more information, see the <a href=":path">online documentation for the Path module</a>.', [
':path' => 'https://www.drupal.org/documentation/modules/path',
':pathauto' => 'https://www.drupal.org/project/pathauto',
]) . '</p>';
$output .= '<h2>' . $this->t('Uses') . '</h2>';
$output .= '<dl>';
$output .= '<dt>' . $this->t('Creating aliases') . '</dt>';
$output .= '<dd>' . $this->t('If you create or edit a taxonomy term you can add an alias (for example <em>music/jazz</em>) in the field "URL alias". When creating or editing content you can add an alias (for example <em>about-us/team</em>) under the section "URL path settings" in the field "URL alias". Aliases for any other path can be added through the page <a href=":aliases">URL aliases</a>. To add aliases a user needs the permission <a href=":permissions">Create and edit URL aliases</a>.', [
':aliases' => Url::fromRoute('entity.path_alias.collection')->toString(),
':permissions' => Url::fromRoute('user.admin_permissions.module', [
'modules' => 'path',
])->toString(),
]) . '</dd>';
$output .= '<dt>' . $this->t('Managing aliases') . '</dt>';
$output .= '<dd>' . $this->t('The Path module provides a way to search and view a <a href=":aliases">list of all aliases</a> that are in use on your website. Aliases can be added, edited and deleted through this list.', [
':aliases' => Url::fromRoute('entity.path_alias.collection')->toString(),
]) . '</dd>';
$output .= '</dl>';
return $output;
case 'entity.path_alias.collection':
return '<p>' . $this->t("An alias defines a different name for an existing URL path - for example, the alias 'about' for the URL path 'node/1'. A URL path can have multiple aliases.") . '</p>';
case 'entity.path_alias.add_form':
return '<p>' . $this->t('Enter the path you wish to create the alias for, followed by the name of the new alias.') . '</p>';
}
return NULL;
}
/**
* Implements hook_entity_type_alter().
*/
#[Hook('entity_type_alter')]
public function entityTypeAlter(array &$entity_types) : void {
// @todo Remove the conditional once core fully supports "path_alias" as an
// optional module. See https://drupal.org/node/3092090.
/** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
if (isset($entity_types['path_alias'])) {
$entity_types['path_alias']->setFormClass('default', PathAliasForm::class);
$entity_types['path_alias']->setFormClass('delete', ContentEntityDeleteForm::class);
$entity_types['path_alias']->setHandlerClass('route_provider', ['html' => AdminHtmlRouteProvider::class]);
$entity_types['path_alias']->setListBuilderClass(PathAliasListBuilder::class);
$entity_types['path_alias']->setLinkTemplate('collection', '/admin/config/search/path');
$entity_types['path_alias']->setLinkTemplate('add-form', '/admin/config/search/path/add');
$entity_types['path_alias']->setLinkTemplate('edit-form', '/admin/config/search/path/edit/{path_alias}');
$entity_types['path_alias']->setLinkTemplate('delete-form', '/admin/config/search/path/delete/{path_alias}');
}
}
/**
* Implements hook_entity_base_field_info_alter().
*/
#[Hook('entity_base_field_info_alter')]
public function entityBaseFieldInfoAlter(&$fields, EntityTypeInterface $entity_type): void {
/** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
if ($entity_type->id() === 'path_alias') {
$fields['langcode']->setDisplayOptions('form', [
'type' => 'language_select',
'weight' => 0,
'settings' => [
'include_locked' => FALSE,
],
]);
$fields['path']->setDisplayOptions('form', ['type' => 'string_textfield', 'weight' => 5, 'settings' => ['size' => 45]]);
$fields['alias']->setDisplayOptions('form', ['type' => 'string_textfield', 'weight' => 10, 'settings' => ['size' => 45]]);
}
}
/**
* Implements hook_entity_base_field_info().
*/
#[Hook('entity_base_field_info')]
public function entityBaseFieldInfo(EntityTypeInterface $entity_type): array {
if (in_array($entity_type->id(), ['taxonomy_term', 'node', 'media'], TRUE)) {
$fields['path'] = BaseFieldDefinition::create('path')->setLabel($this->t('URL alias'))->setTranslatable(TRUE)->setDisplayOptions('form', ['type' => 'path', 'weight' => 30])->setDisplayConfigurable('form', TRUE)->setComputed(TRUE);
return $fields;
}
return [];
}
/**
* Implements hook_entity_translation_create().
*/
#[Hook('entity_translation_create')]
public function entityTranslationCreate(ContentEntityInterface $translation): void {
foreach ($translation->getFieldDefinitions() as $field_name => $field_definition) {
if ($field_definition->getType() === 'path' && $translation->get($field_name)->pid) {
// If there are values and a path ID, update the langcode and unset the
// path ID to save this as a new alias.
$translation->get($field_name)->langcode = $translation->language()->getId();
$translation->get($field_name)->pid = NULL;
}
}
}
/**
* Implements hook_field_widget_single_element_form_alter().
*/
#[Hook('field_widget_single_element_form_alter')]
public function fieldWidgetSingleElementFormAlter(&$element, FormStateInterface $form_state, $context): void {
$field_definition = $context['items']->getFieldDefinition();
$field_name = $field_definition->getName();
$entity_type = $field_definition->getTargetEntityTypeId();
$widget_name = $context['widget']->getPluginId();
if ($entity_type === 'path_alias') {
if (($field_name === 'path' || $field_name === 'alias') && $widget_name === 'string_textfield') {
$element['value']['#field_prefix'] = \Drupal::service('router.request_context')->getCompleteBaseUrl();
}
if ($field_name === 'langcode') {
$element['value']['#description'] = $this->t('A path alias set for a specific language will always be used when displaying this page in that language, and takes precedence over path aliases set as <em>- Not specified -</em>.');
$element['value']['#empty_value'] = LanguageInterface::LANGCODE_NOT_SPECIFIED;
$element['value']['#empty_option'] = $this->t('- Not specified -');
}
if ($field_name === 'path') {
$element['value']['#description'] = $this->t('Specify the existing path you wish to alias. For example: /node/28, /media/1, /taxonomy/term/1.');
}
if ($field_name === 'alias') {
$element['value']['#description'] = $this->t('Specify an alternative path by which this data can be accessed. For example, type "/about" when writing an about page.');
}
}
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace Drupal\path;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
/**
* Form handler for the path alias edit forms.
*
* @internal
*/
class PathAliasForm extends ContentEntityForm {
/**
* The path_alias entity.
*
* @var \Drupal\path_alias\PathAliasInterface
*/
protected $entity;
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
parent::save($form, $form_state);
$this->messenger()->addStatus($this->t('The alias has been saved.'));
$form_state->setRedirect('entity.path_alias.collection');
}
}

View File

@ -0,0 +1,197 @@
<?php
namespace Drupal\path;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\path_alias\AliasManagerInterface;
use Drupal\Core\Url;
use Drupal\path\Form\PathFilterForm;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Defines a class to build a listing of path_alias entities.
*
* @see \Drupal\path_alias\Entity\PathAlias
*/
class PathAliasListBuilder extends EntityListBuilder {
/**
* The current request.
*
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $currentRequest;
/**
* The form builder.
*
* @var \Drupal\Core\Form\FormBuilderInterface
*/
protected $formBuilder;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The path alias manager.
*
* @var \Drupal\path_alias\AliasManagerInterface
*/
protected $aliasManager;
/**
* Constructs a new PathAliasListBuilder object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
* @param \Drupal\Core\Entity\EntityStorageInterface $storage
* The entity storage class.
* @param \Symfony\Component\HttpFoundation\Request $current_request
* The current request.
* @param \Drupal\Core\Form\FormBuilderInterface $form_builder
* The form builder.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\path_alias\AliasManagerInterface $alias_manager
* The path alias manager.
*/
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, Request $current_request, FormBuilderInterface $form_builder, LanguageManagerInterface $language_manager, AliasManagerInterface $alias_manager) {
parent::__construct($entity_type, $storage);
$this->currentRequest = $current_request;
$this->formBuilder = $form_builder;
$this->languageManager = $language_manager;
$this->aliasManager = $alias_manager;
}
/**
* {@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('request_stack')->getCurrentRequest(),
$container->get('form_builder'),
$container->get('language_manager'),
$container->get('path_alias.manager')
);
}
/**
* {@inheritdoc}
*/
protected function getEntityIds() {
$query = $this->getStorage()->getQuery()->accessCheck(TRUE);
$search = $this->currentRequest->query->get('search');
if ($search) {
$query->condition('alias', $search, 'CONTAINS');
}
// Only add the pager if a limit is specified.
if ($this->limit) {
$query->pager($this->limit);
}
// Allow the entity query to sort using the table header.
$header = $this->buildHeader();
$query->tableSort($header);
return $query->execute();
}
/**
* {@inheritdoc}
*/
public function render() {
$keys = $this->currentRequest->query->get('search');
$build['path_admin_filter_form'] = $this->formBuilder->getForm(PathFilterForm::class, $keys);
$build += parent::render();
$build['table']['#empty'] = $this->t('No path aliases available. <a href=":link">Add URL alias</a>.', [':link' => Url::fromRoute('entity.path_alias.add_form')->toString()]);
return $build;
}
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header = [
'alias' => [
'data' => $this->t('Alias'),
'field' => 'alias',
'specifier' => 'alias',
'sort' => 'asc',
],
'path' => [
'data' => $this->t('System path'),
'field' => 'path',
'specifier' => 'path',
],
];
// Enable language column and filter if multiple languages are added.
if ($this->languageManager->isMultilingual()) {
$header['language_name'] = [
'data' => $this->t('Language'),
'field' => 'langcode',
'specifier' => 'langcode',
'class' => [RESPONSIVE_PRIORITY_MEDIUM],
];
}
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
/** @var \Drupal\Core\Path\Entity\PathAlias $entity */
$langcode = $entity->language()->getId();
$alias = $entity->getAlias();
$path = $entity->getPath();
$url = Url::fromUserInput($path);
$row['data']['alias']['data'] = [
'#type' => 'link',
'#title' => $alias,
'#url' => $url,
];
// Create a new URL for linking to the un-aliased system path.
$system_url = Url::fromUri("base:{$path}");
$row['data']['path']['data'] = [
'#type' => 'link',
'#title' => $path,
'#url' => $system_url,
];
if ($this->languageManager->isMultilingual()) {
$row['data']['language_name'] = $this->languageManager->getLanguageName($langcode);
}
$row['data']['operations']['data'] = $this->buildOperations($entity);
// If the system path maps to a different URL alias, highlight this table
// row to let the user know of old aliases.
if ($alias != $this->aliasManager->getAliasByPath($path, $langcode)) {
$row['class'] = ['warning'];
}
return $row;
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace Drupal\path\Plugin\Field\FieldType;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\TypedData\ComputedItemListTrait;
/**
* Represents a configurable entity path field.
*/
class PathFieldItemList extends FieldItemList {
use ComputedItemListTrait;
/**
* {@inheritdoc}
*/
protected function computeValue() {
// Default the langcode to the current language if this is a new entity or
// there is no alias for an existent entity.
// @todo Set the langcode to not specified for untranslatable fields
// in https://www.drupal.org/node/2689459.
$value = ['langcode' => $this->getLangcode()];
$entity = $this->getEntity();
if (!$entity->isNew()) {
/** @var \Drupal\path_alias\AliasRepositoryInterface $path_alias_repository */
$path_alias_repository = \Drupal::service('path_alias.repository');
if ($path_alias = $path_alias_repository->lookupBySystemPath('/' . $entity->toUrl()->getInternalPath(), $this->getLangcode())) {
$value = [
'alias' => $path_alias['alias'],
'pid' => $path_alias['id'],
'langcode' => $path_alias['langcode'],
];
}
}
$this->list[0] = $this->createItem(0, $value);
}
/**
* {@inheritdoc}
*/
public function defaultAccess($operation = 'view', ?AccountInterface $account = NULL) {
if ($operation == 'view') {
return AccessResult::allowed();
}
return AccessResult::allowedIfHasPermissions($account, ['create url aliases', 'administer url aliases'], 'OR')->cachePerPermissions();
}
/**
* {@inheritdoc}
*/
public function delete() {
// Delete all aliases associated with this entity in the current language.
$entity = $this->getEntity();
$path_alias_storage = \Drupal::entityTypeManager()->getStorage('path_alias');
$entities = $path_alias_storage->loadByProperties([
'path' => '/' . $entity->toUrl()->getInternalPath(),
'langcode' => $entity->language()->getId(),
]);
$path_alias_storage->delete($entities);
}
}

View File

@ -0,0 +1,147 @@
<?php
namespace Drupal\path\Plugin\Field\FieldType;
use Drupal\Component\Utility\Random;
use Drupal\Core\Field\Attribute\FieldType;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
/**
* Defines the 'path' entity field type.
*/
#[FieldType(
id: "path",
label: new TranslatableMarkup("Path"),
description: new TranslatableMarkup("An entity field containing a path alias and related data."),
default_widget: "path",
no_ui: TRUE,
list_class: PathFieldItemList::class,
constraints: ["PathAlias" => []],
)]
class PathItem extends FieldItemBase {
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['alias'] = DataDefinition::create('string')
->setLabel(t('Path alias'));
$properties['pid'] = DataDefinition::create('integer')
->setLabel(t('Path id'));
$properties['langcode'] = DataDefinition::create('string')
->setLabel(t('Language Code'));
return $properties;
}
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [];
}
/**
* {@inheritdoc}
*/
public function isEmpty() {
$alias = $this->get('alias')->getValue();
$pid = $this->get('pid')->getValue();
$langcode = $this->get('langcode')->getValue();
return ($alias === NULL || $alias === '') && ($pid === NULL || $pid === '') && ($langcode === NULL || $langcode === '');
}
/**
* {@inheritdoc}
*/
public function preSave() {
$alias = $this->get('alias')->getValue();
if ($alias !== NULL) {
$this->set('alias', trim($alias));
}
}
/**
* {@inheritdoc}
*/
public function postSave($update) {
$path_alias_storage = \Drupal::entityTypeManager()->getStorage('path_alias');
$entity = $this->getEntity();
$alias = $this->get('alias')->getValue();
$pid = $this->get('pid')->getValue();
$langcode = $this->get('langcode')->getValue();
// If specified, rely on the langcode property for the language, so that the
// existing language of an alias can be kept. That could for example be
// unspecified even if the field/entity has a specific langcode.
$alias_langcode = ($langcode && $pid) ? $langcode : $this->getLangcode();
// If we have an alias, we need to create or update a path alias entity.
if ($alias) {
$properties = [
'path' => '/' . $entity->toUrl()->getInternalPath(),
'alias' => $alias,
'langcode' => $alias_langcode,
];
if (!$pid) {
// Try to load it from storage before creating it. In some cases the
// path alias could be created before this function runs. For example,
// \Drupal\workspaces\EntityOperations::entityTranslationInsert will
// create a translation, and an associated path alias will be created
// with it.
$query = $path_alias_storage->getQuery()->accessCheck(FALSE);
foreach ($properties as $field => $value) {
$query->condition($field, $value);
}
$ids = $query->execute();
$pid = $ids ? reset($ids) : $pid;
}
if (!$pid) {
$path_alias = $path_alias_storage->create($properties);
$path_alias->save();
$this->set('pid', $path_alias->id());
}
else {
$path_alias = $path_alias_storage->load($pid);
if ($alias != $path_alias->getAlias()) {
$path_alias->setAlias($alias);
$path_alias->save();
}
}
}
elseif ($pid) {
// Otherwise, delete the old alias if the user erased it.
$path_alias = $path_alias_storage->load($pid);
if ($entity->isDefaultRevision()) {
$path_alias_storage->delete([$path_alias]);
}
else {
$path_alias_storage->deleteRevision($path_alias->getRevisionID());
}
}
}
/**
* {@inheritdoc}
*/
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
$random = new Random();
$values['alias'] = '/' . str_replace(' ', '-', strtolower($random->sentences(3)));
return $values;
}
/**
* {@inheritdoc}
*/
public static function mainPropertyName() {
return 'alias';
}
}

View File

@ -0,0 +1,115 @@
<?php
namespace Drupal\path\Plugin\Field\FieldWidget;
use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\Validator\ConstraintViolationInterface;
/**
* Plugin implementation of the 'path' widget.
*/
#[FieldWidget(
id: 'path',
label: new TranslatableMarkup('URL alias'),
field_types: ['path']
)]
class PathWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$entity = $items->getEntity();
$element += [
'#element_validate' => [[static::class, 'validateFormElement']],
];
$element['alias'] = [
'#type' => 'textfield',
'#title' => $element['#title'],
'#default_value' => $items[$delta]->alias,
'#required' => $element['#required'],
'#maxlength' => 255,
'#description' => $this->t('Specify an alternative path by which this data can be accessed. For example, type "/about" when writing an about page.'),
];
$element['pid'] = [
'#type' => 'value',
'#value' => $items[$delta]->pid,
];
$element['source'] = [
'#type' => 'value',
'#value' => !$entity->isNew() ? '/' . $entity->toUrl()->getInternalPath() : NULL,
];
$element['langcode'] = [
'#type' => 'value',
'#value' => $items[$delta]->langcode,
];
// If the advanced settings tabs-set is available (normally rendered in the
// second column on wide-resolutions), place the field as a details element
// in this tab-set.
if (isset($form['advanced'])) {
$element += [
'#type' => 'details',
'#title' => $this->t('URL path settings'),
'#open' => !empty($items[$delta]->alias),
'#group' => 'advanced',
'#access' => $entity->get('path')->access('edit'),
'#attributes' => [
'class' => ['path-form'],
],
'#attached' => [
'library' => ['path/drupal.path'],
],
];
$element['#weight'] = 30;
}
return $element;
}
/**
* Form element validation handler for URL alias form element.
*
* @param array $element
* The form element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
public static function validateFormElement(array &$element, FormStateInterface $form_state) {
// Trim the submitted value of whitespace and slashes.
$alias = rtrim(trim($element['alias']['#value']), " \\/");
if ($alias !== '') {
$form_state->setValueForElement($element['alias'], $alias);
/** @var \Drupal\path_alias\PathAliasInterface $path_alias */
$path_alias = \Drupal::entityTypeManager()->getStorage('path_alias')->create([
'path' => $element['source']['#value'],
'alias' => $alias,
'langcode' => $element['langcode']['#value'],
]);
$violations = $path_alias->validate();
foreach ($violations as $violation) {
// Newly created entities do not have a system path yet, so we need to
// disregard some violations.
if (!$path_alias->getPath() && $violation->getPropertyPath() === 'path') {
continue;
}
$form_state->setError($element['alias'], $violation->getMessage());
}
}
}
/**
* {@inheritdoc}
*/
public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
return $element['alias'];
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace Drupal\path\Plugin\Validation\Constraint;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Attribute\Constraint;
use Symfony\Component\Validator\Constraint as SymfonyConstraint;
/**
* Validation constraint for changing path aliases in pending revisions.
*/
#[Constraint(
id: 'PathAlias',
label: new TranslatableMarkup('Path alias.', [], ['context' => 'Validation'])
)]
class PathAliasConstraint extends SymfonyConstraint {
/**
* The default violation message.
*
* @var string
*/
public $message = 'You can only change the URL alias for the <em>published</em> version of this content.';
}

View File

@ -0,0 +1,63 @@
<?php
namespace Drupal\path\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Constraint validator for changing path aliases in pending revisions.
*/
class PathAliasConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
private $entityTypeManager;
/**
* Creates a new PathAliasConstraintValidator instance.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint): void {
$entity = !empty($value->getParent()) ? $value->getEntity() : NULL;
if ($entity && !$entity->isNew() && !$entity->isDefaultRevision()) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $original */
$original = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
$entity_langcode = $entity->language()->getId();
// Only add the violation if the current translation does not have the
// same path alias.
if ($original->hasTranslation($entity_langcode)) {
if ($value->alias != $original->getTranslation($entity_langcode)->path->alias) {
$this->context->addViolation($constraint->message);
}
}
}
}
}

View File

@ -0,0 +1,73 @@
<?php
namespace Drupal\path\Plugin\migrate\process;
use Drupal\migrate\Attribute\MigrateProcess;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
/**
* A process plugin to update the path of a translated node.
*
* Available configuration keys:
* - source: An array of two values, the first being the original path, and the
* second being an array of the format [nid, langcode] if a translated node
* exists (likely from a migration lookup). Paths not of the format
* '/node/<nid>' will pass through unchanged, as will any inputs with invalid
* or missing translated nodes.
*
* This plugin will return the correct path for the translated node if the above
* conditions are met, and will return the original path otherwise.
*
* Example:
* node_translation:
* -
* plugin: explode
* source: source
* delimiter: /
* -
* # If the source path has no slashes return a dummy default value.
* plugin: extract
* default: 'INVALID_NID'
* index:
* - 1
* -
* plugin: migration_lookup
* migration: d7_node_translation
* _path:
* plugin: concat
* source:
* - constants/slash
* - source
* path:
* plugin: path_set_translated
* source:
* - '@_path'
* - '@node_translation'
*
* In the example above, if the node_translation lookup succeeds and the
* original path is of the format '/node/<original node nid>', then the new path
* will be set to '/node/<translated node nid>'
*/
#[MigrateProcess('path_set_translated')]
class PathSetTranslated extends ProcessPluginBase {
/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
if (!is_array($value)) {
throw new MigrateException("The input value should be an array.");
}
$path = $value[0] ?? '';
$nid = (is_array($value[1]) && isset($value[1][0])) ? $value[1][0] : FALSE;
if (preg_match('/^\/node\/\d+$/', $path) && $nid) {
return '/node/' . $nid;
}
return $path;
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace Drupal\path\Plugin\migrate\source;
use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
/**
* Base class for the url_alias source plugins.
*/
abstract class UrlAliasBase extends DrupalSqlBase {
/**
* {@inheritdoc}
*/
public function query() {
// The order of the migration is significant since
// \Drupal\path_alias\AliasRepository::lookupPathAlias() orders by pid
// before returning a result. Postgres does not automatically order by
// primary key therefore we need to add a specific order by.
return $this->select('url_alias', 'ua')->fields('ua')->orderBy('pid');
}
/**
* {@inheritdoc}
*/
public function fields() {
return [
'pid' => $this->t('The numeric identifier of the path alias.'),
'language' => $this->t('The language code of the URL alias.'),
];
}
/**
* {@inheritdoc}
*/
public function getIds() {
$ids['pid']['type'] = 'integer';
return $ids;
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace Drupal\path\Plugin\migrate\source\d6;
use Drupal\path\Plugin\migrate\source\UrlAliasBase;
/**
* Drupal 6 URL aliases 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_url_alias",
* source_module = "path"
* )
*/
class UrlAlias extends UrlAliasBase {
/**
* {@inheritdoc}
*/
public function fields() {
$fields = parent::fields();
$fields['src'] = $this->t('The internal system path.');
$fields['dst'] = $this->t('The path alias.');
return $fields;
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace Drupal\path\Plugin\migrate\source\d7;
use Drupal\path\Plugin\migrate\source\UrlAliasBase;
/**
* Drupal 7 URL aliases 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 = "d7_url_alias",
* source_module = "path"
* )
*/
class UrlAlias extends UrlAliasBase {
/**
* {@inheritdoc}
*/
public function fields() {
$fields = parent::fields();
$fields['source'] = $this->t('The internal system path.');
$fields['alias'] = $this->t('The path alias.');
return $fields;
}
}