You are here

public function CurrencyConstraintValidator::validate in Price 3.x

Same name and namespace in other branches
  1. 8 src/Plugin/Validation/Constraint/CurrencyConstraintValidator.php \Drupal\price\Plugin\Validation\Constraint\CurrencyConstraintValidator::validate()
  2. 2.0.x src/Plugin/Validation/Constraint/CurrencyConstraintValidator.php \Drupal\price\Plugin\Validation\Constraint\CurrencyConstraintValidator::validate()
  3. 2.x src/Plugin/Validation/Constraint/CurrencyConstraintValidator.php \Drupal\price\Plugin\Validation\Constraint\CurrencyConstraintValidator::validate()
  4. 3.0.x src/Plugin/Validation/Constraint/CurrencyConstraintValidator.php \Drupal\price\Plugin\Validation\Constraint\CurrencyConstraintValidator::validate()

File

src/Plugin/Validation/Constraint/CurrencyConstraintValidator.php, line 45

Class

CurrencyConstraintValidator
Validates the currency constraint.

Namespace

Drupal\price\Plugin\Validation\Constraint

Code

public function validate($value, Constraint $constraint) {

  //    if (!($value instanceof PriceItem)) {
  //      throw new UnexpectedTypeException($value, PriceItem::class);
  //    }
  $price_item = $value;
  $currency_code = $price_item
    ->get('currency_code')
    ->getValue();
  if ($currency_code === NULL || $currency_code === '') {
    return;
  }
  $currencies = $this->entityTypeManager
    ->getStorage('price_currency')
    ->loadMultiple();
  if (!isset($currencies[$currency_code])) {
    $this->context
      ->buildViolation($constraint->invalidMessage)
      ->atPath('currency_code')
      ->setParameter('%value', $this
      ->formatValue($currency_code))
      ->addViolation();
    return;
  }
  $available_currencies = $constraint->availableCurrencies;
  if (!empty($available_currencies) && !in_array($currency_code, $available_currencies)) {
    $this->context
      ->buildViolation($constraint->notAvailableMessage)
      ->atPath('currency_code')
      ->setParameter('%value', $this
      ->formatValue($currency_code))
      ->addViolation();
  }
}