Coverage index

src/Form/UpgradeForm.php

Lines: 100.00%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Form;
6
7
use Drupal\Core\Form\ConfirmFormBase;
8
use Drupal\Core\Form\FormStateInterface;
9
use Drupal\Core\StringTranslation\TranslatableMarkup;
10
use Drupal\Core\Url;
11
12
/**
13
 * Upgrade form.
14
 *
15
 * From 8.x-2.x to 3.0.x.
16
 */
17
final class UpgradeForm extends ConfirmFormBase {
18
19
  /**
20
   * {@inheritdoc}
21
   */
22
  public function getFormId(): string {
231
    return 'visitors_upgrade';
24
  }
25
26
  /**
27
   * {@inheritdoc}
28
   */
29
  public function getQuestion(): TranslatableMarkup {
301
    return $this->t('Migrate Visitors 8.x-2.x to 3.0.x');
31
  }
32
33
  /**
34
   * {@inheritdoc}
35
   */
36
  public function getDescription(): TranslatableMarkup {
371
    return $this->t('This action will upgrade the data.');
38
  }
39
40
  /**
41
   * {@inheritdoc}
42
   */
43
  public function getCancelUrl(): Url {
441
    return new Url('visitors.settings');
45
  }
46
47
  /**
48
   * {@inheritdoc}
49
   */
50
  public function submitForm(array &$form, FormStateInterface $form_state) {
51
52
    $operations = [
53
      [['\Drupal\visitors\Form\UpgradeForm', 'upgrade'], []],
54
    ];
551
    $batch = [
561
      'title' => $this->t('Upgrading data'),
571
      'operations' => $operations,
581
      'finished' => '\Drupal\visitors\Form\UpgradeForm::finished',
591
    ];
601
    if (function_exists('batch_set')) {
611
      \batch_set($batch);
62
    }
63
641
    return 1;
65
  }
66
67
  /**
68
   * Batch method for upgrading.
69
   *
70
   * @param array $context
71
   *   The batch context.
72
   */
73
  public static function upgrade(&$context) {
74
752
    $service = \Drupal::service('visitors.upgrade');
762
    if (!isset($context['sandbox']['max'])) {
771
      $context['sandbox']['max'] = $service->getTotal();
781
      $context['sandbox']['current'] = 0;
791
      $context['finished'] = ($context['sandbox']['max'] == $context['sandbox']['current']) ? 1 : $context['sandbox']['current'] / $context['sandbox']['max'];
80
811
      return;
82
    }
83
841
    $batch_size = 50;
851
    $rows = $service->getVisitorsRows($batch_size);
86
871
    foreach ($rows as $row) {
881
      $service->upgradeRow((array) $row);
891
      $context['sandbox']['current'] += 1;
90
    }
91
921
    $context['finished'] = ($context['sandbox']['max'] == $context['sandbox']['current']) ? 1 : $context['sandbox']['current'] / $context['sandbox']['max'];
93
  }
94
95
}