EnumLookup.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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\Framework\GraphQl\Query;
  8. use Magento\Framework\GraphQl\Config\Element\Enum;
  9. use Magento\Framework\GraphQl\ConfigInterface;
  10. use Magento\Framework\GraphQl\Schema\Type\Enum\DataMapperInterface;
  11. use Magento\Framework\Phrase;
  12. /**
  13. * Processor that looks up definition data of an enum to lookup and convert data as it's specified in the schema.
  14. */
  15. class EnumLookup
  16. {
  17. /**
  18. * @var ConfigInterface
  19. */
  20. private $typeConfig;
  21. /**
  22. * @var DataMapperInterface
  23. */
  24. private $enumDataMapper;
  25. /**
  26. * @param ConfigInterface $typeConfig
  27. * @param DataMapperInterface $enumDataMapper
  28. */
  29. public function __construct(ConfigInterface $typeConfig, DataMapperInterface $enumDataMapper)
  30. {
  31. $this->typeConfig = $typeConfig;
  32. $this->enumDataMapper = $enumDataMapper;
  33. }
  34. /**
  35. * Convert a field value from a db query to an enum value declared as an item in the graphql schema
  36. *
  37. * @param string $enumName
  38. * @param string $fieldValue
  39. * @return string
  40. * @throws \Magento\Framework\Exception\RuntimeException
  41. */
  42. public function getEnumValueFromField(string $enumName, string $fieldValue) : string
  43. {
  44. $priceViewEnum = $this->typeConfig->getConfigElement($enumName);
  45. if ($priceViewEnum instanceof Enum) {
  46. foreach ($priceViewEnum->getValues() as $enumItem) {
  47. $mappedValues = $this->enumDataMapper->getMappedEnums($enumName);
  48. if (isset($mappedValues[$enumItem->getName()]) && $mappedValues[$enumItem->getName()] == $fieldValue) {
  49. return $enumItem->getValue();
  50. }
  51. }
  52. } else {
  53. throw new \Magento\Framework\Exception\RuntimeException(
  54. new Phrase('Enum type "%1" not defined', [$enumName])
  55. );
  56. }
  57. return '';
  58. }
  59. }