AttributesJoiner.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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\CatalogGraphQl\Model;
  8. use GraphQL\Language\AST\FieldNode;
  9. use Magento\Eav\Model\Entity\Collection\AbstractCollection;
  10. /**
  11. * Joins attributes for provided field node field names.
  12. */
  13. class AttributesJoiner
  14. {
  15. /**
  16. * @var array
  17. */
  18. private $queryFields = [];
  19. /**
  20. * Join fields attached to field node to collection's select.
  21. *
  22. * @param FieldNode $fieldNode
  23. * @param AbstractCollection $collection
  24. * @return void
  25. */
  26. public function join(FieldNode $fieldNode, AbstractCollection $collection) : void
  27. {
  28. foreach ($this->getQueryFields($fieldNode) as $field) {
  29. if (!$collection->isAttributeAdded($field)) {
  30. $collection->addAttributeToSelect($field);
  31. }
  32. }
  33. }
  34. /**
  35. * Get an array of queried fields.
  36. *
  37. * @param FieldNode $fieldNode
  38. * @return string[]
  39. */
  40. public function getQueryFields(FieldNode $fieldNode)
  41. {
  42. if (!isset($this->queryFields[$fieldNode->name->value])) {
  43. $this->queryFields[$fieldNode->name->value] = [];
  44. $query = $fieldNode->selectionSet->selections;
  45. /** @var FieldNode $field */
  46. foreach ($query as $field) {
  47. if ($field->kind === 'InlineFragment') {
  48. continue;
  49. }
  50. $this->queryFields[$fieldNode->name->value][] = $field->name->value;
  51. }
  52. }
  53. return $this->queryFields[$fieldNode->name->value];
  54. }
  55. }