FieldFactory.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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\ObjectManagerInterface;
  9. /**
  10. * Factory for config elements of 'field' type.
  11. */
  12. class FieldFactory
  13. {
  14. /**
  15. * @var ObjectManagerInterface
  16. */
  17. private $objectManager;
  18. /**
  19. * @param ObjectManagerInterface $objectManager
  20. */
  21. public function __construct(
  22. ObjectManagerInterface $objectManager
  23. ) {
  24. $this->objectManager = $objectManager;
  25. }
  26. /**
  27. * Create a field object from a configured array with optional arguments.
  28. *
  29. * Field data must contain name and type. Other values are optional and include required, itemType, description,
  30. * and resolver. Arguments array must be in the format of [$argumentData['name'] => $argumentData].
  31. *
  32. * @param array $fieldData
  33. * @param array $arguments
  34. * @return Field
  35. */
  36. public function createFromConfigData(
  37. array $fieldData,
  38. array $arguments = []
  39. ) : Field {
  40. $fieldType = $fieldData['type'];
  41. $isList = false;
  42. //check if type ends with []
  43. if ($fieldType{strlen($fieldType) - 2} == '[' && $fieldType{strlen($fieldType) - 1} == ']') {
  44. $isList = true;
  45. $fieldData['type'] = str_replace('[]', '', $fieldData['type']);
  46. $fieldData['itemType'] = str_replace('[]', '', $fieldData['type']);
  47. }
  48. return $this->objectManager->create(
  49. Field::class,
  50. [
  51. 'name' => $fieldData['name'],
  52. 'type' => $fieldData['type'],
  53. 'required' => isset($fieldData['required']) ? $fieldData['required'] : false,
  54. 'isList' => isset($fieldData['itemType']) || $isList,
  55. 'itemType' => isset($fieldData['itemType']) ? $fieldData['itemType'] : '',
  56. 'resolver' => isset($fieldData['resolver']) ? $fieldData['resolver'] : '',
  57. 'description' => isset($fieldData['description']) ? $fieldData['description'] : '',
  58. 'arguments' => $arguments
  59. ]
  60. );
  61. }
  62. }