|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | +declare(strict_types=1); |
| 7 | + |
| 8 | +namespace Magento\QuoteGraphQlPwa\Model\Resolver; |
| 9 | + |
| 10 | +use Magento\Framework\Exception\LocalizedException; |
| 11 | +use Magento\Framework\GraphQl\Config\Element\Field; |
| 12 | +use Magento\Framework\GraphQl\Query\ResolverInterface; |
| 13 | +use Magento\Framework\GraphQl\Query\EnumLookup; |
| 14 | +use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; |
| 15 | +use Magento\Quote\Model\Quote\Item; |
| 16 | + |
| 17 | +/** |
| 18 | + * @inheritdoc |
| 19 | + */ |
| 20 | +class CartItemErrors implements ResolverInterface |
| 21 | +{ |
| 22 | + public const ERROR_UNDEFINED = 0; |
| 23 | + |
| 24 | + /** @var \Magento\Framework\GraphQl\Query\EnumLookup */ |
| 25 | + private $enumLookup; |
| 26 | + |
| 27 | + /** |
| 28 | + * @param \Magento\Framework\GraphQl\Query\EnumLookup $enumLookup |
| 29 | + */ |
| 30 | + public function __construct( |
| 31 | + EnumLookup $enumLookup |
| 32 | + ) { |
| 33 | + $this->enumLookup = $enumLookup; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * @inheritdoc |
| 38 | + */ |
| 39 | + public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null) |
| 40 | + { |
| 41 | + if (!isset($value['model'])) { |
| 42 | + throw new LocalizedException(__('"model" value should be specified')); |
| 43 | + } |
| 44 | + /** @var Item $cartItem */ |
| 45 | + $cartItem = $value['model']; |
| 46 | + |
| 47 | + return $this->getItemErrors($cartItem); |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Get error messages for cart item |
| 52 | + * |
| 53 | + * @param \Magento\Quote\Model\Quote\Item $cartItem |
| 54 | + * |
| 55 | + * @return string[]|null |
| 56 | + * @throws \Magento\Framework\Exception\RuntimeException |
| 57 | + */ |
| 58 | + private function getItemErrors(Item $cartItem): ?array |
| 59 | + { |
| 60 | + $hasError = (bool) $cartItem->getData('has_error'); |
| 61 | + if (!$hasError) { |
| 62 | + return null; |
| 63 | + } |
| 64 | + |
| 65 | + $errors = []; |
| 66 | + foreach ($cartItem->getErrorInfos() as $error) { |
| 67 | + $errorType = $error['code'] ?? self::ERROR_UNDEFINED; |
| 68 | + $errorEnumCode = $this->enumLookup->getEnumValueFromField( |
| 69 | + 'CartItemErrorType', |
| 70 | + (string)$errorType |
| 71 | + ); |
| 72 | + $errors[] = [ |
| 73 | + 'code' => $errorEnumCode, |
| 74 | + 'message' => $error['message'] |
| 75 | + ]; |
| 76 | + } |
| 77 | + |
| 78 | + return $errors; |
| 79 | + } |
| 80 | +} |
0 commit comments