You are here

public function PurchasedEntityAvailableConstraintValidator::validate in Commerce Core 8.2

File

modules/order/src/Plugin/Validation/Constraint/PurchasedEntityAvailableConstraintValidator.php, line 70

Class

PurchasedEntityAvailableConstraintValidator
Constraint validator for validating purchased entity availability.

Namespace

Drupal\commerce_order\Plugin\Validation\Constraint

Code

public function validate($value, Constraint $constraint) {
  assert($value instanceof EntityReferenceFieldItemListInterface);
  if ($value
    ->isEmpty()) {
    return;
  }
  $order_item = $value
    ->getEntity();
  assert($order_item instanceof OrderItemInterface);
  $purchased_entity = $order_item
    ->getPurchasedEntity();
  if (!$purchased_entity instanceof PurchasableEntityInterface) {

    // An invalid reference will be handled by the ValidReference constraint.
    return;
  }
  $order = $order_item
    ->getOrder();
  if (!$order instanceof OrderInterface) {

    // This may be a new order item that hasn't been assigned to an order yet,
    // so provide a default customer and store for the context.
    $customer = $this->currentUser;
    try {
      $store = $this
        ->selectStore($purchased_entity);
    } catch (\Exception $e) {
      $this->context
        ->addViolation($e
        ->getMessage());
      return;
    }
  }
  elseif ($order
    ->getState()
    ->getId() === 'draft') {
    $customer = $order
      ->getCustomer();
    $store = $order
      ->getStore();
  }
  else {

    // Do not process non-draft orders.
    return;
  }
  $quantity = $order_item
    ->getQuantity();
  $context = new Context($customer, $store);
  $availability_result = $this->availabilityManager
    ->check($order_item, $context);
  if ($availability_result
    ->isUnavailable()) {

    // If a reason is provided for the availability result, use it.
    if (!empty($availability_result
      ->getReason())) {
      $this->context
        ->buildViolation($availability_result
        ->getReason())
        ->addViolation();
    }
    else {

      // Otherwise fallback to the generic error message.
      $this->context
        ->buildViolation($constraint->message, [
        '%label' => $purchased_entity
          ->label(),
        '%quantity' => $quantity,
      ])
        ->addViolation();
    }
  }
}