|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright 2025 Adobe |
| 4 | + * All Rights Reserved. |
| 5 | + */ |
| 6 | +declare(strict_types=1); |
| 7 | + |
| 8 | +namespace Magento\QuoteGraphQl\Plugin; |
| 9 | + |
| 10 | +use Magento\Quote\Model\ValidationRules\ShippingMethodValidationRule; |
| 11 | +use Magento\Quote\Model\Quote; |
| 12 | +use Magento\Framework\Validation\ValidationResult; |
| 13 | +use Magento\Framework\Validation\ValidationResultFactory; |
| 14 | + |
| 15 | +class ShippingMethodValidationRulePlugin |
| 16 | +{ |
| 17 | + /** |
| 18 | + * @var ValidationResultFactory |
| 19 | + */ |
| 20 | + private $validationResultFactory; |
| 21 | + |
| 22 | + /** |
| 23 | + * @param ValidationResultFactory $validationResultFactory |
| 24 | + */ |
| 25 | + public function __construct(ValidationResultFactory $validationResultFactory) |
| 26 | + { |
| 27 | + $this->validationResultFactory = $validationResultFactory; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * After plugin for validate method to ensure shipping method validity. |
| 32 | + * |
| 33 | + * @param ShippingMethodValidationRule $subject |
| 34 | + * @param ValidationResult[] $result |
| 35 | + * @param Quote $quote |
| 36 | + * @return ValidationResult[] |
| 37 | + */ |
| 38 | + public function afterValidate( |
| 39 | + ShippingMethodValidationRule $subject, |
| 40 | + array $result, |
| 41 | + Quote $quote |
| 42 | + ): array { |
| 43 | + $shippingAddress = $quote->getShippingAddress(); |
| 44 | + if (!$shippingAddress || $quote->isVirtual()) { |
| 45 | + return $result; |
| 46 | + } |
| 47 | + |
| 48 | + $shippingMethod = $shippingAddress->getShippingMethod(); |
| 49 | + $shippingRate = $shippingMethod ? $shippingAddress->getShippingRateByCode($shippingMethod) : null; |
| 50 | + $validationResult = $shippingMethod && $shippingRate && $shippingAddress->requestShippingRates(); |
| 51 | + |
| 52 | + if ($validationResult) { |
| 53 | + return $result; |
| 54 | + } |
| 55 | + |
| 56 | + // If previously valid, rebuild with a generic error to mark invalid |
| 57 | + $existing = $result[0] ?? null; |
| 58 | + if ($existing instanceof ValidationResult && $existing->isValid()) { |
| 59 | + $result[0] = $this->validationResultFactory->create([ |
| 60 | + 'errors' => [__('The shipping method is missing. Select the shipping method and try again')] |
| 61 | + ]); |
| 62 | + } |
| 63 | + |
| 64 | + return $result; |
| 65 | + } |
| 66 | +} |
0 commit comments