You are here

class OrderReportGenerateForm in Commerce Reporting 8

Profides a form for bulk generating order reports.

Hierarchy

Expanded class hierarchy of OrderReportGenerateForm

1 string reference to 'OrderReportGenerateForm'
commerce_reports.routing.yml in ./commerce_reports.routing.yml
commerce_reports.routing.yml

File

src/Form/OrderReportGenerateForm.php, line 14

Namespace

Drupal\commerce_reports\Form
View source
class OrderReportGenerateForm extends FormBase {

  /**
   * The number of orders to process in each batch.
   *
   * @var int
   */
  const BATCH_SIZE = 25;

  /**
   * The report type manager.
   *
   * @var \Drupal\commerce_reports\ReportTypeManager
   */
  protected $reportTypeManager;

  /**
   * Constructs a new OrderReportGenerateForm object.
   *
   * @param \Drupal\commerce_reports\ReportTypeManager $report_type_manager
   *   The order report type manager.
   */
  public function __construct(ReportTypeManager $report_type_manager) {
    $this->reportTypeManager = $report_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.commerce_report_type'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'commerce_reports_generate_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $plugin_types = $this->reportTypeManager
      ->getDefinitions();
    $plugin_options = [];
    foreach ($plugin_types as $plugin_id => $plugin_definition) {
      $plugin_options[$plugin_id] = $plugin_definition['label'];
    }
    asort($plugin_options);
    $form['plugin_id'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Report types'),
      '#description' => $this
        ->t('Select all report types or a single report type to be generated.'),
      '#empty_option' => $this
        ->t('All Reports'),
      '#empty_value' => '',
      '#options' => $plugin_options,
    ];
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Generate'),
      '#button_type' => 'primary',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $plugin_id = $values['plugin_id'];
    $batch = [
      'title' => $this
        ->t('Generating reports'),
      'progress_message' => '',
      'operations' => [
        [
          [
            get_class($this),
            'processBatch',
          ],
          [
            $plugin_id,
          ],
        ],
      ],
      'finished' => [
        $this,
        'finishBatch',
      ],
    ];
    batch_set($batch);
    $form_state
      ->setRedirect('commerce.configuration');
  }

  /**
   * Processes the batch and generates the order reports.
   *
   * @param array $context
   *   The batch context information.
   */
  public static function processBatch($plugin_id, array &$context) {
    $order_storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_order');

    // Initialization.
    if (empty($context['sandbox'])) {
      $context['results']['total_generated'] = 0;

      // Determine maximum id for a non-draft order.
      $order_ids = $order_storage
        ->getQuery()
        ->condition('state', 'draft', '<>')
        ->sort('order_id', 'DESC')
        ->range(0, 1)
        ->execute();

      // No orders to process.
      if (empty($order_ids)) {
        $context['finished'] = 1;
        return;
      }
      $context['sandbox']['maximum_id'] = reset($order_ids);
      $context['sandbox']['current_offset'] = 0;
    }
    $maximum_id = $context['sandbox']['maximum_id'];
    $current_offset =& $context['sandbox']['current_offset'];
    $max_remaining = $maximum_id - $current_offset;
    if ($max_remaining < 1) {
      $context['finished'] = 1;
      return;
    }
    $limit = $max_remaining < self::BATCH_SIZE ? $max_remaining : self::BATCH_SIZE;

    // Get a batch of orders to be processed.
    $batch_orders_ids = $order_storage
      ->getQuery()
      ->sort('order_id')
      ->range($current_offset, $limit)
      ->execute();

    // Generate order reports for the batch (after deleting any existing reports).
    $order_report_generator = \Drupal::service('commerce_reports.order_report_generator');
    $generated = $order_report_generator
      ->refreshReports($batch_orders_ids, $plugin_id);
    $current_offset += $limit;
    $context['results']['total_generated'] += $generated;

    // Finished when order with maximum id has been processed in the batch.
    $batch_maximum_id = end($batch_orders_ids);
    if ($batch_maximum_id >= $maximum_id) {
      $context['finished'] = 1;
      return;
    }
    $context['message'] = t('Generated reports for @created orders of @total_quantity.', [
      '@created' => $batch_maximum_id,
      '@total_quantity' => $maximum_id,
    ]);
    $context['finished'] = $batch_maximum_id / $maximum_id;
  }

  /**
   * Batch finished callback: display batch statistics.
   *
   * @param bool $success
   *   Indicates whether the batch has completed successfully.
   * @param mixed[] $results
   *   The array of results gathered by the batch processing.
   * @param string[] $operations
   *   If $success is FALSE, contains the operations that remained unprocessed.
   */
  public static function finishBatch($success, array $results, array $operations) {
    if ($success) {
      \Drupal::messenger()
        ->addMessage(\Drupal::translation()
        ->formatPlural($results['total_generated'], 'Generated reports for 1 order.', 'Generated reports for @count orders.'));
    }
    else {
      $error_operation = reset($operations);
      \Drupal::messenger()
        ->addError(t('An error occurred while processing @operation with arguments: @args', [
        '@operation' => $error_operation[0],
        '@args' => print_r($error_operation[0], TRUE),
      ]));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
OrderReportGenerateForm::$reportTypeManager protected property The report type manager.
OrderReportGenerateForm::BATCH_SIZE constant The number of orders to process in each batch.
OrderReportGenerateForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
OrderReportGenerateForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
OrderReportGenerateForm::finishBatch public static function Batch finished callback: display batch statistics.
OrderReportGenerateForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
OrderReportGenerateForm::processBatch public static function Processes the batch and generates the order reports.
OrderReportGenerateForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
OrderReportGenerateForm::__construct public function Constructs a new OrderReportGenerateForm object.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.