rdf_sync-1.x-dev/src/BatchSynchronizer.php

src/BatchSynchronizer.php
<?php

declare(strict_types=1);

namespace Drupal\rdf_sync;

use Drupal\Core\Batch\BatchBuilder;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\rdf_sync\Model\SyncMethod;

/**
 * Batch synchronizer.
 */
class BatchSynchronizer {

  public function __construct(
    protected RdfSyncSynchronizer $synchronizer,
    protected EntityTypeManagerInterface $entityTypeManager,
  ) {}

  /**
   * Initiates the batch process.
   *
   * @param string $entityTypeId
   *   Entity type id.
   * @param array $bundles
   *   List of bundles.
   */
  public function initBatch(string $entityTypeId, array $bundles): void {
    $entityType = $this->entityTypeManager->getDefinition($entityTypeId);

    $query = $this->entityTypeManager->getStorage($entityTypeId)
      ->getQuery()
      ->accessCheck(FALSE);

    if ($entityType->hasKey('bundle')) {
      $bundleKey = $entityType->getKey('bundle');
      $query->condition($bundleKey, $bundles, 'IN');
    }

    $ids = array_values($query->execute());

    $batchBuilder = (new BatchBuilder())->addOperation([
      static::class,
      'init',
    ], [count($ids)]);
    foreach (array_chunk($ids, 5) as $queuedIds) {
      $batchBuilder->addOperation([
        static::class,
        'synchronizeBatch',
      ], [$entityTypeId, $queuedIds]);
    }
    batch_set($batchBuilder->toArray());
  }

  /**
   * Initiates the batch process.
   *
   * @param int $total
   *   Total number of entities to be synchronized.
   * @param array $context
   *   The batch process context.
   */
  public static function init(int $total, array &$context): void {
    $context['results']['total'] = $total;
    $context['results']['progress'] = 0;
  }

  /**
   * Synchronizes one batch.
   *
   * @param string $entityTypeId
   *   The entity type ID of the entities being synchronized.
   * @param int[]|string[] $ids
   *   A list of entity IDs.
   * @param array $context
   *   The batch process context.
   */
  public static function synchronizeBatch(string $entityTypeId, array $ids, array &$context): void {
    $synchronizer = \Drupal::getContainer()->get('rdf_sync.synchronizer');
    $storage = \Drupal::entityTypeManager()->getStorage($entityTypeId);

    /** @var \Drupal\Core\Entity\ContentEntityInterface[] $entities */
    $entities = $storage->loadMultiple($ids);
    $synchronizer->synchronize(SyncMethod::UPDATE, $entities, TRUE);
    $synchronizer->destruct();

    $context['results']['progress'] += count($entities);
    $context['message'] = "Synchronized {$context['results']['progress']} out of {$context['results']['total']} entities";
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc