BatchStorage.php

Same filename in this branch
  1. main core/lib/Drupal/Core/ProxyClass/Batch/BatchStorage.php
Same filename and directory in other branches
  1. 11.x core/lib/Drupal/Core/ProxyClass/Batch/BatchStorage.php
  2. 11.x core/lib/Drupal/Core/Batch/BatchStorage.php
  3. 10 core/lib/Drupal/Core/ProxyClass/Batch/BatchStorage.php
  4. 10 core/lib/Drupal/Core/Batch/BatchStorage.php
  5. 9 core/lib/Drupal/Core/ProxyClass/Batch/BatchStorage.php
  6. 9 core/lib/Drupal/Core/Batch/BatchStorage.php
  7. 8.9.x core/lib/Drupal/Core/ProxyClass/Batch/BatchStorage.php
  8. 8.9.x core/lib/Drupal/Core/Batch/BatchStorage.php

Namespace

Drupal\Core\Batch

File

core/lib/Drupal/Core/Batch/BatchStorage.php

View source
<?php

namespace Drupal\Core\Batch;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Access\CsrfTokenGenerator;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\DatabaseException;
use Drupal\Core\Database\SchemaDefinition\Column;
use Drupal\Core\Database\SchemaDefinition\ColumnSize;
use Drupal\Core\Database\SchemaDefinition\Index;
use Drupal\Core\Database\SchemaDefinition\PrimaryKey;
use Drupal\Core\Database\SchemaDefinition\Schema;
use Drupal\Core\Database\SchemaDefinition\SchemaDefinitionType;
use Drupal\Core\Database\SchemaDefinition\Table;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

/**
 * Defines the storage handler class for batches.
 */
class BatchStorage implements BatchStorageInterface {
  
  /**
   * The table name.
   */
  const TABLE_NAME = 'batch';
  
  /**
   * Constructs the database batch storage service.
   *
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
   * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
   *   The session.
   * @param \Drupal\Core\Access\CsrfTokenGenerator $csrfToken
   *   The CSRF token generator.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   */
  public function __construct(protected Connection $connection, protected SessionInterface $session, protected CsrfTokenGenerator $csrfToken, protected TimeInterface $time) {
  }
  
  /**
   * {@inheritdoc}
   */
  public function load($id) {
    // Ensure that a session is started before using the CSRF token generator.
    $this->session
      ->start();
    try {
      $batch = $this->connection
        ->select('batch', 'b')
        ->fields('b', [
        'batch',
      ])
        ->condition('bid', $id)
        ->condition('token', $this->csrfToken
        ->get($id))
        ->execute()
        ->fetchField();
    } catch (\Exception $e) {
      $this->catchException($e);
      $batch = FALSE;
    }
    if ($batch) {
      return unserialize($batch);
    }
    return FALSE;
  }
  
  /**
   * {@inheritdoc}
   */
  public function delete($id) {
    try {
      $this->connection
        ->delete('batch')
        ->condition('bid', $id)
        ->execute();
    } catch (\Exception $e) {
      $this->catchException($e);
    }
  }
  
  /**
   * {@inheritdoc}
   */
  public function update(array $batch) {
    try {
      $this->connection
        ->update('batch')
        ->fields([
        'batch' => serialize($batch),
      ])
        ->condition('bid', $batch['id'])
        ->execute();
    } catch (\Exception $e) {
      $this->catchException($e);
    }
  }
  
  /**
   * {@inheritdoc}
   */
  public function cleanup() {
    try {
      // Cleanup the batch table and the queue for failed batches.
      $this->connection
        ->delete('batch')
        ->condition('timestamp', $this->time
        ->getRequestTime() - 864000, '<')
        ->execute();
    } catch (\Exception $e) {
      $this->catchException($e);
    }
  }
  
  /**
   * {@inheritdoc}
   */
  public function create(array $batch) {
    // Ensure that a session is started before using the CSRF token generator,
    // and update the database record.
    $this->session
      ->start();
    $this->connection
      ->update('batch')
      ->fields([
      'token' => $this->csrfToken
        ->get($batch['id']),
      'batch' => serialize($batch),
    ])
      ->condition('bid', $batch['id'])
      ->execute();
  }
  
  /**
   * {@inheritdoc}
   */
  public function getId() : int {
    $try_again = FALSE;
    try {
      // The batch table might not yet exist.
      return $this->doInsertBatchRecord();
    } catch (\Exception $e) {
      // If there was an exception, try to create the table.
      if (!$try_again = $this->ensureTableExists()) {
        // If the exception happened for other reason than the missing table,
        // propagate the exception.
        throw $e;
      }
    }
    // Now that the table has been created, try again if necessary.
    if ($try_again) {
      return $this->doInsertBatchRecord();
    }
  }
  
  /**
   * Inserts a record in the table and returns the batch id.
   *
   * @return int
   *   A batch id.
   */
  protected function doInsertBatchRecord() : int {
    return $this->connection
      ->insert('batch')
      ->fields([
      'timestamp' => $this->time
        ->getRequestTime(),
      'token' => '',
      'batch' => NULL,
    ])
      ->execute();
  }
  
  /**
   * Check if the table exists and create it if not.
   */
  protected function ensureTableExists() {
    try {
      $this->connection
        ->schema()
        ->createSchemaFromDefinition($this->schemaDefinition());
    } catch (DatabaseException) {
    } catch (\Exception) {
      return FALSE;
    }
    return TRUE;
  }
  
  /**
   * Act on an exception when batch might be stale.
   *
   * If the table does not yet exist, that's fine, but if the table exists and
   * yet the query failed, then the batch is stale and the exception needs to
   * propagate.
   *
   * @param \Exception $e
   *   The exception.
   *
   * @throws \Exception
   */
  protected function catchException(\Exception $e) {
    if ($this->connection
      ->schema()
      ->tableExists(static::TABLE_NAME)) {
      throw $e;
    }
  }
  
  /**
   * Defines the schema for the batch table.
   *
   * @internal
   */
  public function schemaDefinition() : Schema {
    $tables[] = new Table(name: static::TABLE_NAME, description: 'Stores details about batches (processes that run in multiple HTTP requests).', columns: [
      Column::serial(name: 'bid', description: 'Primary Key: Unique batch ID.'),
      Column::varcharAscii(name: 'token', description: "A string token generated against the current user's session id and the batch id, used to ensure that only the user who submitted the batch can effectively access it.", length: 64, notNull: TRUE),
      Column::int(name: 'timestamp', description: 'A Unix timestamp indicating when this batch was submitted for processing. Stale batches are purged at cron time.', notNull: TRUE),
      Column::blob(name: 'batch', description: 'A serialized array containing the processing data for the batch.', size: ColumnSize::Big, notNull: FALSE),
    ], primaryKey: new PrimaryKey([
      'bid',
    ]), indexes: [
      new Index(name: 'token', columns: [
        'token',
      ]),
    ]);
    return new Schema(type: SchemaDefinitionType::Storage, name: 'batch', tables: $tables);
  }

}

Classes

Title Deprecated Summary
BatchStorage Defines the storage handler class for batches.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.