annotate core/modules/workspaces/src/EntityOperations.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@17 1 <?php
Chris@17 2
Chris@17 3 namespace Drupal\workspaces;
Chris@17 4
Chris@17 5 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
Chris@17 6 use Drupal\Core\Entity\EntityInterface;
Chris@17 7 use Drupal\Core\Entity\EntityTypeManagerInterface;
Chris@17 8 use Drupal\Core\Entity\RevisionableInterface;
Chris@17 9 use Drupal\Core\Form\FormStateInterface;
Chris@17 10 use Drupal\Core\StringTranslation\StringTranslationTrait;
Chris@17 11 use Symfony\Component\DependencyInjection\ContainerInterface;
Chris@17 12
Chris@17 13 /**
Chris@17 14 * Defines a class for reacting to entity events.
Chris@17 15 *
Chris@17 16 * @internal
Chris@17 17 */
Chris@17 18 class EntityOperations implements ContainerInjectionInterface {
Chris@17 19
Chris@17 20 use StringTranslationTrait;
Chris@17 21
Chris@17 22 /**
Chris@17 23 * The entity type manager service.
Chris@17 24 *
Chris@17 25 * @var \Drupal\Core\Entity\EntityTypeManagerInterface
Chris@17 26 */
Chris@17 27 protected $entityTypeManager;
Chris@17 28
Chris@17 29 /**
Chris@17 30 * The workspace manager service.
Chris@17 31 *
Chris@17 32 * @var \Drupal\workspaces\WorkspaceManagerInterface
Chris@17 33 */
Chris@17 34 protected $workspaceManager;
Chris@17 35
Chris@17 36 /**
Chris@17 37 * Constructs a new EntityOperations instance.
Chris@17 38 *
Chris@17 39 * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
Chris@17 40 * The entity type manager service.
Chris@17 41 * @param \Drupal\workspaces\WorkspaceManagerInterface $workspace_manager
Chris@17 42 * The workspace manager service.
Chris@17 43 */
Chris@17 44 public function __construct(EntityTypeManagerInterface $entity_type_manager, WorkspaceManagerInterface $workspace_manager) {
Chris@17 45 $this->entityTypeManager = $entity_type_manager;
Chris@17 46 $this->workspaceManager = $workspace_manager;
Chris@17 47 }
Chris@17 48
Chris@17 49 /**
Chris@17 50 * {@inheritdoc}
Chris@17 51 */
Chris@17 52 public static function create(ContainerInterface $container) {
Chris@17 53 return new static(
Chris@17 54 $container->get('entity_type.manager'),
Chris@17 55 $container->get('workspaces.manager')
Chris@17 56 );
Chris@17 57 }
Chris@17 58
Chris@17 59 /**
Chris@18 60 * Acts on entity IDs before they are loaded.
Chris@17 61 *
Chris@18 62 * @see hook_entity_preload()
Chris@17 63 */
Chris@18 64 public function entityPreload(array $ids, $entity_type_id) {
Chris@18 65 $entities = [];
Chris@18 66
Chris@17 67 // Only run if the entity type can belong to a workspace and we are in a
Chris@17 68 // non-default workspace.
Chris@17 69 if (!$this->workspaceManager->shouldAlterOperations($this->entityTypeManager->getDefinition($entity_type_id))) {
Chris@18 70 return $entities;
Chris@17 71 }
Chris@17 72
Chris@17 73 // Get a list of revision IDs for entities that have a revision set for the
Chris@17 74 // current active workspace. If an entity has multiple revisions set for a
Chris@17 75 // workspace, only the one with the highest ID is returned.
Chris@17 76 $max_revision_id = 'max_target_entity_revision_id';
Chris@18 77 $query = $this->entityTypeManager
Chris@17 78 ->getStorage('workspace_association')
Chris@17 79 ->getAggregateQuery()
Chris@17 80 ->accessCheck(FALSE)
Chris@17 81 ->allRevisions()
Chris@17 82 ->aggregate('target_entity_revision_id', 'MAX', NULL, $max_revision_id)
Chris@17 83 ->groupBy('target_entity_id')
Chris@17 84 ->condition('target_entity_type_id', $entity_type_id)
Chris@18 85 ->condition('workspace', $this->workspaceManager->getActiveWorkspace()->id());
Chris@17 86
Chris@18 87 if ($ids) {
Chris@18 88 $query->condition('target_entity_id', $ids, 'IN');
Chris@17 89 }
Chris@17 90
Chris@18 91 $results = $query->execute();
Chris@18 92
Chris@17 93 if ($results) {
Chris@17 94 /** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
Chris@17 95 $storage = $this->entityTypeManager->getStorage($entity_type_id);
Chris@17 96
Chris@17 97 // Swap out every entity which has a revision set for the current active
Chris@17 98 // workspace.
Chris@17 99 $swap_revision_ids = array_column($results, $max_revision_id);
Chris@17 100 foreach ($storage->loadMultipleRevisions($swap_revision_ids) as $revision) {
Chris@17 101 $entities[$revision->id()] = $revision;
Chris@17 102 }
Chris@17 103 }
Chris@18 104
Chris@18 105 return $entities;
Chris@17 106 }
Chris@17 107
Chris@17 108 /**
Chris@17 109 * Acts on an entity before it is created or updated.
Chris@17 110 *
Chris@17 111 * @param \Drupal\Core\Entity\EntityInterface $entity
Chris@17 112 * The entity being saved.
Chris@17 113 *
Chris@17 114 * @see hook_entity_presave()
Chris@17 115 */
Chris@17 116 public function entityPresave(EntityInterface $entity) {
Chris@17 117 $entity_type = $entity->getEntityType();
Chris@17 118
Chris@17 119 // Only run if this is not an entity type provided by the Workspaces module
Chris@17 120 // and we are in a non-default workspace
Chris@17 121 if ($entity_type->getProvider() === 'workspaces' || $this->workspaceManager->getActiveWorkspace()->isDefaultWorkspace()) {
Chris@17 122 return;
Chris@17 123 }
Chris@17 124
Chris@17 125 // Disallow any change to an unsupported entity when we are not in the
Chris@17 126 // default workspace.
Chris@17 127 if (!$this->workspaceManager->isEntityTypeSupported($entity_type)) {
Chris@17 128 throw new \RuntimeException('This entity can only be saved in the default workspace.');
Chris@17 129 }
Chris@17 130
Chris@18 131 /** @var \Drupal\Core\Entity\ContentEntityInterface|\Drupal\Core\Entity\EntityPublishedInterface $entity */
Chris@18 132 if (!$entity->isNew() && !$entity->isSyncing()) {
Chris@17 133 // Force a new revision if the entity is not replicating.
Chris@17 134 $entity->setNewRevision(TRUE);
Chris@17 135
Chris@17 136 // All entities in the non-default workspace are pending revisions,
Chris@17 137 // regardless of their publishing status. This means that when creating
Chris@17 138 // a published pending revision in a non-default workspace it will also be
Chris@17 139 // a published pending revision in the default workspace, however, it will
Chris@17 140 // become the default revision only when it is replicated to the default
Chris@17 141 // workspace.
Chris@17 142 $entity->isDefaultRevision(FALSE);
Chris@17 143 }
Chris@17 144
Chris@17 145 // When a new published entity is inserted in a non-default workspace, we
Chris@17 146 // actually want two revisions to be saved:
Chris@17 147 // - An unpublished default revision in the default ('live') workspace.
Chris@17 148 // - A published pending revision in the current workspace.
Chris@17 149 if ($entity->isNew() && $entity->isPublished()) {
Chris@17 150 // Keep track of the publishing status in a dynamic property for
Chris@17 151 // ::entityInsert(), then unpublish the default revision.
Chris@17 152 // @todo Remove this dynamic property once we have an API for associating
Chris@17 153 // temporary data with an entity: https://www.drupal.org/node/2896474.
Chris@17 154 $entity->_initialPublished = TRUE;
Chris@17 155 $entity->setUnpublished();
Chris@17 156 }
Chris@17 157 }
Chris@17 158
Chris@17 159 /**
Chris@17 160 * Responds to the creation of a new entity.
Chris@17 161 *
Chris@17 162 * @param \Drupal\Core\Entity\EntityInterface $entity
Chris@17 163 * The entity that was just saved.
Chris@17 164 *
Chris@17 165 * @see hook_entity_insert()
Chris@17 166 */
Chris@17 167 public function entityInsert(EntityInterface $entity) {
Chris@17 168 /** @var \Drupal\Core\Entity\RevisionableInterface|\Drupal\Core\Entity\EntityPublishedInterface $entity */
Chris@17 169 // Only run if the entity type can belong to a workspace and we are in a
Chris@17 170 // non-default workspace.
Chris@17 171 if (!$this->workspaceManager->shouldAlterOperations($entity->getEntityType())) {
Chris@17 172 return;
Chris@17 173 }
Chris@17 174
Chris@17 175 $this->trackEntity($entity);
Chris@17 176
Chris@17 177 // When an entity is newly created in a workspace, it should be published in
Chris@17 178 // that workspace, but not yet published on the live workspace. It is first
Chris@17 179 // saved as unpublished for the default revision, then immediately a second
Chris@17 180 // revision is created which is published and attached to the workspace.
Chris@17 181 // This ensures that the published version of the entity does not 'leak'
Chris@17 182 // into the live site. This differs from edits to existing entities where
Chris@17 183 // there is already a valid default revision for the live workspace.
Chris@17 184 if (isset($entity->_initialPublished)) {
Chris@17 185 // Operate on a clone to avoid changing the entity prior to subsequent
Chris@17 186 // hook_entity_insert() implementations.
Chris@17 187 $pending_revision = clone $entity;
Chris@17 188 $pending_revision->setPublished();
Chris@17 189 $pending_revision->isDefaultRevision(FALSE);
Chris@17 190 $pending_revision->save();
Chris@17 191 }
Chris@17 192 }
Chris@17 193
Chris@17 194 /**
Chris@17 195 * Responds to updates to an entity.
Chris@17 196 *
Chris@17 197 * @param \Drupal\Core\Entity\EntityInterface $entity
Chris@17 198 * The entity that was just saved.
Chris@17 199 *
Chris@17 200 * @see hook_entity_update()
Chris@17 201 */
Chris@17 202 public function entityUpdate(EntityInterface $entity) {
Chris@17 203 // Only run if the entity type can belong to a workspace and we are in a
Chris@17 204 // non-default workspace.
Chris@17 205 if (!$this->workspaceManager->shouldAlterOperations($entity->getEntityType())) {
Chris@17 206 return;
Chris@17 207 }
Chris@17 208
Chris@17 209 // Only track new revisions.
Chris@17 210 /** @var \Drupal\Core\Entity\RevisionableInterface $entity */
Chris@17 211 if ($entity->getLoadedRevisionId() != $entity->getRevisionId()) {
Chris@17 212 $this->trackEntity($entity);
Chris@17 213 }
Chris@17 214 }
Chris@17 215
Chris@17 216 /**
Chris@17 217 * Acts on an entity before it is deleted.
Chris@17 218 *
Chris@17 219 * @param \Drupal\Core\Entity\EntityInterface $entity
Chris@17 220 * The entity being deleted.
Chris@17 221 *
Chris@17 222 * @see hook_entity_predelete()
Chris@17 223 */
Chris@17 224 public function entityPredelete(EntityInterface $entity) {
Chris@17 225 $entity_type = $entity->getEntityType();
Chris@17 226
Chris@17 227 // Only run if this is not an entity type provided by the Workspaces module
Chris@17 228 // and we are in a non-default workspace
Chris@17 229 if ($entity_type->getProvider() === 'workspaces' || $this->workspaceManager->getActiveWorkspace()->isDefaultWorkspace()) {
Chris@17 230 return;
Chris@17 231 }
Chris@17 232
Chris@17 233 // Disallow any change to an unsupported entity when we are not in the
Chris@17 234 // default workspace.
Chris@17 235 if (!$this->workspaceManager->isEntityTypeSupported($entity_type)) {
Chris@17 236 throw new \RuntimeException('This entity can only be deleted in the default workspace.');
Chris@17 237 }
Chris@17 238 }
Chris@17 239
Chris@17 240 /**
Chris@17 241 * Updates or creates a WorkspaceAssociation entity for a given entity.
Chris@17 242 *
Chris@17 243 * If the passed-in entity can belong to a workspace and already has a
Chris@17 244 * WorkspaceAssociation entity, then a new revision of this will be created with
Chris@17 245 * the new information. Otherwise, a new WorkspaceAssociation entity is created to
Chris@17 246 * store the passed-in entity's information.
Chris@17 247 *
Chris@18 248 * @param \Drupal\Core\Entity\RevisionableInterface $entity
Chris@17 249 * The entity to update or create from.
Chris@17 250 */
Chris@18 251 protected function trackEntity(RevisionableInterface $entity) {
Chris@17 252 // If the entity is not new, check if there's an existing
Chris@17 253 // WorkspaceAssociation entity for it.
Chris@17 254 $workspace_association_storage = $this->entityTypeManager->getStorage('workspace_association');
Chris@17 255 if (!$entity->isNew()) {
Chris@17 256 $workspace_associations = $workspace_association_storage->loadByProperties([
Chris@17 257 'target_entity_type_id' => $entity->getEntityTypeId(),
Chris@17 258 'target_entity_id' => $entity->id(),
Chris@17 259 ]);
Chris@17 260
Chris@17 261 /** @var \Drupal\Core\Entity\ContentEntityInterface $workspace_association */
Chris@17 262 $workspace_association = reset($workspace_associations);
Chris@17 263 }
Chris@17 264
Chris@17 265 // If there was a WorkspaceAssociation entry create a new revision,
Chris@17 266 // otherwise create a new entity with the type and ID.
Chris@17 267 if (!empty($workspace_association)) {
Chris@17 268 $workspace_association->setNewRevision(TRUE);
Chris@17 269 }
Chris@17 270 else {
Chris@17 271 $workspace_association = $workspace_association_storage->create([
Chris@17 272 'target_entity_type_id' => $entity->getEntityTypeId(),
Chris@17 273 'target_entity_id' => $entity->id(),
Chris@17 274 ]);
Chris@17 275 }
Chris@17 276
Chris@17 277 // Add the revision ID and the workspace ID.
Chris@17 278 $workspace_association->set('target_entity_revision_id', $entity->getRevisionId());
Chris@17 279 $workspace_association->set('workspace', $this->workspaceManager->getActiveWorkspace()->id());
Chris@17 280
Chris@17 281 // Save without updating the tracked content entity.
Chris@17 282 $workspace_association->save();
Chris@17 283 }
Chris@17 284
Chris@17 285 /**
Chris@17 286 * Alters entity forms to disallow concurrent editing in multiple workspaces.
Chris@17 287 *
Chris@17 288 * @param array $form
Chris@17 289 * An associative array containing the structure of the form.
Chris@17 290 * @param \Drupal\Core\Form\FormStateInterface $form_state
Chris@17 291 * The current state of the form.
Chris@17 292 * @param string $form_id
Chris@17 293 * The form ID.
Chris@17 294 *
Chris@17 295 * @see hook_form_alter()
Chris@17 296 */
Chris@17 297 public function entityFormAlter(array &$form, FormStateInterface $form_state, $form_id) {
Chris@17 298 /** @var \Drupal\Core\Entity\EntityInterface $entity */
Chris@17 299 $entity = $form_state->getFormObject()->getEntity();
Chris@17 300 if (!$this->workspaceManager->isEntityTypeSupported($entity->getEntityType())) {
Chris@17 301 return;
Chris@17 302 }
Chris@17 303
Chris@17 304 // For supported entity types, signal the fact that this form is safe to use
Chris@17 305 // in a non-default workspace.
Chris@17 306 // @see \Drupal\workspaces\FormOperations::validateForm()
Chris@17 307 $form_state->set('workspace_safe', TRUE);
Chris@17 308
Chris@17 309 // Add an entity builder to the form which marks the edited entity object as
Chris@17 310 // a pending revision. This is needed so validation constraints like
Chris@17 311 // \Drupal\path\Plugin\Validation\Constraint\PathAliasConstraintValidator
Chris@17 312 // know in advance (before hook_entity_presave()) that the new revision will
Chris@17 313 // be a pending one.
Chris@17 314 $active_workspace = $this->workspaceManager->getActiveWorkspace();
Chris@17 315 if (!$active_workspace->isDefaultWorkspace()) {
Chris@17 316 $form['#entity_builders'][] = [get_called_class(), 'entityFormEntityBuild'];
Chris@17 317 }
Chris@17 318
Chris@17 319 /** @var \Drupal\workspaces\WorkspaceAssociationStorageInterface $workspace_association_storage */
Chris@17 320 $workspace_association_storage = $this->entityTypeManager->getStorage('workspace_association');
Chris@17 321 if ($workspace_ids = $workspace_association_storage->getEntityTrackingWorkspaceIds($entity)) {
Chris@17 322 // An entity can only be edited in one workspace.
Chris@17 323 $workspace_id = reset($workspace_ids);
Chris@17 324
Chris@17 325 if ($workspace_id !== $active_workspace->id()) {
Chris@17 326 $workspace = $this->entityTypeManager->getStorage('workspace')->load($workspace_id);
Chris@17 327
Chris@17 328 $form['#markup'] = $this->t('The content is being edited in the %label workspace.', ['%label' => $workspace->label()]);
Chris@17 329 $form['#access'] = FALSE;
Chris@17 330 }
Chris@17 331 }
Chris@17 332 }
Chris@17 333
Chris@17 334 /**
Chris@17 335 * Entity builder that marks all supported entities as pending revisions.
Chris@17 336 */
Chris@17 337 public static function entityFormEntityBuild($entity_type_id, RevisionableInterface $entity, &$form, FormStateInterface &$form_state) {
Chris@17 338 // Set the non-default revision flag so that validation constraints are also
Chris@17 339 // aware that a pending revision is about to be created.
Chris@17 340 $entity->isDefaultRevision(FALSE);
Chris@17 341 }
Chris@17 342
Chris@17 343 }