@@ -20,6 +20,24 @@ class AttributesJoiner
2020 */
2121 private $ queryFields = [];
2222
23+ /**
24+ * Field to attribute mapping
25+ *
26+ * For fields that are not named the same as their attribute, or require extra attributes to resolve
27+ * e.g. ['field' => ['attr1', 'attr2'], 'other_field' => ['other_attr']]
28+ *
29+ * @var array
30+ */
31+ private $ fieldToAttributeMap = [];
32+
33+ /**
34+ * @param array $fieldToAttributeMap
35+ */
36+ public function __construct (array $ fieldToAttributeMap = [])
37+ {
38+ $ this ->fieldToAttributeMap = $ fieldToAttributeMap ;
39+ }
40+
2341 /**
2442 * Join fields attached to field node to collection's select.
2543 *
@@ -30,9 +48,7 @@ class AttributesJoiner
3048 public function join (FieldNode $ fieldNode , AbstractCollection $ collection ) : void
3149 {
3250 foreach ($ this ->getQueryFields ($ fieldNode ) as $ field ) {
33- if (!$ collection ->isAttributeAdded ($ field )) {
34- $ collection ->addAttributeToSelect ($ field );
35- }
51+ $ this ->addFieldToCollection ($ collection , $ field );
3652 }
3753 }
3854
@@ -42,7 +58,7 @@ public function join(FieldNode $fieldNode, AbstractCollection $collection) : voi
4258 * @param FieldNode $fieldNode
4359 * @return string[]
4460 */
45- public function getQueryFields (FieldNode $ fieldNode )
61+ public function getQueryFields (FieldNode $ fieldNode ): array
4662 {
4763 if (!isset ($ this ->queryFields [$ fieldNode ->name ->value ])) {
4864 $ this ->queryFields [$ fieldNode ->name ->value ] = [];
@@ -58,4 +74,29 @@ public function getQueryFields(FieldNode $fieldNode)
5874
5975 return $ this ->queryFields [$ fieldNode ->name ->value ];
6076 }
77+
78+ /**
79+ * Add field to collection select
80+ *
81+ * Add a query field to the collection, using mapped attribute names if they are set
82+ *
83+ * @param AbstractCollection $collection
84+ * @param string $field
85+ */
86+ private function addFieldToCollection (AbstractCollection $ collection , string $ field )
87+ {
88+ $ attribute = isset ($ this ->fieldToAttributeMap [$ field ]) ? $ this ->fieldToAttributeMap [$ field ] : $ field ;
89+
90+ if (is_array ($ attribute )) {
91+ foreach ($ attribute as $ attributeName ) {
92+ if (!$ collection ->isAttributeAdded ($ attributeName )) {
93+ $ collection ->addAttributeToSelect ($ attributeName );
94+ }
95+ }
96+ } else {
97+ if (!$ collection ->isAttributeAdded ($ attribute )) {
98+ $ collection ->addAttributeToSelect ($ attribute );
99+ }
100+ }
101+ }
61102}
0 commit comments