You are here

class OrderAnonymize in Commerce Bulk 8

Delete terms.

Plugin annotation


@Action(
  id = "commerce_bulk_order_zanonymize",
  label = @Translation("Anonymize Orders"),
  type = "commerce_order"
)

Hierarchy

Expanded class hierarchy of OrderAnonymize

File

src/Plugin/Action/OrderAnonymize.php, line 22

Namespace

Drupal\commerce_bulk\Plugin\Action
View source
class OrderAnonymize extends ConfigurableActionBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $request = \Drupal::request();
    $storage = \Drupal::service('entity_type.manager')
      ->getStorage('commerce_order');
    if ($ids = explode('|', $request->query
      ->get('ids'))) {
      $default_fields = [
        'ip_address',
        'billing_profile',
        'shipping_profile',
        'data',
        'mail',
        'field_pakiautomaadid',
      ];
      $bundles = $fields = [];
      $orders = $storage
        ->loadMultiple($ids);
      $form_state
        ->set('orders', $orders);
      $list = '<ol>';
      foreach ($orders as $order) {
        $list .= '<li><h5>' . $order
          ->id() . '</h5></li>';
        $bundle = $order
          ->bundle();
        if (!isset($bundles[$bundle])) {
          $bundles[$bundle] = $bundle;
          foreach ($order
            ->getFieldDefinitions() as $id => $definition) {
            $fields[$id] = $definition
              ->getLabel();
          }
        }
      }
      $list .= '</ol>';
      $form['warning'] = [
        '#markup' => new TranslatableMarkup('<h1>You are about to anonymize the following orders:</h1>' . $list),
      ];
      $form['strong_warning'] = [
        '#markup' => new TranslatableMarkup('<h2 style="color:red">After this operation your life will never be the same.</h2>'),
      ];
      $form['fields'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Fields'),
        '#description' => $this
          ->t('Select fields to anonymize. Use <mark>Ctrl</mark> or <mark>Shift</mark> keys to select multiple options.'),
        '#multiple' => TRUE,
        '#options' => $fields,
        '#size' => count($fields),
        '#default_value' => $default_fields,
        '#required' => TRUE,
      ];
      $form['order_age'] = [
        '#type' => 'number',
        '#title' => $this
          ->t('Order Age'),
        '#description' => $this
          ->t('Anonymize only orders older than a number of days specified. Leave empty to anonymize all selected orders.'),
        '#min' => '1',
        '#step' => '1',
      ];
      $form['cancel'] = [
        '#type' => 'submit',
        '#value' => 'CANCEL AND BACK',
        '#weight' => 1000,
      ];

      // Remove the "Action was applied to N items" message.
      \Drupal::messenger()
        ->deleteByType('status');
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    if ($form_state
      ->getTriggeringElement()['#id'] != 'edit-cancel') {
      $orders = (array) $form_state
        ->get('orders');
      $fields = (array) $form_state
        ->getValue('fields');
      $age = (int) $form_state
        ->getValue('order_age');
      $this
        ->anonymizeEntities($orders, $fields, $age);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function anonymizeEntities(array $entities, array $fields, int $age = 0) {
    $age = $age ? $age * 24 * 60 * 60 : $age;
    $completed = \time() - $age;
    $time = current($entities) instanceof OrderInterface ? 'Completed' : 'Changed';
    foreach ($entities as $entity) {
      if ($age && $entity
        ->{'get' . $time . 'Time'}() > $completed) {
        continue;
      }
      $save = FALSE;
      foreach ($fields as $name) {
        if (!$entity
          ->hasField($name)) {
          continue;
        }
        $item = $entity
          ->get($name);
        if ($value = $item
          ->getValue()) {
          $save = TRUE;
          $this
            ->anonymizeData($value);
          $entity
            ->set($name, $value);
        }
      }
      $save && $entity
        ->save();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function anonymizeData(&$data) {
    foreach ($data as $index => &$value) {
      if ($value === NULL || is_bool($value)) {
        continue;
      }
      if (is_array($value)) {
        $this
          ->anonymizeData($value);
      }
      elseif ($index == 'target_id' || $index == 'target_revision_id') {
        $value = NULL;
      }
      elseif (is_numeric($value)) {
        $str = $value[0] != 1 ? '1' : '2';
        $value = str_pad($str, strlen($value), "0");
      }
      elseif (is_string($value)) {
        $vals = array_merge(range(65, 90), range(97, 122), range(48, 57));
        $max = count($vals) - 1;
        $str = chr(mt_rand(97, 122));
        for ($i = 1; $i < strlen($value); $i++) {
          $str .= chr($vals[mt_rand(0, $max)]);
        }
        $value = $str;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function executeMultiple(array $orders) {
    if ($orders) {
      $ids = [];
      foreach ($orders as $order) {
        $ids[] = $order
          ->id();
      }
      $url = $order
        ->toUrl();
      $query = [
        'destination' => \Drupal::request()
          ->getRequestUri(),
        'ids' => implode('|', $ids),
      ];
      $path = $url::fromUserInput('/admin/config/system/actions/configure/' . $this
        ->getPluginId(), [
        'query' => $query,
      ])
        ->toString();
      $response = new RedirectResponse($path);
      $response
        ->send();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function execute($term = NULL) {

    // Do nothing.
  }

  /**
   * {@inheritdoc}
   */
  public function access($order, AccountInterface $account = NULL, $return_as_object = FALSE) {
    $result = $order
      ->access('update', $account, TRUE);
    return $return_as_object ? $result : $result
      ->isAllowed();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigurableActionBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 1
ConfigurableActionBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ConfigurableActionBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
ConfigurableActionBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 2
ConfigurableActionBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct 6
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
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
OrderAnonymize::access public function Checks object access. Overrides ActionInterface::access
OrderAnonymize::anonymizeData public function
OrderAnonymize::anonymizeEntities public function
OrderAnonymize::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
OrderAnonymize::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableActionBase::defaultConfiguration
OrderAnonymize::execute public function Executes the plugin. Overrides ExecutableInterface::execute
OrderAnonymize::executeMultiple public function Executes the plugin for an array of objects. Overrides ActionBase::executeMultiple
OrderAnonymize::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
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.