You are here

public function WorkflowManager::entityPreSave in Forms Steps 8

Workflow info storage on hook_entity_presave().

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity that is going to be saved.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

\Drupal\Core\Entity\EntityStorageException

\Drupal\entity_embed\Exception\EntityNotFoundException

File

src/Service/WorkflowManager.php, line 131

Class

WorkflowManager
Class WorkflowManager.

Namespace

Drupal\forms_steps\Service

Code

public function entityPreSave(EntityInterface $entity) {
  if ($entity
    ->isNew()) {
    return;
  }
  $currentRoute = $this->currentRouteMatch
    ->getRouteName();
  if (preg_match('/^forms_steps\\./', $currentRoute) && strcmp($entity
    ->getEntityTypeId(), Workflow::ENTITY_TYPE) != 0) {

    /** @var \Drupal\forms_steps\Step $step */
    $step = $this->formsStepsManager
      ->getStepByRoute($currentRoute);
    if (is_null($step)) {
      throw new EntityNotFoundException($this
        ->t('Unable to find Forms Steps step entity.'));
    }

    // We check if we are currently managing the right entity and not an
    // entity reference.
    if (strcmp($step
      ->entityType(), $entity
      ->getEntityTypeId()) != 0 || strcmp($step
      ->entityBundle(), $entity
      ->bundle()) != 0) {
      return;
    }
    $instanceId = $this->currentRouteMatch
      ->getParameter('instance_id');
    $workflows = [];
    if (!empty($instanceId)) {
      try {
        $workflows = $this->entityTypeManager
          ->getStorage(Workflow::ENTITY_TYPE)
          ->loadByProperties([
          'instance_id' => $instanceId,
          'entity_type' => $entity
            ->getEntityTypeId(),
          'bundle' => $entity
            ->bundle(),
          'step' => $step
            ->id(),
          'entity_id' => $entity
            ->id(),
          'form_mode' => $step
            ->formMode(),
          'forms_steps' => $step
            ->formsSteps()
            ->id(),
        ]);
      } catch (\Exception $ex) {

        // Nothing to do.
      }
    }
    else {
      $instanceId = $this->uuidService
        ->generate();
    }
    if (empty($workflows)) {
      $workflow = $this->entityTypeManager
        ->getStorage(Workflow::ENTITY_TYPE)
        ->create([
        'instance_id' => $instanceId,
        'entity_type' => $entity
          ->getEntityTypeId(),
        'bundle' => $entity
          ->bundle(),
        'step' => $step
          ->id(),
        'entity_id' => $entity
          ->id(),
        'form_mode' => $step
          ->formMode(),
        'forms_steps' => $step
          ->formsSteps()
          ->id(),
      ]);
      $workflow
        ->save();
    }
  }
}