You are here

public static function BrightcoveUtil::runQueue in Brightcove Video Connect 8

Same name and namespace in other branches
  1. 8.2 src/BrightcoveUtil.php \Drupal\brightcove\BrightcoveUtil::runQueue()
  2. 3.x src/BrightcoveUtil.php \Drupal\brightcove\BrightcoveUtil::runQueue()

Runs a queue.

Parameters

string $queue: The queue name to clear.

mixed &$context: The Batch API context.

File

src/BrightcoveUtil.php, line 327

Class

BrightcoveUtil
Utility class for Brightcove.

Namespace

Drupal\brightcove

Code

public static function runQueue($queue, &$context) {

  // This is a static function called by Batch API, so it's not possible to
  // use dependency injection here.

  /* @var \Drupal\Core\Queue\QueueWorkerInterface $queue_worker */
  $queue_worker = \Drupal::getContainer()
    ->get('plugin.manager.queue_worker')
    ->createInstance($queue);
  $queue = \Drupal::queue($queue);

  // Let's process ALL the items in the queue, 5 by 5, to avoid PHP timeouts.
  // If there's any problem with processing any of those 5 items, stop sooner.
  $limit = 5;
  $handled_all = TRUE;
  while ($limit > 0 && ($item = $queue
    ->claimItem(5))) {
    try {
      $queue_worker
        ->processItem($item->data);
      $queue
        ->deleteItem($item);
    } catch (SuspendQueueException $e) {
      $queue
        ->releaseItem($item);
      $handled_all = FALSE;
      break;
    } catch (APIException $e) {
      if ($e
        ->getCode() == 401) {
        $queue
          ->deleteItem($item);
        $handled_all = TRUE;
      }
      else {
        watchdog_exception('brightcove', $e);
        \Drupal::logger('brightcove')
          ->error($e
          ->getMessage());
        $handled_all = FALSE;
      }
    } catch (\Exception $e) {
      watchdog_exception('brightcove', $e);
      \Drupal::logger('brightcove')
        ->error($e
        ->getMessage());
      $handled_all = FALSE;
    }
    $limit--;
  }

  // As this batch may be run synchronously with the queue's cron processor,
  // we can't be sure about the number of items left for the batch as long as
  // there is any. So let's just inform the user about the number of remaining
  // items, as we don't really care if they are processed by this batch
  // processor or the cron one.
  $remaining = $queue
    ->numberOfItems();
  $context['message'] = t('@count item(s) left in current queue', [
    '@count' => $remaining,
  ]);
  $context['finished'] = $handled_all && $remaining == 0;
}