You are here

public function Adjustment::__construct in Commerce Core 8.2

Constructs a new Adjustment object.

Parameters

array $definition: The definition.

File

modules/order/src/Adjustment.php, line 70

Class

Adjustment
Represents an adjustment.

Namespace

Drupal\commerce_order

Code

public function __construct(array $definition) {
  foreach ([
    'type',
    'label',
    'amount',
  ] as $required_property) {
    if (empty($definition[$required_property])) {
      throw new \InvalidArgumentException(sprintf('Missing required property %s.', $required_property));
    }
  }
  if (!$definition['amount'] instanceof Price) {
    throw new \InvalidArgumentException(sprintf('Property "amount" should be an instance of %s.', Price::class));
  }
  $adjustment_type_manager = \Drupal::service('plugin.manager.commerce_adjustment_type');
  $types = $adjustment_type_manager
    ->getDefinitions();
  if (empty($types[$definition['type']])) {
    throw new \InvalidArgumentException(sprintf('%s is an invalid adjustment type.', $definition['type']));
  }
  if (isset($definition['percentage'])) {
    if (is_float($definition['percentage'])) {
      throw new \InvalidArgumentException(sprintf('The provided percentage "%s" must be a string, not a float.', $definition['percentage']));
    }
    if (!is_numeric($definition['percentage'])) {
      throw new \InvalidArgumentException(sprintf('The provided percentage "%s" is not a numeric value.', $definition['percentage']));
    }
  }

  // Assume that 'custom' adjustments are always locked, for BC reasons.
  if ($definition['type'] == 'custom' && !isset($definition['locked'])) {
    $definition['locked'] = TRUE;
  }
  $this->type = $definition['type'];
  $this->label = (string) $definition['label'];
  $this->amount = $definition['amount'];
  $this->percentage = isset($definition['percentage']) ? $definition['percentage'] : NULL;
  $this->sourceId = !empty($definition['source_id']) ? $definition['source_id'] : NULL;
  $this->included = !empty($definition['included']);
  $this->locked = !empty($definition['locked']);
}