You are here

class OrderItemDiscountAdjustment in Commerce Migrate 3.0.x

Same name and namespace in other branches
  1. 8.2 modules/commerce/src/Plugin/migrate/process/commerce1/OrderItemDiscountAdjustment.php \Drupal\commerce_migrate_commerce\Plugin\migrate\process\commerce1\OrderItemDiscountAdjustment
  2. 3.1.x modules/commerce/src/Plugin/migrate/process/commerce1/OrderItemDiscountAdjustment.php \Drupal\commerce_migrate_commerce\Plugin\migrate\process\commerce1\OrderItemDiscountAdjustment

Builds an array of adjustment data.

Plugin annotation


@MigrateProcessPlugin(
  id = "commerce1_order_item_discount_adjustment"
)

Hierarchy

Expanded class hierarchy of OrderItemDiscountAdjustment

1 file declares its use of OrderItemDiscountAdjustment
OrderItemDiscountAdjustmentTest.php in modules/commerce/tests/src/Unit/Plugin/migrate/process/commerce1/OrderItemDiscountAdjustmentTest.php

File

modules/commerce/src/Plugin/migrate/process/commerce1/OrderItemDiscountAdjustment.php, line 23

Namespace

Drupal\commerce_migrate_commerce\Plugin\migrate\process\commerce1
View source
class OrderItemDiscountAdjustment extends CommercePrice implements ContainerFactoryPluginInterface {

  /**
   * The migration plugin manager.
   *
   * @var \Drupal\migrate\Plugin\MigrationPluginManagerInterface
   */
  protected $migrationPluginManager;

  /**
   * The migration to be executed.
   *
   * @var \Drupal\migrate\Plugin\MigrationInterface
   */
  protected $migration;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The rounder.
   *
   * @var \Drupal\commerce_price\RounderInterface
   */
  protected $rounder;

  /**
   * The number.
   *
   * @var string
   */
  protected $number;

  /**
   * The currency code.
   *
   * @var string
   */
  protected $currencyCode;

  /**
   * Constructs a MigrationLookup object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
   *   The Migration the plugin is being used in.
   * @param \Drupal\migrate\Plugin\MigrationPluginManagerInterface $migration_plugin_manager
   *   The Migration Plugin Manager Interface.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\commerce_price\RounderInterface $rounder
   *   The rounder.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, MigrationPluginManagerInterface $migration_plugin_manager, EntityTypeManagerInterface $entity_type_manager, RounderInterface $rounder) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->migrationPluginManager = $migration_plugin_manager;
    $this->migration = $migration;
    $this->entityTypeManager = $entity_type_manager;
    $this->rounder = $rounder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return new static($configuration, $plugin_id, $plugin_definition, $migration, $container
      ->get('plugin.manager.migration'), $container
      ->get('entity_type.manager'), $container
      ->get('commerce_price.rounder'));
  }

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $adjustment = [];

    // Find all price components on the order, not the line item, that are not
    // a shipping type and not also in the line item price components.
    $order_components = $row
      ->getSourceProperty('order_components/0/data/components');
    $order_names = [];
    foreach ($order_components as $order_component) {
      $order_names[] = $order_component['name'];
    }
    $shipping = $row
      ->getSourceProperty('shipping');
    $not_shipping = [];
    if (!empty($order_names)) {
      $shipping_names = [];
      foreach ($shipping as $shipping_item) {
        $data = unserialize($shipping_item['data']);
        $shipping_names[] = $data['shipping_service']['price_component'];
      }
      $not_shipping = array_diff($order_names, $shipping_names);
    }
    if (!empty($not_shipping)) {
      foreach ($not_shipping as $item) {
        if ($value['name'] === $item) {
          $adjustment = $this
            ->getAdjustment($value, $migrate_executable, $row);
        }
      }
    }
    return $adjustment;
  }

  /**
   * Get the adjustments on this order item.
   *
   * @param mixed $value
   *   The value to be transformed.
   * @param \Drupal\migrate\MigrateExecutableInterface $migrate_executable
   *   The migration in which this process is being executed.
   * @param \Drupal\migrate\Row $row
   *   The row from the source to process. Normally, just transforming the value
   *   is adequate but very rarely you might need to change two columns at the
   *   same time or something like that.
   *
   * @return array
   *   An array of adjustment data.
   *
   * @throws \Drupal\migrate\MigrateSkipRowException
   */
  protected function getAdjustment($value, MigrateExecutableInterface $migrate_executable, Row $row) {
    $adjustment = [];
    if (is_array($value)) {
      if ($value['name'] !== 'base_price') {
        $parts = explode('|', $value['name'], -1);
        if (!empty($parts)) {
          $percentage = NULL;
          $type = '';
          $label = '';
          $amount = (string) $value['price']['amount'];
          $currency_code = $value['price']['currency_code'];
          if ($parts[0] === 'tax') {
            $type = 'tax';
            $tax_rate = $value['price']['data']['tax_rate'];
            $label = $tax_rate['display_title'];
            $percentage = $tax_rate['rate'];
          }
          if ($parts[0] === 'discount') {
            $type = 'promotion';
            $label = $value['price']['data']['discount_component_title'];
          }
          if (empty($type)) {
            throw new MigrateSkipRowException(sprintf("Unknown adjustment type for line item '%s'.", $row
              ->getSourceProperty('line_item_id')));
          }

          // Scale the incoming price by the fraction digits.
          $fraction_digits = isset($value['price']['fraction_digits']) ? $value['price']['fraction_digits']['fraction_digits'] : '2';
          $input = [
            'amount' => $amount,
            'fraction_digits' => $fraction_digits,
            'currency_code' => $currency_code,
          ];
          $price_scaled = parent::transform($input, $migrate_executable, $row, NULL);
          $price = new Price((string) $price_scaled['number'], $price_scaled['currency_code']);
          $price = $this->rounder
            ->round($price);
          $num_product_line = $row
            ->getSourceProperty('num_product_line');
          $last_line = FALSE;
          if ($row
            ->getSourceProperty('line_item_id') == $row
            ->getSourceProperty('max_line_item_id')) {
            $last_line = TRUE;
          }
          $amount = $this
            ->split($num_product_line, $last_line, $price);
          if ($amount) {
            $adjustment = [
              'type' => $type,
              'label' => $label,
              'amount' => $amount
                ->getNumber(),
              'currency_code' => $amount
                ->getCurrencyCode(),
              'percentage' => $percentage,
              'source_id' => 'custom',
              'included' => FALSE,
              'locked' => TRUE,
            ];
          }
        }
      }
    }
    return $adjustment;
  }

  /**
   * Calculates the adjustment amount for this line.
   *
   * @param int $num_product_line
   *   The product line number.
   * @param bool $last_line
   *   TRUE if this is the last line of the order to process FALSE otherwise.
   * @param \Drupal\commerce_price\Price $price
   *   The price for this line.
   *
   * @return \Drupal\commerce_price\Price|null
   *   The new price for this line item. NULL if no line number was provided.
   */
  protected function split($num_product_line, $last_line, Price $price) {
    $individual_amount = NULL;
    if ($num_product_line > 0) {

      // Get the amount to add to each product line item.
      $percentage = 1 / $num_product_line;
      $percentage = new Price((string) $percentage, $price
        ->getCurrencyCode());

      // Calculate the initial per-order-item amounts using the percentage.
      // Round down to ensure that their sum isn't larger than the full amount.
      $individual_amount = $price
        ->multiply($percentage
        ->getNumber());
      $individual_amount = $this->rounder
        ->round($individual_amount, PHP_ROUND_HALF_DOWN);

      // Make any adjustments needed in the last line item for this order.
      if ($last_line) {
        $price_calculated = $individual_amount
          ->multiply($num_product_line);
        $difference = $price
          ->subtract($price_calculated);
        if (!$difference
          ->isZero()) {
          $individual_amount = $individual_amount
            ->add($difference);
        }
      }
    }
    return $individual_amount;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
OrderItemDiscountAdjustment::$currencyCode protected property The currency code.
OrderItemDiscountAdjustment::$entityTypeManager protected property The entity type manager.
OrderItemDiscountAdjustment::$migration protected property The migration to be executed.
OrderItemDiscountAdjustment::$migrationPluginManager protected property The migration plugin manager.
OrderItemDiscountAdjustment::$number protected property The number.
OrderItemDiscountAdjustment::$rounder protected property The rounder.
OrderItemDiscountAdjustment::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
OrderItemDiscountAdjustment::getAdjustment protected function Get the adjustments on this order item. 1
OrderItemDiscountAdjustment::split protected function Calculates the adjustment amount for this line. 1
OrderItemDiscountAdjustment::transform public function Performs the associated process. Overrides CommercePrice::transform
OrderItemDiscountAdjustment::__construct public function Constructs a MigrationLookup object. Overrides PluginBase::__construct
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 2
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.
ProcessPluginBase::multiple public function Indicates whether the returned value requires multiple handling. Overrides MigrateProcessInterface::multiple 3
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
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.