You are here

public function SequentialNumberPatternBase::getNextSequence in Commerce Core 8.2

Gets the next sequence for the given entity.

Parameters

\Drupal\Core\Entity\ContentEntityInterface $entity: The entity.

Return value

\Drupal\commerce_number_pattern\Sequence The next sequence.

Overrides SequentialNumberPatternInterface::getNextSequence

1 call to SequentialNumberPatternBase::getNextSequence()
SequentialNumberPatternBase::generate in modules/number_pattern/src/Plugin/Commerce/NumberPattern/SequentialNumberPatternBase.php
Generates a number for the given content entity.

File

modules/number_pattern/src/Plugin/Commerce/NumberPattern/SequentialNumberPatternBase.php, line 233

Class

SequentialNumberPatternBase
Provides a base class for number pattern plugins which support sequences.

Namespace

Drupal\commerce_number_pattern\Plugin\Commerce\NumberPattern

Code

public function getNextSequence(ContentEntityInterface $entity) {
  $transaction = $this->connection
    ->startTransaction();
  try {
    $store_id = $this
      ->getStoreId($entity);

    // Get the current sequence with FOR UPDATE to ensure we acquire a row
    // level lock. If a competing process for a different order attempts to
    // get the current sequence while we're in this function, it will block
    // in the getCurrentSequence query execute until our transaction
    // completes.
    $current_sequence = $this
      ->getCurrentSequence($entity);
    if (!$current_sequence || $this
      ->shouldReset($current_sequence)) {
      $sequence = $this
        ->getInitialSequence($entity);
    }
    else {
      $sequence = new Sequence([
        'number' => $current_sequence
          ->getNumber() + 1,
        'generated' => $this->time
          ->getRequestTime(),
        'store_id' => $store_id,
      ]);
    }
    $this->connection
      ->merge('commerce_number_pattern_sequence')
      ->fields([
      'entity_id' => $this->parentEntity
        ->id(),
      'store_id' => $store_id,
      'number' => $sequence
        ->getNumber(),
      'generated' => $sequence
        ->getGeneratedTime(),
    ])
      ->keys([
      'entity_id' => $this->parentEntity
        ->id(),
      'store_id' => $store_id,
    ])
      ->execute();
  } catch (\Exception $e) {
    $transaction
      ->rollBack();
    throw $e;
  }

  // Commit the transaction to complete the update and allow any blocked
  // competing process to continue safely.
  unset($transaction);
  return $sequence;
}