Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
QuoteValidator.php
Go to the documentation of this file.
1 <?php
7 namespace Magento\Quote\Model;
8 
16 
24 {
28  const MAXIMUM_AVAILABLE_NUMBER = 99999999;
29 
33  private $allowedCountryReader;
34 
38  private $minimumAmountMessage;
39 
43  private $quoteValidationRule;
44 
52  public function __construct(
53  AllowedCountries $allowedCountryReader = null,
54  OrderAmountValidationMessage $minimumAmountMessage = null,
55  QuoteValidationRuleInterface $quoteValidationRule = null
56  ) {
57  $this->allowedCountryReader = $allowedCountryReader ?: ObjectManager::getInstance()
58  ->get(AllowedCountries::class);
59  $this->minimumAmountMessage = $minimumAmountMessage ?: ObjectManager::getInstance()
60  ->get(OrderAmountValidationMessage::class);
61  $this->quoteValidationRule = $quoteValidationRule ?: ObjectManager::getInstance()
62  ->get(QuoteValidationRuleInterface::class);
63  }
64 
73  {
74  if (!$quote->getHasError() && $amount >= self::MAXIMUM_AVAILABLE_NUMBER) {
75  $quote->setHasError(true);
76  $quote->addMessage(__('This item price or quantity is not valid for checkout.'));
77  }
78 
79  return $this;
80  }
81 
90  {
91  if ($quote->getHasError()) {
92  $errors = $this->getQuoteErrors($quote);
93  throw new LocalizedException(__($errors ?: 'Something went wrong. Please try to place the order again.'));
94  }
95 
96  foreach ($this->quoteValidationRule->validate($quote) as $validationResult) {
97  if ($validationResult->isValid()) {
98  continue;
99  }
100 
101  $messages = $validationResult->getErrors();
102  $defaultMessage = array_shift($messages);
103  if ($defaultMessage && !empty($messages)) {
104  $defaultMessage .= ' %1';
105  }
106  if ($defaultMessage) {
107  throw new LocalizedException(__($defaultMessage, implode(' ', $messages)));
108  }
109  }
110 
111  return $this;
112  }
113 
120  private function getQuoteErrors(QuoteEntity $quote): string
121  {
122  $errors = array_map(
123  function (Error $error) {
124  return $error->getText();
125  },
126  $quote->getErrors()
127  );
128 
129  return implode(PHP_EOL, $errors);
130  }
131 }
validateBeforeSubmit(QuoteEntity $quote)
$quote
__()
Definition: __.php:13
$amount
Definition: order.php:14
validateQuoteAmount(QuoteEntity $quote, $amount)
__construct(AllowedCountries $allowedCountryReader=null, OrderAmountValidationMessage $minimumAmountMessage=null, QuoteValidationRuleInterface $quoteValidationRule=null)
$errors
Definition: overview.phtml:9