annotate core/modules/workspaces/src/EntityOperations.php @ 17:129ea1e6d783

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