You are here

UpdateTerms.php in Termcase 8

Namespace

Drupal\termcase

File

src/UpdateTerms.php
View source
<?php

namespace Drupal\termcase;


/**
 * Class, which contains the callbacks of a batch process.
 */
class UpdateTerms {

  /**
   * Batch process callback.
   *
   * @param array $terms
   *   The terms to update.
   * @param int $case
   *   The case to convert the terms to.
   * @param array $context
   *   Sandbox context.
   */
  public static function updateAllTerms(array $terms, $case, array &$context) {
    if (!isset($context['sandbox']['progress'])) {
      $context['sandbox']['progress'] = 0;
      $context['sandbox']['current_term'] = 0;
      $context['sandbox']['max'] = count($terms);
    }

    // Process 5 terms at a time.
    $limit = 5;
    $terms = array_slice($terms, $context['sandbox']['progress'], $limit);
    foreach ($terms as $term) {
      $converted_term = _termcase_convert_string_to_case($term->name, $case);
      termcase_update_term($converted_term, $term->tid, $term->vid);

      // Store some result for post-processing in the finished callback.
      $context['results'][] = $term->name;

      // Update our progress information.
      $context['sandbox']['progress']++;
      $context['sandbox']['current_term'] = $term->tid;
      $context['message'] = t('Now processing %term', [
        '%term' => $term->name,
      ]);
    }

    // Inform the batch engine that we are not finished,
    // and provide an estimation of the completion level we reached.
    if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
      $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
    }
  }

  /**
   * Callback function to format number of results or error message.
   */
  public static function updateAllTermsFinishedCallback($success, $results, $operations) {

    // The 'success' parameter means no fatal PHP errors were detected. All
    // other error management should be handled using 'results'.
    if ($success) {
      $message = \Drupal::translation()
        ->formatPlural(count($results), 'One post processed.', '@count posts processed.');
    }
    else {
      $message = t('Finished with an error.');
    }
    \Drupal::messenger()
      ->addMessage($message);
  }

}

Classes

Namesort descending Description
UpdateTerms Class, which contains the callbacks of a batch process.