EnumFactory.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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\Config\Element;
  8. use Magento\Framework\GraphQl\Config\ConfigElementFactoryInterface;
  9. use Magento\Framework\GraphQl\Config\ConfigElementInterface;
  10. use Magento\Framework\ObjectManagerInterface;
  11. /**
  12. * {@inheritdoc}
  13. */
  14. class EnumFactory implements ConfigElementFactoryInterface
  15. {
  16. /**
  17. * @var ObjectManagerInterface
  18. */
  19. private $objectManager;
  20. /**
  21. * @var EnumValueFactory
  22. */
  23. private $enumValueFactory;
  24. /**
  25. * @param ObjectManagerInterface $objectManager
  26. * @param EnumValueFactory $enumValueFactory
  27. */
  28. public function __construct(
  29. ObjectManagerInterface $objectManager,
  30. EnumValueFactory $enumValueFactory
  31. ) {
  32. $this->objectManager = $objectManager;
  33. $this->enumValueFactory = $enumValueFactory;
  34. }
  35. /**
  36. * Create an enum based off a configured enum type. Name and values required.
  37. *
  38. * @param string $name
  39. * @param EnumValue[] $values
  40. * @param string $description
  41. * @return Enum
  42. */
  43. public function create(string $name, array $values, string $description = ''): Enum
  44. {
  45. return $this->objectManager->create(
  46. Enum::class,
  47. [
  48. 'name' => $name,
  49. 'values' => $values,
  50. 'description' => $description
  51. ]
  52. );
  53. }
  54. /**
  55. * Instantiate an object representing 'enum' GraphQL config element.
  56. *
  57. * @param array $data
  58. * @return ConfigElementInterface
  59. */
  60. public function createFromConfigData(array $data): ConfigElementInterface
  61. {
  62. $values = [];
  63. foreach ($data['items'] as $item) {
  64. $values[$item['_value']] = $this->enumValueFactory->create(
  65. $item['name'],
  66. $item['_value'],
  67. isset($item['description']) ? $item['description'] : ''
  68. );
  69. }
  70. return $this->create(
  71. $data['name'],
  72. $values,
  73. isset($data['description']) ? $data['description'] : ''
  74. );
  75. }
  76. }