You are here

function conflict_entity_load in Conflict 8.2

Implements hook_entity_load().

Attaches a clone of the loaded entity to the currently loaded entity, which will be used if any conflicts are detected on an entity form submission in order to determine the changes made by the user in case the entity has been saved meanwhile.

File

./conflict.module, line 61
The module that makes concurrent editing possible.

Code

function conflict_entity_load(array $entities, $entity_type_id) {

  // @todo decide whether this is the right place for storing a clone of the
  // loaded entity. Another possible place would be the form state for the main
  // entity and the field state for inline entities. The problem with the
  // current solution is that even entities loaded e.g. for a non inline entity
  // form widget will be cloned.
  $route = \Drupal::routeMatch()
    ->getRouteObject();

  // The route object will not be present if the entity is being loaded before
  // the routing has completed. This happens e.g. in
  // Drupal\Core\ParamConverter\EntityConverter::convert(), therefore we have
  // to check if the route object is not present that we are still in the
  // browser. This is not a perfect solution as there will be cases where we
  // will clone unnecessary the entity, but currently the most simple solution.
  if (is_null($route) && php_sapi_name() != 'cli' || $route && ($route_defaults = $route
    ->getDefaults()) && isset($route_defaults['_entity_form'])) {
    foreach ($entities as $entity) {
      if ($entity instanceof ContentEntityInterface) {
        $clone = clone $entity;
        $entity->{EntityConflictHandlerInterface::CONFLICT_ENTITY_ORIGINAL} = $clone;
        $serialized = serialize($clone);
        $hash = $entity_type_id . '_' . $entity
          ->id() . sha1($serialized);
        $entity->{EntityConflictHandlerInterface::CONFLICT_ENTITY_ORIGINAL_HASH} = $hash;
        \Drupal::keyValueExpirable('conflict_original_entity')
          ->setWithExpireIfNotExists($hash, $serialized, 86400);
      }
    }
  }
}