AttributeReader.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\CatalogGraphQl\Model\Config;
  7. use Magento\Framework\Config\ReaderInterface;
  8. use Magento\Framework\GraphQl\Exception\GraphQlInputException;
  9. use Magento\Framework\GraphQl\Schema\Type\Entity\MapperInterface;
  10. use Magento\Framework\Reflection\TypeProcessor;
  11. use Magento\EavGraphQl\Model\Resolver\Query\Type;
  12. use Magento\CatalogGraphQl\Model\Resolver\Products\Attributes\Collection;
  13. /**
  14. * Adds custom/eav attribute to Catalog product types in the GraphQL config.
  15. */
  16. class AttributeReader implements ReaderInterface
  17. {
  18. /**
  19. * @var MapperInterface
  20. */
  21. private $mapper;
  22. /**
  23. * @var Type
  24. */
  25. private $typeLocator;
  26. /**
  27. * @var Collection
  28. */
  29. private $collection;
  30. /**
  31. * @param MapperInterface $mapper
  32. * @param Type $typeLocator
  33. * @param Collection $collection
  34. */
  35. public function __construct(
  36. MapperInterface $mapper,
  37. Type $typeLocator,
  38. Collection $collection
  39. ) {
  40. $this->mapper = $mapper;
  41. $this->typeLocator = $typeLocator;
  42. $this->collection = $collection;
  43. }
  44. /**
  45. * Read configuration scope
  46. *
  47. * @param string|null $scope
  48. * @return array
  49. * @throws GraphQlInputException
  50. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  51. */
  52. public function read($scope = null) : array
  53. {
  54. $typeNames = $this->mapper->getMappedTypes(\Magento\Catalog\Model\Product::ENTITY);
  55. $config =[];
  56. /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
  57. foreach ($this->collection->getAttributes() as $attribute) {
  58. $attributeCode = $attribute->getAttributeCode();
  59. $locatedType = $this->typeLocator->getType(
  60. $attributeCode,
  61. \Magento\Catalog\Model\Product::ENTITY
  62. ) ?: 'String';
  63. $locatedType = $locatedType === TypeProcessor::NORMALIZED_ANY_TYPE ? 'String' : ucfirst($locatedType);
  64. foreach ($typeNames as $typeName) {
  65. $config[$typeName]['fields'][$attributeCode] = [
  66. 'name' => $attributeCode,
  67. 'type' => $locatedType,
  68. 'arguments' => []
  69. ];
  70. }
  71. }
  72. return $config;
  73. }
  74. }