You are here

public function WorkflowScheduledTransition::save in Workflow 8

Saves a scheduled transition. If the transition is executed, save in history.

Overrides WorkflowTransition::save

File

src/Entity/WorkflowScheduledTransition.php, line 100

Class

WorkflowScheduledTransition
Implements a scheduled transition, as shown on Workflow form.

Namespace

Drupal\workflow\Entity

Code

public function save() {

  // If executed, save in history.
  if ($this->isExecuted) {

    // Be careful, we are not a WorkflowScheduleTransition anymore!
    // No fuzzing around, just copy the ScheduledTransition to a normal one.
    $current_sid = $this
      ->getFromSid();
    $field_name = $this
      ->getFieldName();
    $executed_transition = WorkflowTransition::create([
      $current_sid,
      'field_name' => $field_name,
    ]);
    $executed_transition
      ->setTargetEntity($this
      ->getTargetEntity());
    $executed_transition
      ->setValues($this
      ->getToSid(), $this
      ->getOwnerId(), \Drupal::time()
      ->getRequestTime(), $this
      ->getComment());
    return $executed_transition
      ->save();

    // <-- exit !!
  }
  $hid = $this
    ->id();
  if (!$hid) {

    // Insert the transition. Make sure it hasn't already been inserted.
    // @todo Allow a scheduled transition per revision.
    $entity = $this
      ->getTargetEntity();
    $found_transition = self::loadByProperties($entity
      ->getEntityTypeId(), $entity
      ->id(), [], $this
      ->getFieldName(), $this
      ->getLangcode());
    if ($found_transition) {

      // Avoid duplicate entries.
      $found_transition
        ->delete();
      $result = parent::save();
    }
    else {
      $result = parent::save();
    }
  }
  else {
    workflow_debug(__FILE__, __FUNCTION__, __LINE__);

    // @todo D8-port: still test this snippet.
    // Update the transition.
    $result = parent::save();
  }

  // Create user message.
  if ($state = $this
    ->getToState()) {
    $entity = $this
      ->getTargetEntity();
    $message = '%entity_title scheduled for state change to %state_name on %scheduled_date';
    $args = [
      '%entity_title' => $entity
        ->label(),
      '%state_name' => $state
        ->label(),
      '%scheduled_date' => $this
        ->getTimestampFormatted(),
      'link' => $this
        ->getTargetEntityId() && $this
        ->getTargetEntity()
        ->hasLinkTemplate('canonical') ? $this
        ->getTargetEntity()
        ->toLink($this
        ->t('View'))
        ->toString() : '',
    ];
    \Drupal::logger('workflow')
      ->notice($message, $args);
    $this
      ->messenger()
      ->addStatus($this
      ->t($message, $args));
  }
  return $result;
}