|
| 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\EavGraphQl\Model\Resolver; |
| 9 | + |
| 10 | +use Magento\Eav\Api\AttributeOptionManagementInterface; |
| 11 | +use Magento\Framework\GraphQl\Config\Element\Field; |
| 12 | +use Magento\Framework\GraphQl\Query\Resolver\Value; |
| 13 | +use Magento\Framework\GraphQl\Query\Resolver\ValueFactory; |
| 14 | +use Magento\Framework\GraphQl\Query\ResolverInterface; |
| 15 | +use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; |
| 16 | + |
| 17 | +/** |
| 18 | + * Resolve attribute options data for custom attribute. |
| 19 | + */ |
| 20 | +class AttributeOptions implements ResolverInterface |
| 21 | +{ |
| 22 | + /** |
| 23 | + * @var AttributeOptionManagementInterface |
| 24 | + */ |
| 25 | + protected $optionManager; |
| 26 | + |
| 27 | + /** |
| 28 | + * @var ValueFactory |
| 29 | + */ |
| 30 | + protected $valueFactory; |
| 31 | + |
| 32 | + /** |
| 33 | + * AttributeOptions constructor. |
| 34 | + * |
| 35 | + * @param AttributeOptionManagementInterface $optionManager |
| 36 | + * @param ValueFactory $valueFactory |
| 37 | + */ |
| 38 | + public function __construct( |
| 39 | + AttributeOptionManagementInterface $optionManager, |
| 40 | + ValueFactory $valueFactory |
| 41 | + ) { |
| 42 | + $this->optionManager = $optionManager; |
| 43 | + $this->valueFactory = $valueFactory; |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * {@inheritDoc} |
| 48 | + */ |
| 49 | + public function resolve( |
| 50 | + Field $field, |
| 51 | + $context, |
| 52 | + ResolveInfo $info, |
| 53 | + array $value = null, |
| 54 | + array $args = null |
| 55 | + ) : Value { |
| 56 | + $options = []; |
| 57 | + |
| 58 | + $entityType = !empty($value['entity_type']) ? $value['entity_type'] : ''; |
| 59 | + $attributeCode = !empty($value['attribute_code']) ? $value['attribute_code'] : ''; |
| 60 | + |
| 61 | + try { |
| 62 | + /** @var \Magento\Eav\Api\Data\AttributeOptionInterface[] $attributeOptions */ |
| 63 | + $attributeOptions = $this->optionManager->getItems($entityType, $attributeCode); |
| 64 | + } catch (\Exception $e) { |
| 65 | + $attributeOptions = []; |
| 66 | + } |
| 67 | + |
| 68 | + if (is_array($attributeOptions)) { |
| 69 | + /** @var \Magento\Eav\Api\Data\AttributeOptionInterface $option */ |
| 70 | + foreach ($attributeOptions as $option) { |
| 71 | + if (!$option->getValue()) { |
| 72 | + continue; |
| 73 | + } |
| 74 | + |
| 75 | + $options[] = [ |
| 76 | + 'label' => $option->getLabel(), |
| 77 | + 'value' => $option->getValue() |
| 78 | + ]; |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + $result = function () use ($options) { |
| 83 | + return $options; |
| 84 | + }; |
| 85 | + |
| 86 | + return $this->valueFactory->create($result); |
| 87 | + } |
| 88 | +} |
0 commit comments