You are here

public function SerialSQLStorage::generateValueFromName in Serial Field 8

Generates a unique serial value (unique per entity bundle).

Parameters

string $storageName: Storage name.

bool $delete: Indicates if temporary records should be deleted.

Return value

int Unique serial id.

Overrides SerialStorageInterface::generateValueFromName

2 calls to SerialSQLStorage::generateValueFromName()
SerialSQLStorage::generateValue in src/SerialSQLStorage.php
Generates a unique serial value (unique per entity bundle).
SerialSQLStorage::initOldEntries in src/SerialSQLStorage.php
Initializes the value of a new serial field in existing entities.

File

src/SerialSQLStorage.php, line 69

Class

SerialSQLStorage
Serial storage service definition.

Namespace

Drupal\serial

Code

public function generateValueFromName($storageName, $delete = TRUE) {
  $connection = Database::getConnection();

  // @todo review https://api.drupal.org/api/drupal/core%21includes%21database.inc/function/db_transaction/8.2.x
  $transaction = $connection
    ->startTransaction();
  try {

    // Insert a temporary record to get a new unique serial value.
    $uniqid = uniqid('', TRUE);
    $sid = $connection
      ->insert($storageName)
      ->fields([
      'uniqid' => $uniqid,
    ])
      ->execute();

    // If there's a reason why it's come back undefined, reset it.
    $sid = isset($sid) ? $sid : 0;

    // Delete the temporary record.
    if ($delete && $sid && $sid % 10 == 0) {
      $connection
        ->delete($storageName)
        ->condition('sid', $sid, '<')
        ->execute();
    }

    // Return the new unique serial value.
    return $sid;
  } catch (\Exception $e) {
    $transaction
      ->rollback();
    watchdog_exception('serial', $e);
    throw $e;
  }
}