You are here

public function JobCheckoutManager::checkoutAndRedirect in Translation Management Tool 8

Attempts to checkout a number of jobs and prepare the necessary redirects.

Parameters

\Drupal\Core\Form\FormStateInterface $form_state: Form state array, used to set the initial redirect.

\Drupal\tmgmt\JobInterface[] $jobs: Array of jobs to attempt checkout

Related topics

File

src/JobCheckoutManager.php, line 68

Class

JobCheckoutManager
Provides functionality related to job checkout and submissions.

Namespace

Drupal\tmgmt

Code

public function checkoutAndRedirect(FormStateInterface $form_state, array $jobs) {
  $checkout_jobs = $this
    ->checkoutMultiple($jobs);
  $jobs_ready_for_checkout = array_udiff($jobs, $checkout_jobs, function (JobInterface $a, JobInterface $b) {
    if ($a
      ->id() < $b
      ->id()) {
      return -1;
    }
    elseif ($a
      ->id() > $b
      ->id()) {
      return 1;
    }
    else {
      return 0;
    }
  });

  // If necessary, do a redirect.
  if ($checkout_jobs || $jobs_ready_for_checkout) {
    $request = $this->requestStack
      ->getCurrentRequest();
    if ($request->query
      ->has('destination')) {

      // Remove existing destination, as that will prevent us from being
      // redirect to the job checkout page. Set the destination as the final
      // redirect instead.
      $redirect = $request->query
        ->get('destination');
      $request->query
        ->remove('destination');
    }
    else {
      $redirect = Url::fromRoute('<current>')
        ->getInternalPath();
    }
    $this->jobQueue
      ->startQueue(array_merge($checkout_jobs, $jobs_ready_for_checkout), $redirect);

    // Prepare a batch job for the jobs that can be submitted already.
    if ($jobs_ready_for_checkout) {
      $batch = array(
        'title' => t('Submitting jobs'),
        'operations' => [],
        'finished' => [
          JobCheckoutManager::class,
          'batchSubmitFinished',
        ],
      );
      foreach ($jobs_ready_for_checkout as $job) {
        $batch['operations'][] = [
          [
            JobCheckoutManager::class,
            'batchSubmit',
          ],
          [
            $job
              ->id(),
            NULL,
          ],
        ];
      }
      batch_set($batch);
    }
    else {
      $form_state
        ->setRedirectUrl($this->jobQueue
        ->getNextUrl());
    }

    // Count of the job messages is one less due to the final redirect.
    $this
      ->messenger()
      ->addStatus($this
      ->getStringTranslation()
      ->formatPlural(count($checkout_jobs), t('One job needs to be checked out.'), t('@count jobs need to be checked out.')));
  }
}