AllowedCountryValidationRule.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Quote\Model\ValidationRules;
  8. use Magento\Directory\Model\AllowedCountries;
  9. use Magento\Framework\Validation\ValidationResultFactory;
  10. use Magento\Quote\Model\Quote;
  11. use Magento\Store\Model\ScopeInterface;
  12. /**
  13. * @inheritdoc
  14. */
  15. class AllowedCountryValidationRule implements QuoteValidationRuleInterface
  16. {
  17. /**
  18. * @var string
  19. */
  20. private $generalMessage;
  21. /**
  22. * @var AllowedCountries
  23. */
  24. private $allowedCountryReader;
  25. /**
  26. * @var ValidationResultFactory
  27. */
  28. private $validationResultFactory;
  29. /**
  30. * @param AllowedCountries $allowedCountryReader
  31. * @param ValidationResultFactory $validationResultFactory
  32. * @param string $generalMessage
  33. */
  34. public function __construct(
  35. AllowedCountries $allowedCountryReader,
  36. ValidationResultFactory $validationResultFactory,
  37. string $generalMessage = ''
  38. ) {
  39. $this->allowedCountryReader = $allowedCountryReader;
  40. $this->validationResultFactory = $validationResultFactory;
  41. $this->generalMessage = $generalMessage;
  42. }
  43. /**
  44. * @inheritdoc
  45. */
  46. public function validate(Quote $quote): array
  47. {
  48. $validationErrors = [];
  49. if (!$quote->isVirtual()) {
  50. $shippingAddress = $quote->getShippingAddress();
  51. $shippingAddress->setStoreId($quote->getStoreId());
  52. $validationResult =
  53. in_array(
  54. $shippingAddress->getCountryId(),
  55. $this->allowedCountryReader->getAllowedCountries(
  56. ScopeInterface::SCOPE_STORE,
  57. $quote->getStoreId()
  58. )
  59. );
  60. if (!$validationResult) {
  61. $validationErrors = [__($this->generalMessage)];
  62. }
  63. }
  64. return [$this->validationResultFactory->create(['errors' => $validationErrors])];
  65. }
  66. }